From 95fdf9491231a02010c25e902f1dc9637733c2b1 Mon Sep 17 00:00:00 2001 From: 4DBug <4DBug@github.com> Date: Wed, 14 Oct 2026 10:23:55 -0500 Subject: [PATCH] Comments: mirror upstream imgui.cpp/.h, imgui_internal.h, widgets/draw/tables/demo and imstb_* comments (comment-only, code tokens unchanged) --- build/ImGui.linemap.json | 2 +- build/ImGui.luau | 12776 ++++++++++++++++++++++++------- build/imgui_love.linemap.json | 2 +- build/imgui_love.lua | 12782 +++++++++++++++++++++++++------- imgui.lua | 3868 ++++++++-- imgui_demo.lua | 1495 +++- imgui_draw.lua | 734 +- imgui_h.lua | 1870 +++-- imgui_internal.lua | 1498 ++-- imgui_tables.lua | 816 +- imgui_widgets.lua | 1456 +++- imstb_rectpack.lua | 240 +- imstb_textedit.lua | 371 +- imstb_truetype.lua | 428 +- 14 files changed, 30451 insertions(+), 7887 deletions(-) diff --git a/build/ImGui.linemap.json b/build/ImGui.linemap.json index ba5877b..aa9b712 100644 --- a/build/ImGui.linemap.json +++ b/build/ImGui.linemap.json @@ -1 +1 @@ -[[12, "imgui.lua"], [18514, "imgui_demo.lua"], [25799, "imgui_draw.lua"], [31037, "imgui_h.lua"], [33235, "imgui_impl_roblox.lua"], [34587, "imgui_impl_roblox_fonts.lua"], [40990, "imgui_internal.lua"], [44166, "imgui_tables.lua"], [48513, "imgui_widgets.lua"], [58268, "imstb_rectpack.lua"], [58714, "imstb_textedit.lua"], [59955, "imstb_truetype.lua"], [62423, "imstd_minstdio.lua"]] \ No newline at end of file +[[12, "imgui.lua"], [21288, "imgui_demo.lua"], [29706, "imgui_draw.lua"], [35476, "imgui_h.lua"], [38142, "imgui_impl_roblox.lua"], [39494, "imgui_impl_roblox_fonts.lua"], [45897, "imgui_internal.lua"], [49343, "imgui_tables.lua"], [54338, "imgui_widgets.lua"], [64949, "imstb_rectpack.lua"], [65613, "imstb_textedit.lua"], [67155, "imstb_truetype.lua"], [69943, "imstd_minstdio.lua"]] \ No newline at end of file diff --git a/build/ImGui.luau b/build/ImGui.luau index 55d6f89..2104390 100644 --- a/build/ImGui.luau +++ b/build/ImGui.luau @@ -9,6 +9,422 @@ function IM_INCLUDE(name) end __FILES['imgui.lua'] = function() +-- dear imgui, v1.93 WIP (Luau port) +-- (main code and documentation) + +-- This file is a Lua/Luau port of Dear ImGui's imgui.cpp (docking branch, 1.93 WIP), following imgui.cpp function by function. +-- It runs on Roblox (Luau, primary target) and LÖVE (LuaJIT). Upstream documentation, examples and the demo apply almost directly. + +-- Help: +-- - Call and read ImGui.ShowDemoWindow() in imgui_demo.lua. All applications in examples/ are doing that. +-- - Read top of imgui.lua for more details, links and comments. +-- - ImVec2 and ImVec4 have arithmetic metamethods (a + b, a * 2.0, etc.); fields are .x, .y (.z, .w). +-- - See README.md "Differences from C++ Dear ImGui" for the Luau conventions (out-params become return values, flags enums, text buffers). + +-- Resources: +-- - FAQ ........................ https://dearimgui.com/faq (in upstream repository as docs/FAQ.md) +-- - Homepage ................... https://github.com/ocornut/imgui +-- - Releases & Changelog ....... https://github.com/ocornut/imgui/releases +-- - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!) +-- - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) +-- - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) +-- - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) +-- - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings + backends for various tech/engines) +-- - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools +-- - Glossary https://github.com/ocornut/imgui/wiki/Glossary +-- - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui +-- - Issues & support ........... https://github.com/ocornut/imgui/issues (upstream; for issues specific to this port, use this port's repository) +-- - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) +-- - Web version of the Demo .... https://pthom.github.io/imgui_explorer (w/ source code browser) + +-- Copyright (c) 2014-2026 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. +-- Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts. +-- PLEASE reach out at omar AT discohello DOT com. See https://github.com/ocornut/imgui/wiki/Funding +-- Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine. +-- This port is unofficial and not affiliated with the Dear ImGui project; it is distributed under the same license. + +-- It is recommended that you don't modify imgui.lua! It will become difficult for you to update the library. +-- Note that 'ImGui' being a plain table, you can add functions into it from your own source files, without +-- modifying imgui.lua. You may use the internal functions and data structures (imgui_internal.lua), but they don't +-- come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you +-- to a better solution or official support for them. + +-- +-- Index of this file: +-- +-- DOCUMENTATION +-- +-- - MISSION STATEMENT +-- - CONTROLS GUIDE +-- - PROGRAMMER GUIDE +-- - READ FIRST +-- - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI +-- - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE +-- - HOW A SIMPLE APPLICATION 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) +-- +-- CODE +-- (search for "[SECTION]" in the code to find them) +-- +-- [SECTION] INCLUDES +-- [SECTION] FORWARD DECLARATIONS +-- [SECTION] CONTEXT AND MEMORY ALLOCATORS +-- [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO) +-- [SECTION] MISC HELPERS/UTILITIES (Geometry functions) +-- [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) +-- [SECTION] MISC HELPERS/UTILITIES (File functions) +-- [SECTION] MISC HELPERS/UTILITIES (ImText* functions) +-- [SECTION] MISC HELPERS/UTILITIES (Color functions) +-- [SECTION] ImGuiStorage +-- [SECTION] ImGuiTextFilter +-- [SECTION] ImGuiTextBuffer, ImGuiTextIndex +-- [SECTION] ImGuiListClipper +-- [SECTION] STYLING +-- [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 +-- [SECTION] ITEM SUBMISSION +-- [SECTION] LAYOUT +-- [SECTION] SCROLLING +-- [SECTION] TOOLTIPS +-- [SECTION] POPUPS +-- [SECTION] WINDOW FOCUS +-- [SECTION] KEYBOARD/GAMEPAD NAVIGATION +-- [SECTION] DRAG AND DROP +-- [SECTION] LOGGING/CAPTURING +-- [SECTION] SETTINGS +-- [SECTION] LOCALIZATION +-- [SECTION] VIEWPORTS, PLATFORM WINDOWS +-- [SECTION] DOCKING +-- [SECTION] PLATFORM DEPENDENT HELPERS +-- [SECTION] METRICS/DEBUGGER WINDOW +-- [SECTION] DEBUG LOG WINDOW +-- [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL) +-- +-- (In this port, the sections keep upstream's names but may appear in a different order: +-- e.g. DRAG AND DROP and DOCKING are near the top of imgui.lua. Some are partial or empty, see docs/TODO.txt.) +-- + +------------------------------------------------------------------------------- +-- DOCUMENTATION +------------------------------------------------------------------------------- + +-- +-- MISSION STATEMENT +-- ================= +-- +-- - Easy to use to create code-driven and data-driven tools. +-- - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools. +-- - Easy to hack and improve. +-- - Minimize setup and maintenance. +-- - Minimize state storage on user side. +-- - Minimize state synchronization. +-- - Portable, minimize dependencies, run on target (consoles, phones, etc.). +-- - Efficient runtime and memory consumption. +-- +-- Designed primarily for developers and content-creators, not the typical end-user! +-- Some of the current weaknesses (which we aim to address in the future) includes: +-- +-- - Doesn't look fancy by default. +-- - Limited layout features, intricate layouts are typically crafted in code. +-- +-- +-- CONTROLS GUIDE +-- ============== +-- +-- - MOUSE CONTROLS +-- - Mouse wheel: Scroll vertically. +-- - Shift+Mouse wheel: Scroll horizontally. +-- - Click [X]: Close a window, available when an 'open' value is passed to ImGui.Begin() (open = ImGui.Begin(name, open)). +-- - Click ^, Double-Click title: Collapse window. +-- - Drag on corner/border: Resize window (double-click to auto fit window to its contents). +-- - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true). +-- - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack). +-- +-- - TEXT EDITOR +-- - Hold Shift or Drag Mouse: Select text. +-- - Ctrl+Left/Right: Word jump. +-- - Ctrl+Shift+Left/Right: Select words. +-- - Ctrl+A or Double-Click: Select All. +-- - Ctrl+X, Ctrl+C, Ctrl+V: Use OS clipboard (on Roblox, requires ImGui_ImplRoblox.SetTextProxy(true)). +-- - Ctrl+Z Undo. +-- - Ctrl+Y or Ctrl+Shift+Z: Redo. +-- - ESCAPE: Revert text to its original value. +-- - On macOS, controls are automatically adjusted to match standard macOS text editing and behaviors. +-- (for 99% of shortcuts, Ctrl is replaced by Cmd on macOS). +-- +-- - KEYBOARD CONTROLS +-- - Basic: +-- - Tab, Shift+Tab Cycle through text editable fields. +-- - Ctrl+Tab, Ctrl+Shift+Tab Cycle through windows. +-- - Ctrl+Click Input text into a Slider or Drag widget. +-- - Extended features with `io.ConfigFlags = bit32.bor(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard)`: +-- - Tab, Shift+Tab: Cycle through every items. +-- - Arrow keys Move through items using directional navigation. Tweak value. +-- - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys). +-- - Enter Activate item (prefer text input when possible). +-- - Space Activate item (prefer tweaking with arrows when possible). +-- - Escape Deactivate item, leave child window, close popup. +-- - Page Up, Page Down Previous page, next page. +-- - Home, End Scroll to top, scroll to bottom. +-- - Alt Toggle between scrolling layer and menu layer. +-- - Ctrl+Tab then Ctrl+Arrows Move window. Hold Shift to resize instead of moving. +-- - Menu or Shift+F10 Open context menu. +-- - Output when ImGuiConfigFlags.NavEnableKeyboard set, +-- - io.WantCaptureKeyboard flag is set when keyboard is claimed. +-- - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags.NoNavInputs flag set. +-- - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used). +-- +-- - GAMEPAD CONTROLS +-- - Enable with 'io.ConfigFlags = bit32.bor(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad)'. +-- - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse! +-- - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets +-- - Backend support: backend needs to: +-- - Set 'io.BackendFlags = bit32.bor(io.BackendFlags, ImGuiBackendFlags.HasGamepad)' + call io:AddKeyEvent()/io:AddKeyAnalogEvent() with ImGuiKey.GamepadXXX keys. +-- - For analog values (0.0 to 1.0), 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.). +-- - (The Roblox and LÖVE backends of this port currently handle mouse and keyboard only: gamepad and touch are not wired up yet.) +-- - 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. +-- +-- - REMOTE INPUTS SHARING & MOUSE EMULATION +-- - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions. +-- - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the io.ConfigNavMoveSetMousePos flag. +-- Enabling io.ConfigNavMoveSetMousePos + ImGuiBackendFlags.HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements. +-- When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved. +-- When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. +-- (If you set the io.ConfigNavMoveSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!) +-- +-- +-- PROGRAMMER GUIDE +-- ================ +-- +-- READ FIRST +-- ---------- +-- - Remember to check the wonderful Wiki: https://github.com/ocornut/imgui/wiki +-- - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone! +-- The UI can be highly dynamic, there are no construction or destruction steps, less superfluous +-- data retention on your side, less state duplication, less state synchronization, fewer bugs. +-- - Call and read ImGui.ShowDemoWindow() for demo code demonstrating most features (imgui_demo.lua, a port of imgui_demo.cpp). +-- Or browse pthom's online imgui_explorer: https://pthom.github.io/imgui_explorer for a web version w/ source code browser. +-- - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori). +-- You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki. +-- - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances. +-- For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI, +-- where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches. +-- - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right. +-- - IM_ASSERT() is used throughout the code, like upstream. +-- If you get an assert, read the messages and comments around the assert. +-- - This codebase aims to be highly optimized: +-- - A typical idle frame should allocate as little as possible (in Luau: avoid creating tables/closures per frame). +-- - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible. +-- - This codebase aims to be both highly opinionated and highly flexible: +-- - This code works because of the things it choose to solve or not solve. +-- - The port keeps upstream's structure (ImGui is a table of free functions, structures are plain tables) +-- so that upstream code, comments and documentation map almost 1:1. See docs/PORTING.md for the porting rules. +-- +-- +-- HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI +-- ---------------------------------------------- +-- - Update by re-pulling this repository (or updating the Wally package / downloading a newer release), +-- then rebuild the bundle (python3 tools/bundle.py, or --target love) and overwrite every file. +-- - This port tracks upstream; read upstream's "API BREAKING CHANGES" (see below) when the tracked upstream version changes. +-- If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed +-- from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will +-- likely be a comment about it. Please report any issue to the GitHub page! +-- - Try to keep your copy of Dear ImGui reasonably up to date! +-- +-- +-- GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE +-- --------------------------------------------------------------- +-- - See https://github.com/ocornut/imgui/wiki/Getting-Started, and README.md of this repository. +-- - Run and study the examples and demo in imgui_demo.lua to get acquainted with the library. +-- - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder +-- (backends/imgui_impl_roblox.lua for Roblox, backends/imgui_impl_love.lua for LÖVE). +-- - Build a single file with tools/bundle.py: build/ImGui.luau (Roblox ModuleScript) or build/imgui_love.lua (LÖVE), +-- then require() / load it. All exported names (ImGui, ImVec2, ImVec4, IM_COL32, every ImGui*Flags enum...) are fields of the returned table. +-- - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. +-- - Dear ImGui never touches or knows about your GPU state. The only function that knows about rendering is the draw function that you provide (the backend's RenderDrawData). +-- Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" +-- phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui.Render(). +-- - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code. +-- +-- +-- HOW A SIMPLE APPLICATION MAY LOOK LIKE +-- -------------------------------------- +-- +-- USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.lua files from the backends/ folder). +-- The sub-folders in examples/ contain examples applications following this structure. +-- +-- Roblox (LocalScript, see examples/example_roblox/main.client.luau): +-- +-- local G = require(ReplicatedStorage:WaitForChild("ImGui")) +-- local ImGui, ImGui_ImplRoblox = G.ImGui, G.ImGui_ImplRoblox +-- +-- -- Application init: create a dear imgui context, setup some options, load fonts +-- ImGui.CreateContext() +-- local io = ImGui.GetIO() +-- -- TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags = bit32.bor(io.ConfigFlags, G.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. +-- +-- -- Initialize helper Platform and Renderer backend (here we are using imgui_impl_roblox.lua) +-- ImGui_ImplRoblox.Init() +-- +-- -- Application main loop +-- RunService.Stepped:Connect(function() +-- -- Feed inputs to dear imgui, start new frame +-- ImGui_ImplRoblox.NewFrame() +-- ImGui.NewFrame() +-- +-- -- Any application code here +-- ImGui.Text("Hello, world!") +-- +-- -- Render dear imgui +-- ImGui.Render() +-- ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData()) +-- end) +-- +-- -- Shutdown +-- ImGui_ImplRoblox.Shutdown() +-- ImGui.DestroyContext() +-- +-- LÖVE (see examples/example_love/main.lua): +-- +-- function love.load() +-- ImGui.CreateContext() +-- G.ImGui_ImplLove.Init({ root = ROOT }) +-- end +-- function love.update(dt) +-- G.ImGui_ImplLove.NewFrame() +-- ImGui.NewFrame() +-- ImGui.Text("Hello, world!") +-- ImGui.Render() +-- end +-- function love.draw() +-- G.ImGui_ImplLove.RenderDrawData(ImGui.GetDrawData()) +-- end +-- -- + forward love.mousemoved/mousepressed/mousereleased/wheelmoved/keypressed/keyreleased/textinput/focus +-- -- to G.ImGui_ImplLove.MouseMoved/MousePressed/MouseReleased/WheelMoved/KeyPressed/KeyReleased/TextInput/Focus. +-- +-- 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. +-- +-- +-- USAGE +-- ----- +-- +-- Widget functions are called every frame; their return values tell you what the user did. +-- Out-parameters of the C++ API (bool* p_open, float* v, int* v...) are passed by value and the new value is returned: +-- +-- ImGui.Text("Hello, world %d", 123) +-- if ImGui.Button("Save") then +-- MySaveFunction() +-- end +-- ImGui.InputText("string", buf, 256) -- buf = ImGui.NewTextBuffer("...", 256), edited in place +-- f = ImGui.SliderFloat("float", f, 0.0, 1.0) -- returns (value, changed) +-- pressed, v = ImGui.Checkbox("checkbox", v) +-- +-- -- Create a window called "My First Tool", with a menu bar. +-- my_tool_active = ImGui.Begin("My First Tool", my_tool_active, ImGuiWindowFlags.MenuBar) -- returns (open, visible) +-- if ImGui.BeginMenuBar() then +-- if ImGui.BeginMenu("File") then +-- if ImGui.MenuItem("Close", "Ctrl+W") then my_tool_active = false end +-- ImGui.EndMenu() +-- end +-- ImGui.EndMenuBar() +-- end +-- ImGui.ColorEdit4("Color", my_color) -- ImVec4 / arrays are edited in place +-- ImGui.End() +-- +-- +-- USING CUSTOM BACKEND / CUSTOM ENGINE +-- ------------------------------------ +-- +-- A backend implements the usual Dear ImGui contract: Init, NewFrame, RenderDrawData, inputs -> io:AddXXXEvent(), +-- texture updates via ImTextureData. Adding another Lua host means a new backends/imgui_impl_.lua. +-- -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions. +-- -> the backends in backends/imgui_impl_roblox.lua and backends/imgui_impl_love.lua are complete implementations. +-- +-- Basic application/backend skeleton: +-- +-- -- Application init: create a Dear ImGui context, setup some options, load fonts +-- ImGui.CreateContext() +-- local io = ImGui.GetIO() +-- -- TODO: set io.ConfigXXX values, e.g. +-- io.ConfigFlags = bit32.bor(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) -- Enable keyboard controls +-- +-- -- TODO: Load TTF/OTF fonts if you don't want to use the default font. +-- io.Fonts:AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0) +-- +-- -- Application main loop (called once per frame) +-- local function OnFrame(dt) +-- -- Setup low-level inputs, or write to those fields from your input event handlers, etc. +-- -- (In the examples/ app this is usually done within the ImGui_ImplXXX.NewFrame() function from one of the Backends) +-- io.DeltaTime = dt -- set the time elapsed since the previous frame (in seconds) +-- io.DisplaySize.x = 1920.0 -- set the current display width +-- io.DisplaySize.y = 1280.0 -- set the current display height here +-- io:AddMousePosEvent(mouse_x, mouse_y) -- update mouse position +-- io:AddMouseButtonEvent(0, mouse_b0) -- update mouse button states +-- io:AddMouseButtonEvent(1, mouse_b1) -- update mouse button states +-- +-- -- Call NewFrame(), after this point you can use ImGui.* functions anytime +-- -- (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere) +-- ImGui.NewFrame() +-- +-- -- Most of your application code here +-- ImGui.Text("Hello, world!") +-- 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! +-- +-- -- 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() -- this is automatically called by Render(), but available +-- ImGui.Render() +-- +-- -- Update textures +-- local draw_data = ImGui.GetDrawData() +-- for _, tex in draw_data.Textures:iter() do +-- if tex.Status ~= ImTextureStatus.OK then +-- MyImGuiBackend_UpdateTexture(tex) +-- end +-- end +-- +-- -- Render dear imgui contents +-- MyImGuiBackend_RenderDrawData(draw_data) +-- end +-- +-- -- Shutdown +-- ImGui.DestroyContext() +-- +-- +-- +-- API BREAKING CHANGES +-- ==================== +-- +-- This port tracks upstream Dear ImGui 1.93 WIP (docking branch). +-- For the change-log of API breaking changes, see the top of upstream imgui.cpp, or https://github.com/ocornut/imgui/releases +-- +-- +-- FREQUENTLY ASKED QUESTIONS (FAQ) +-- ================================ +-- +-- Read all answers online: +-- https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url) +-- For questions specific to this port (Roblox, LÖVE, performance, differences from C++), see the FAQ in README.md of this repository. +-- + --- Dear ImGui WIP -- (Core Code) @@ -20,6 +436,9 @@ IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS = true -- Don't implement ImStd.ImFileOpen/ IMGUI_DISABLE_DEBUG_TOOLS = false -- Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty +-- Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be ~= nil. +-- - ImGui.CreateContext() will automatically set this pointer if it is nil. +-- Change to a different context by calling ImGui.SetCurrentContext(). --- @type ImGuiContext? local GImGui = nil @@ -37,10 +456,13 @@ local function LUA_TableConstructorWrapper(T, size, userdata) return p end +-- Memory Allocator functions. Use SetAllocatorFunctions() to change them. +-- - You probably don't want to modify that mid-program. local GImAllocatorAllocFunc = LUA_TableConstructorWrapper local GImAllocatorFreeFunc = function(p0, p1, p2) end local GImAllocatorUserData = nil +-- IM_ALLOC() == ImGui.MemAlloc() --- @param constructor function --- @param size int function ImGui.MemAlloc(constructor, size) @@ -52,6 +474,7 @@ function ImGui.MemAlloc(constructor, size) return p end +-- IM_FREE() == ImGui.MemFree() -- This does not set `owner[field]` to nil! --- @param owner table --- @param field string|int @@ -65,6 +488,7 @@ function ImGui.MemFree(owner, field) return GImAllocatorFreeFunc(owner, field, GImAllocatorUserData) end +-- We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames" --- @param info ImGuiDebugAllocInfo --- @param frame_count int --- @param ptr table @@ -105,6 +529,10 @@ do --[[ [SECTION] imgui_dragdrop (was imgui_dragdrop.lua) ]] -- Drag and drop: 1:1 port of imgui.cpp [SECTION] DRAG AND DROP (docking branch) -- Payload `Data` is any Lua value (no copy is made). `data_size` is optional and only kept for API parity. +------------------------------------------------------------------------------- +-- [SECTION] DRAG AND DROP +------------------------------------------------------------------------------- + function ImGui.IsDragDropActive() return ImGui.GetCurrentContext().DragDropActive end @@ -120,11 +548,20 @@ function ImGui.ClearDragDrop() g.DragDropAcceptFrameCount = -1 end +-- When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource() +-- If the item has an identifier: +-- - This assume/require the item to be activated (typically via ButtonBehavior). +-- - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button. +-- - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag. +-- If the item has no identifier: +-- - Currently always assume left mouse button. function ImGui.BeginDragDropSource(flags) if flags == nil then flags = 0 end local g = ImGui.GetCurrentContext() local window = g.CurrentWindow + -- FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button, + -- in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic). local mouse_button = ImGuiMouseButton.Left local source_drag_active = false @@ -133,19 +570,30 @@ function ImGui.BeginDragDropSource(flags) if bit32.band(flags, ImGuiDragDropFlags.SourceExtern) == 0 then source_id = g.LastItemData.ID if source_id ~= 0 then + -- Common path: items with ID if g.ActiveId ~= source_id then return false end if g.ActiveIdMouseButton ~= -1 then mouse_button = g.ActiveIdMouseButton end if g.IO.MouseDown[mouse_button] == false or window.SkipItems then return false end g.ActiveIdAllowOverlap = false else + -- Uncommon path: items without ID if g.IO.MouseDown[mouse_button] == false or window.SkipItems then return false end if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) == 0 and (g.ActiveId == 0 or g.ActiveIdWindow ~= window) then return false end + + -- If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to: + -- A) Read the explanation below, B) Use the ImGuiDragDropFlags.SourceAllowNullID flag. if bit32.band(flags, ImGuiDragDropFlags.SourceAllowNullID) == 0 then IM_ASSERT(false, "Use ImGuiDragDropFlags.SourceAllowNullID for items without an ID") return false end + + -- Magic fallback to handle items with no assigned ID, e.g. Text(), Image() + -- We build a throwaway ID based on current ID stack + relative AABB of items in window. + -- THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZING OF THE WIDGET, so if your widget moves your dragging operation will be canceled. + -- We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive. + -- Rely on keeping other window.LastItemXXX fields intact. source_id = window:GetIDFromRectangle(g.LastItemData.Rect) g.LastItemData.ID = source_id ImGui.KeepAliveID(source_id) @@ -154,14 +602,16 @@ function ImGui.BeginDragDropSource(flags) ImGui.SetActiveID(source_id, window) ImGui.FocusWindow(window) end - if g.ActiveId == source_id then g.ActiveIdAllowOverlap = is_hovered end + if g.ActiveId == source_id then g.ActiveIdAllowOverlap = is_hovered end -- Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker. end if g.ActiveId ~= source_id then return false end source_parent_id = window.IDStack.Data[window.IDStack.Size] source_drag_active = ImGui.IsMouseDragging(mouse_button) + -- Disable navigation and key inputs while dragging + cancel existing request if any ImGui.SetActiveIdUsingAllKeyboardKeys() else + -- When ImGuiDragDropFlags.SourceExtern is set: window = nil source_id = ImHashStr("#SourceExtern") source_drag_active = true @@ -170,9 +620,10 @@ function ImGui.BeginDragDropSource(flags) ImGui.SetActiveID(source_id, nil) end - IM_ASSERT(g.DragDropWithinTarget == false) + IM_ASSERT(g.DragDropWithinTarget == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() if not source_drag_active then return false end + -- Activate drag and drop if not g.DragDropActive then IM_ASSERT(source_id ~= 0) ImGui.ClearDragDrop() @@ -188,13 +639,15 @@ function ImGui.BeginDragDropSource(flags) g.DragDropWithinSource = true if bit32.band(flags, ImGuiDragDropFlags.SourceNoPreviewTooltip) == 0 then + -- Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit) + -- We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents. local ret if g.DragDropAcceptIdPrev ~= 0 and bit32.band(g.DragDropAcceptFlagsPrev, ImGuiDragDropFlags.AcceptNoPreviewTooltip) ~= 0 then ret = ImGui.BeginTooltipHidden() else ret = ImGui.BeginTooltip() end - IM_ASSERT(ret) + IM_ASSERT(ret) -- FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", nil, ImGuiWindowFlags.NoSavedSettings) + SetWindowHiddenAndSkipItemsForCurrentFrame(). end if bit32.band(flags, ImGuiDragDropFlags.SourceNoDisableHover) == 0 and bit32.band(flags, ImGuiDragDropFlags.SourceExtern) == 0 then @@ -212,10 +665,12 @@ function ImGui.EndDragDropSource() ImGui.EndTooltip() end + -- Discard the drag if have not called SetDragDropPayload() if g.DragDropPayload.DataFrameCount == -1 then ImGui.ClearDragDrop() end g.DragDropWithinSource = false end +-- Use 'cond' to choose to submit payload on drag start or every frame --- @param data any # any Lua value --- @return bool accepted function ImGui.SetDragDropPayload(type, data, data_size, cond) @@ -226,15 +681,17 @@ function ImGui.SetDragDropPayload(type, data, data_size, cond) IM_ASSERT(type ~= nil) IM_ASSERT(#type < 32, "Payload type can be at most 32 characters long") IM_ASSERT(cond == ImGuiCond.Always or cond == ImGuiCond.Once) - IM_ASSERT(payload.SourceId ~= 0) + IM_ASSERT(payload.SourceId ~= 0) -- Not called between BeginDragDropSource() and EndDragDropSource() if cond == ImGuiCond.Always or payload.DataFrameCount == -1 then + -- Copy payload payload.DataType = type payload.Data = data payload.DataSize = data_size or ((data ~= nil) and 1 or 0) end payload.DataFrameCount = g.FrameCount + -- Return whether the payload has been accepted return (g.DragDropAcceptFrameCount == g.FrameCount) or (g.DragDropAcceptFrameCount == g.FrameCount - 1) end @@ -249,15 +706,19 @@ function ImGui.BeginDragDropTargetCustom(bb, id) if not ImGui.IsMouseHoveringRect(bb.Min, bb.Max) or (id == g.DragDropPayload.SourceId) then return false end if window.SkipItems then return false end - IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) + IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() g.DragDropTargetRect = ImRect(bb.Min, bb.Max) - g.DragDropTargetClipRect = ImRect(window.ClipRect.Min, window.ClipRect.Max) + g.DragDropTargetClipRect = ImRect(window.ClipRect.Min, window.ClipRect.Max) -- May want to be overridden by user depending on use case? g.DragDropTargetId = id g.DragDropTargetFullViewport = 0 g.DragDropWithinTarget = true return true end +-- Typical usage would be: +-- if not ImGui.IsWindowHovered(bit32.bor(ImGuiHoveredFlags.AnyWindow, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem)) then +-- if ImGui.BeginDragDropTargetViewport(ImGui.GetMainViewport(), nil) then +-- But we are leaving the hover test to the caller for maximum flexibility. function ImGui.BeginDragDropTargetViewport(viewport, p_bb) local g = ImGui.GetCurrentContext() if not g.DragDropActive then return false end @@ -268,7 +729,7 @@ function ImGui.BeginDragDropTargetViewport(viewport, p_bb) return false end - IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) + IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() g.DragDropTargetRect = ImRect(bb.Min, bb.Max) g.DragDropTargetClipRect = ImRect(bb.Min, bb.Max) g.DragDropTargetId = id @@ -277,6 +738,10 @@ function ImGui.BeginDragDropTargetViewport(viewport, p_bb) return true end +-- We don't use BeginDragDropTargetCustom() and duplicate its code because: +-- 1) we use LastItemData's ImGuiItemStatusFlags.HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them. +-- 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can. +-- Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case) function ImGui.BeginDragDropTarget() local g = ImGui.GetCurrentContext() if not g.DragDropActive then return false end @@ -294,7 +759,7 @@ function ImGui.BeginDragDropTarget() end if g.DragDropPayload.SourceId == id then return false end - IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) + IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() g.DragDropTargetRect = ImRect(display_rect.Min, display_rect.Max) local clip = (bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasClipRect) ~= 0) and g.LastItemData.ClipRect or window.ClipRect g.DragDropTargetClipRect = ImRect(clip.Min, clip.Max) @@ -313,10 +778,12 @@ function ImGui.AcceptDragDropPayload(type, flags) if flags == nil then flags = 0 end local g = ImGui.GetCurrentContext() local payload = g.DragDropPayload - IM_ASSERT(g.DragDropActive) - IM_ASSERT(payload.DataFrameCount ~= -1) + IM_ASSERT(g.DragDropActive) -- Not called between BeginDragDropTarget() and EndDragDropTarget() ? + IM_ASSERT(payload.DataFrameCount ~= -1) -- Forgot to call EndDragDropTarget() ? if type ~= nil and not ImGuiPayload_IsDataType(payload, type) then return nil end + -- Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints. + -- NB: We currently accept nil id as target. However, overlapping targets requires a unique ID to function! local was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId) local r = g.DragDropTargetRect local r_surface = r:GetWidth() * r:GetHeight() @@ -325,9 +792,11 @@ function ImGui.AcceptDragDropPayload(type, flags) g.DragDropAcceptFlagsCurr = flags g.DragDropAcceptIdCurr = g.DragDropTargetId g.DragDropAcceptIdCurrRectSurface = r_surface + -- IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId) + -- Render default drop visuals payload.Preview = was_accepted_previously - flags = bit32.bor(flags, bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.AcceptNoDrawDefaultRect)) + flags = bit32.bor(flags, bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.AcceptNoDrawDefaultRect)) -- Source can also inhibit the preview (useful for external sources that live for 1 frame) local draw_target_rect = payload.Preview and bit32.band(flags, ImGuiDragDropFlags.AcceptNoDrawDefaultRect) == 0 if draw_target_rect and g.DragDropTargetFullViewport ~= 0 then ImGui.RenderDragDropTargetRectForViewport(g.DragDropTargetFullViewport, g.DragDropTargetRect) @@ -339,17 +808,18 @@ function ImGui.AcceptDragDropPayload(type, flags) if bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceExtern) ~= 0 and g.DragDropMouseButton == -1 then payload.Delivery = was_accepted_previously and (g.DragDropSourceFrameCount < g.FrameCount) else - payload.Delivery = was_accepted_previously and not ImGui.IsMouseDown(g.DragDropMouseButton) + payload.Delivery = was_accepted_previously and not ImGui.IsMouseDown(g.DragDropMouseButton) -- For extern drag sources affecting OS window focus, it's easier to just test not IsMouseDown() instead of IsMouseReleased() end if not payload.Delivery and bit32.band(flags, ImGuiDragDropFlags.AcceptBeforeDelivery) == 0 then return nil end return payload end +-- FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target. function ImGui.RenderDragDropTargetRectForItem(bb) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow local bb_display = ImRect(bb.Min, bb.Max) - bb_display:ClipWith(g.DragDropTargetClipRect) + bb_display:ClipWith(g.DragDropTargetClipRect) -- Clip THEN expand so we have a way to visualize that target is not entirely visible. bb_display:Expand(g.Style.DragDropTargetPadding) local push_clip_rect = not window.ClipRect:Contains(bb_display) if push_clip_rect then window.DrawList:PushClipRectFullScreen() end @@ -383,6 +853,8 @@ function ImGui.EndDragDropTarget() IM_ASSERT(g.DragDropActive) IM_ASSERT(g.DragDropWithinTarget) g.DragDropWithinTarget = false + + -- Clear drag and drop state payload right after delivery if g.DragDropPayload.Delivery then ImGui.ClearDragDrop() end end @@ -402,54 +874,129 @@ do --[[ [SECTION] imgui_docking (was imgui_docking.lua) ]] -- - node.ChildNodes is a table indexed [0] and [1] like upstream. -- - ImGuiDockPreviewData.DropRectsDraw is indexed [dir + 1] with dir in -1..3 (so keys 0..4), like upstream. +------------------------------------------------------------------------------- +-- [SECTION] DOCKING +------------------------------------------------------------------------------- +-- Docking: Internal Types +-- Docking: Forward Declarations +-- Docking: ImGuiDockContext +-- Docking: ImGuiDockContext Docking/Undocking functions +-- Docking: ImGuiDockNode +-- Docking: ImGuiDockNode Tree manipulation functions +-- Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) +-- Docking: Builder Functions +-- Docking: Begin/End Support Functions (called from Begin/End) +-- Docking: Settings +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- Typical Docking call flow: (root level is generally public API): +------------------------------------------------------------------------------- +-- - NewFrame() new dear imgui frame +-- | DockContextNewFrameUpdateUndocking() - process queued undocking requests +-- | - DockContextProcessUndockWindow() - process one window undocking request +-- | - DockContextProcessUndockNode() - process one whole node undocking request +-- | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes +-- | - update g.HoveredDockNode - [debug] update node hovered by mouse +-- | - DockContextProcessDock() - process one docking request +-- | - DockNodeUpdate() +-- | - DockNodeUpdateForRootNode() +-- | - DockNodeUpdateFlagsAndCollapse() +-- | - DockNodeFindInfo() +-- | - destroy unused node or tab bar +-- | - create dock node host window +-- | - Begin() etc. +-- | - DockNodeStartMouseMovingWindow() +-- | - DockNodeTreeUpdatePosSize() +-- | - DockNodeTreeUpdateSplitter() +-- | - draw node background +-- | - DockNodeUpdateTabBar() - create/update tab bar for a docking node +-- | - DockNodeAddTabBar() +-- | - DockNodeWindowMenuUpdate() +-- | - DockNodeCalcTabBarLayout() +-- | - BeginTabBarEx() +-- | - TabItemEx() calls +-- | - EndTabBar() +-- | - BeginDockableDragDropTarget() +-- | - DockNodeUpdate() - recurse into child nodes... +------------------------------------------------------------------------------- +-- - DockSpace() user submit a dockspace into a window +-- | Begin(Child) - create a child window +-- | DockNodeUpdate() - call main dock node update function +-- | End(Child) +-- | ItemSize() +------------------------------------------------------------------------------- +-- - Begin() +-- | BeginDocked() +-- | BeginDockableDragDropSource() +-- | BeginDockableDragDropTarget() +-- | - DockNodePreviewDockRender() +------------------------------------------------------------------------------- +-- - EndFrame() +-- | DockContextEndFrame() +------------------------------------------------------------------------------- + local MT = ImGui.GetMetatables() -IMGUI_PAYLOAD_TYPE_WINDOW = "_IMWINDOW" +IMGUI_PAYLOAD_TYPE_WINDOW = "_IMWINDOW" -- Payload == ImGuiWindow local DOCKING_HOST_DRAW_CHANNEL_BG = 0 -- Dock host: background fill local DOCKING_HOST_DRAW_CHANNEL_FG = 1 -- Dock host: decorations and contents local DOCKING_SPLITTER_SIZE = 2.0 ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: flags & enums ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Flags for ImGui.DockSpace(), shared/inherited by child nodes. +-- (Some flags can be applied to individual nodes directly) +-- FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api. ImGuiDockNodeFlags = { None = 0, - KeepAliveOnly = bit32.lshift(1, 0), - NoDockingOverCentralNode = bit32.lshift(1, 2), - PassthruCentralNode = bit32.lshift(1, 3), - NoDockingSplit = bit32.lshift(1, 4), - NoResize = bit32.lshift(1, 5), - AutoHideTabBar = bit32.lshift(1, 6), - NoUndocking = bit32.lshift(1, 7), + KeepAliveOnly = bit32.lshift(1, 0), -- -- Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. + -- NoCentralNode = bit32.lshift(1, 1), -- -- Disable Central Node (the node which can stay empty) + NoDockingOverCentralNode = bit32.lshift(1, 2), -- -- Disable docking over the Central Node, which will be always kept empty. + PassthruCentralNode = bit32.lshift(1, 3), -- -- Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol.WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. + NoDockingSplit = bit32.lshift(1, 4), -- -- Disable other windows/nodes from splitting this node. + NoResize = bit32.lshift(1, 5), -- Saved -- Disable resizing node using the splitter/separators. Useful with programmatically setup dockspaces. + AutoHideTabBar = bit32.lshift(1, 6), -- -- Tab bar will automatically hide when there is a single window in the dock node. + NoUndocking = bit32.lshift(1, 7), -- -- Disable undocking this node. + + -- Extend ImGuiDockNodeFlags_ (ImGuiDockNodeFlagsPrivate_) -- [Internal] - DockSpace = bit32.lshift(1, 10), - CentralNode = bit32.lshift(1, 11), - NoTabBar = bit32.lshift(1, 12), - HiddenTabBar = bit32.lshift(1, 13), - NoWindowMenuButton = bit32.lshift(1, 14), - NoCloseButton = bit32.lshift(1, 15), - NoResizeX = bit32.lshift(1, 16), - NoResizeY = bit32.lshift(1, 17), - DockedWindowsInFocusRoute = bit32.lshift(1, 18), - NoDockingSplitOther = bit32.lshift(1, 19), - NoDockingOverMe = bit32.lshift(1, 20), - NoDockingOverOther = bit32.lshift(1, 21), - NoDockingOverEmpty = bit32.lshift(1, 22), + DockSpace = bit32.lshift(1, 10), -- Saved -- A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. + CentralNode = bit32.lshift(1, 11), -- Saved -- The central node has 2 main properties: stay visible when empty, only use "remaining" spaces from its neighbor. + NoTabBar = bit32.lshift(1, 12), -- Saved -- Tab bar is completely unavailable. No triangle in the corner to enable it back. + HiddenTabBar = bit32.lshift(1, 13), -- Saved -- Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) + NoWindowMenuButton = bit32.lshift(1, 14), -- Saved -- Disable window/docking menu (that one that appears instead of the collapse button) + NoCloseButton = bit32.lshift(1, 15), -- Saved -- Disable close button + NoResizeX = bit32.lshift(1, 16), -- -- + NoResizeY = bit32.lshift(1, 17), -- -- + DockedWindowsInFocusRoute = bit32.lshift(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. + NoDockingSplitOther = bit32.lshift(1, 19), -- -- Disable this node from splitting other windows/nodes. + NoDockingOverMe = bit32.lshift(1, 20), -- -- Disable other windows/nodes from being docked over this node. + NoDockingOverOther = bit32.lshift(1, 21), -- -- Disable this node from being docked over another window or non-empty node. + NoDockingOverEmpty = bit32.lshift(1, 22), -- -- Disable this node from being docked over an empty node (e.g. DockSpace with no other windows) } do local F = ImGuiDockNodeFlags - F.NoSplit = F.NoDockingSplit - F.NoDockingInCentralNode = F.NoDockingOverCentralNode + F.NoSplit = F.NoDockingSplit -- Renamed in 1.90 + F.NoDockingInCentralNode = F.NoDockingOverCentralNode -- Renamed in 1.90 F.NoDocking = bit32.bor(F.NoDockingOverMe, F.NoDockingOverOther, F.NoDockingOverEmpty, F.NoDockingSplit, F.NoDockingSplitOther) + -- Masks F.SharedFlagsInheritMask_ = 0xFFFFFFFF F.NoResizeFlagsMask_ = bit32.bor(F.NoResize, F.NoResizeX, F.NoResizeY) + -- When splitting, those local flags are moved to the inheriting child, never duplicated F.LocalFlagsTransferMask_ = bit32.bor(F.NoDockingSplit, F.NoResizeFlagsMask_, F.AutoHideTabBar, F.CentralNode, F.NoTabBar, F.HiddenTabBar, F.NoWindowMenuButton, F.NoCloseButton) F.SavedFlagsMask_ = bit32.bor(F.NoResizeFlagsMask_, F.DockSpace, F.CentralNode, F.NoTabBar, F.HiddenTabBar, F.NoWindowMenuButton, F.NoCloseButton) end +-- Store the source authority (dock node vs window) of a field ImGuiDataAuthority = { Auto = 0, DockNode = 1, Window = 2 } ImGuiDockNodeState = { @@ -459,35 +1006,50 @@ ImGuiDockNodeState = { HostWindowVisible = 3, } +-- List of colors that are stored at the time of Begin() into Docked Windows. +-- We currently store the packed colors in a simple array window.DockStyle.Colors[]. +-- A better solution may involve appending into a log of colors in ImGuiContext + store offsets into those arrays in ImGuiWindow, +-- but it would be more complex as we'd need to double-buffer both as e.g. drop target may refer to window from last frame. ImGuiWindowDockStyleCol = { Text = 0, TabHovered = 1, TabFocused = 2, TabSelected = 3, TabSelectedOverline = 4, TabDimmed = 5, TabDimmedSelected = 6, TabDimmedSelectedOverline = 7, UnsavedMarker = 8, COUNT = 9, } -local ImGuiDockRequestType = { None = 0, Dock = 1, Undock = 2, Split = 3 } - ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Internal Types ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - ImGuiDockRequestType +-- - ImGuiDockRequest +-- - ImGuiDockPreviewData +-- - ImGuiDockNodeSettings +-- - ImGuiDockContext +------------------------------------------------------------------------------- + +local ImGuiDockRequestType = { None = 0, Dock = 1, Undock = 2, Split = 3 } -- Split is the same as Dock but without a DockPayload local function ImGuiDockRequest() return { Type = ImGuiDockRequestType.None, + -- DockTargetWindow: Destination/Target Window to dock into (may be a loose window or a DockNode, might be nil in which case DockTargetNode cannot be nil) + -- DockTargetNode: Destination/Target Node to dock into + -- DockPayload: Source/Payload window to dock (may be a loose window or a DockNode), [Optional] DockTargetWindow = nil, DockTargetNode = nil, DockPayload = nil, DockSplitDir = ImGuiDir.None, DockSplitRatio = 0.5, DockSplitOuter = false, UndockTargetWindow = nil, UndockTargetNode = nil, } end +-- Persistent Settings data, stored contiguously in SettingsNodes local function ImGuiDockNodeSettings() return { ID = 0, ParentNodeId = 0, ParentWindowId = 0, SelectedTabId = 0, - SplitAxis = ImGuiAxis.None, Depth = 0, Flags = 0, + SplitAxis = ImGuiAxis.None, Depth = 0, Flags = 0, -- Flags: NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags.SavedFlagsMask_) Pos = ImVec2(0, 0), Size = ImVec2(0, 0), SizeRef = ImVec2(0, 0), } end function ImGuiDockContext() + -- Nodes: Map ID -> ImGuiDockNode: Active nodes return { Nodes = {}, Requests = ImVector(), NodesSettings = ImVector(), WantFullRebuild = false } end @@ -498,25 +1060,44 @@ local DN = MT.ImGuiDockNode function ImGuiDockNode(id) return setmetatable({ ID = id, + -- SharedFlags: (Write) Flags shared by all nodes of a same dockspace hierarchy (inherited from the root node) + -- LocalFlags: (Write) Flags specific to this node + -- LocalFlagsInWindows: (Write) Flags specific to this node, applied from windows + -- MergedFlags: (Read) Effective flags (== SharedFlags | LocalFlagsInNode | LocalFlagsInWindows) SharedFlags = 0, LocalFlags = 0, LocalFlagsInWindows = 0, MergedFlags = 0, State = ImGuiDockNodeState.Unknown, ParentNode = nil, - ChildNodes = { [0] = nil, [1] = nil }, - Windows = ImVector(), + ChildNodes = { [0] = nil, [1] = nil }, -- [Split node only] Child nodes (left/right or top/bottom). Consider switching to an array. + Windows = ImVector(), -- Note: unordered list! Iterate TabBar.Tabs for user-order. TabBar = nil, + -- Pos: Current position + -- Size: Current size + -- SizeRef: [Split node only] Last explicitly written-to size (overridden when using a splitter affecting the node), used to calculate Size. Pos = ImVec2(0, 0), Size = ImVec2(0, 0), SizeRef = ImVec2(0, 0), - SplitAxis = ImGuiAxis.None, + SplitAxis = ImGuiAxis.None, -- [Split node only] Split axis (X or Y) LastBgColor = IM_COL32_WHITE, - WindowClass = ImGuiWindowClass(), + WindowClass = ImGuiWindowClass(), -- [Root node only] + -- VisibleWindow: Generally point to window which is ID is == SelectedTabID, but when CTRL+Tabbing this can be a different window. HostWindow = nil, VisibleWindow = nil, + -- CentralNode: [Root node only] Pointer to central node. + -- OnlyNodeWithWindows: [Root node only] Set when there is a single visible node within the hierarchy. CentralNode = nil, OnlyNodeWithWindows = nil, - CountNodeWithWindows = 0, + CountNodeWithWindows = 0, -- [Root node only] + -- LastFrameAlive: Last frame number the node was updated or kept alive explicitly with DockSpace() + ImGuiDockNodeFlags.KeepAliveOnly + -- LastFrameActive: Last frame number the node was updated. + -- LastFrameFocused: Last frame number the node was focused. LastFrameAlive = -1, LastFrameActive = -1, LastFrameFocused = -1, + -- LastFocusedNodeId: [Root node only] Which of our child docking node (any ancestor in the hierarchy) was last focused. + -- SelectedTabId: [Leaf node only] Which of our tab/window is selected. + -- WantCloseTabId: [Leaf node only] Set when closing a specific tab/window. + -- RefViewportId: Reference viewport ID from visible window when HostWindow == nil. LastFocusedNodeId = 0, SelectedTabId = 0, WantCloseTabId = 0, RefViewportId = 0, - AuthorityForPos = ImGuiDataAuthority.DockNode, AuthorityForSize = ImGuiDataAuthority.DockNode, + AuthorityForPos = ImGuiDataAuthority.DockNode, AuthorityForSize = ImGuiDataAuthority.DockNode, -- ImGuiDataAuthority AuthorityForViewport = ImGuiDataAuthority.Auto, - IsVisible = true, IsFocused = false, IsBgDrawnThisFrame = false, - HasCloseButton = false, HasWindowMenuButton = false, HasCentralNodeChild = false, + IsVisible = true, IsFocused = false, IsBgDrawnThisFrame = false, -- IsVisible: Set to false when the node is hidden (usually disabled as it has no active window) + HasCloseButton = false, HasWindowMenuButton = false, HasCentralNodeChild = false, -- HasCloseButton: Provide space for a close button (if any of the docked window has one). Note that button may be hidden on window without one. + -- WantCloseAll: Set when closing all tabs at once. + -- WantMouseMove: After a node extraction we need to transition toward moving the newly created host window WantCloseAll = false, WantLockSizeOnce = false, WantMouseMove = false, WantHiddenTabBarUpdate = false, WantHiddenTabBarToggle = false, }, DN) @@ -526,8 +1107,8 @@ function DN:IsRootNode() return self.ParentNode == nil end function DN:IsDockSpace() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.DockSpace) ~= 0 end function DN:IsFloatingNode() return self.ParentNode == nil and bit32.band(self.MergedFlags, ImGuiDockNodeFlags.DockSpace) == 0 end function DN:IsCentralNode() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.CentralNode) ~= 0 end -function DN:IsHiddenTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.HiddenTabBar) ~= 0 end -function DN:IsNoTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.NoTabBar) ~= 0 end +function DN:IsHiddenTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.HiddenTabBar) ~= 0 end -- Hidden tab bar can be shown back by clicking the small triangle +function DN:IsNoTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.NoTabBar) ~= 0 end -- Never show a tab bar function DN:IsSplitNode() return self.ChildNodes[0] ~= nil end function DN:IsLeafNode() return self.ChildNodes[0] == nil end function DN:IsEmpty() return self.ChildNodes[0] == nil and self.Windows.Size == 0 end @@ -538,9 +1119,11 @@ function DN:UpdateMergedFlags() self.MergedFlags = bit32.bor(self.SharedFlags, s local function ImGuiDockPreviewData() local d = { FutureNode = ImGuiDockNode(0), + -- IsSidesAvailable: Hold your breath, grammar freaks.. + -- IsSplitDirExplicit: Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window) IsDropAllowed = false, IsCenterAvailable = false, IsSidesAvailable = false, IsSplitDirExplicit = false, SplitNode = nil, SplitDir = ImGuiDir.None, SplitRatio = 0.0, - DropRectsDraw = {}, + DropRectsDraw = {}, -- May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects() } for n = 0, 4 do d.DropRectsDraw[n] = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX) end return d @@ -561,20 +1144,51 @@ local function DockContextNodesSorted(ctx) end ImGui.DockContextNodesSorted = DockContextNodesSorted ---------------------------------------------------------------------------------------- --- Docking: ImGuiDockContext ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Docking: Forward Declarations +------------------------------------------------------------------------------- +-- Settings local DockSettingsHandler_ClearAll, DockSettingsHandler_ApplyAll, DockSettingsHandler_ReadOpen, DockSettingsHandler_ReadLine, DockSettingsHandler_WriteAll local DockSettingsRenameNodeReferences, DockSettingsRemoveNodeReferences, DockSettingsFindNodeSettings +------------------------------------------------------------------------------- +-- Docking: ImGuiDockContext +------------------------------------------------------------------------------- +-- The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings, +-- or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active. +-- At boot time only, we run a simple GC to remove nodes that have no references. +-- Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures), +-- we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does). +-- This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data. +------------------------------------------------------------------------------- +-- - DockContextInitialize() +-- - DockContextShutdown() +-- - DockContextClearNodes() +-- - DockContextRebuildNodes() +-- - DockContextNewFrameUpdateUndocking() +-- - DockContextNewFrameUpdateDocking() +-- - DockContextEndFrame() +-- - DockContextFindNodeByID() +-- - DockContextBindNodeToWindow() +-- - DockContextGenNodeID() +-- - DockContextAddNode() +-- - DockContextRemoveNode() +-- - ImGuiDockContextPruneNodeData +-- - DockContextPruneUnusedSettingsNodes() +-- - DockContextBuildNodesFromSettings() +-- - DockContextBuildAddWindowsToNodes() +------------------------------------------------------------------------------- + function ImGui.DockContextInitialize(ctx) local g = ctx + + -- Add .ini handle for persistent docking data local ini_handler = ImGuiSettingsHandler() ini_handler.TypeName = "Docking" ini_handler.TypeHash = ImHashStr("Docking") ini_handler.ClearAllFn = DockSettingsHandler_ClearAll - ini_handler.ReadInitFn = DockSettingsHandler_ClearAll + ini_handler.ReadInitFn = DockSettingsHandler_ClearAll -- Also clear on read ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen ini_handler.ReadLineFn = DockSettingsHandler_ReadLine ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll @@ -596,15 +1210,18 @@ function ImGui.DockContextClearNodes(ctx, root_id, clear_settings_refs) ImGui.DockBuilderRemoveNodeChildNodes(root_id) end +-- [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch +-- (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!) function ImGui.DockContextRebuildNodes(ctx) local dc = ctx.DockContext ImGui.SaveIniSettingsToMemory() - local root_id = 0 + local root_id = 0 -- Rebuild all ImGui.DockContextClearNodes(ctx, root_id, false) ImGui.DockContextBuildNodesFromSettings(ctx, dc.NodesSettings.Data, dc.NodesSettings.Size) ImGui.DockContextBuildAddWindowsToNodes(ctx, root_id) end +-- Docking context update function, called by NewFrame() function ImGui.DockContextNewFrameUpdateUndocking(ctx) local g = ctx local dc = ctx.DockContext @@ -615,20 +1232,24 @@ function ImGui.DockContextNewFrameUpdateUndocking(ctx) return end + -- Setting NoSplit at runtime merges all nodes if g.IO.ConfigDockingNoSplit then for _, id in ipairs(DockContextNodesSorted(ctx)) do local node = dc.Nodes[id] if node and node:IsRootNode() and node:IsSplitNode() then ImGui.DockBuilderRemoveNodeChildNodes(node.ID) + -- dc.WantFullRebuild = true end end end + -- Process full rebuild if dc.WantFullRebuild then ImGui.DockContextRebuildNodes(ctx) dc.WantFullRebuild = false end + -- Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame) for _, req in dc.Requests:iter() do if req.Type == ImGuiDockRequestType.Undock and req.UndockTargetWindow then ImGui.DockContextProcessUndockWindow(ctx, req.UndockTargetWindow) @@ -638,11 +1259,15 @@ function ImGui.DockContextNewFrameUpdateUndocking(ctx) end end +-- Docking context update function, called by NewFrame() function ImGui.DockContextNewFrameUpdateDocking(ctx) local g = ctx local dc = ctx.DockContext if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then return end + -- [DEBUG] Store hovered dock node. + -- We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using .DockNode is a good shortcut. + -- Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering. g.DebugHoveredDockNode = nil local hovered_window = g.HoveredWindowUnderMovingWindow if hovered_window then @@ -653,6 +1278,7 @@ function ImGui.DockContextNewFrameUpdateDocking(ctx) end end + -- Process Docking requests for _, req in dc.Requests:iter() do if req.Type == ImGuiDockRequestType.Dock then ImGui.DockContextProcessDock(ctx, req) @@ -660,6 +1286,7 @@ function ImGui.DockContextNewFrameUpdateDocking(ctx) end dc.Requests:resize(0) + -- Create windows for each automatic docking nodes for _, id in ipairs(DockContextNodesSorted(ctx)) do local node = dc.Nodes[id] if node and node:IsFloatingNode() then @@ -669,6 +1296,7 @@ function ImGui.DockContextNewFrameUpdateDocking(ctx) end function ImGui.DockContextEndFrame(ctx) + -- Draw backgrounds of node missing their window local g = ctx local dc = g.DockContext for _, id in ipairs(DockContextNodesSorted(ctx)) do @@ -687,17 +1315,23 @@ function ImGui.DockContextFindNodeByID(ctx, id) end function ImGui.DockContextGenNodeID(ctx) + -- Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used) + -- FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0 + -- We should poke in ctx.Nodes to find a suitable ID faster. Even more so trivial that ctx.Nodes lookup is already sorted. local id = 0x0001 while ImGui.DockContextFindNodeByID(ctx, id) ~= nil do id = id + 1 end return id end function ImGui.DockContextAddNode(ctx, id) + -- Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window. if id == 0 then id = ImGui.DockContextGenNodeID(ctx) else IM_ASSERT(ImGui.DockContextFindNodeByID(ctx, id) == nil) end + + -- We don't set node.LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings! local node = ImGuiDockNode(id) ctx.DockContext.Nodes[node.ID] = node return node @@ -726,12 +1360,14 @@ function ImGui.DockContextRemoveNode(ctx, node, merge_sibling_into_parent_node) end end +-- Raw-ish delete function ImGui.DockContextDeleteNode(ctx, node) local dc = ctx.DockContext node.TabBar = nil dc.Nodes[node.ID] = nil end +-- Garbage collect unused nodes (run once at init time) function ImGui.DockContextPruneUnusedSettingsNodes(ctx) local g = ctx local dc = ctx.DockContext @@ -744,9 +1380,10 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) return d end + -- Count child nodes and compute RootID for _, settings in dc.NodesSettings:iter() do if pool[settings.ID] ~= nil then - settings.ID = 0 + settings.ID = 0 -- Duplicate else local parent_data = (settings.ParentNodeId ~= 0) and pool[settings.ParentNodeId] or nil GetOrAdd(settings.ID).RootId = parent_data and parent_data.RootId or settings.ID @@ -757,6 +1394,8 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) end end + -- Count reference to dock ids from dockspaces + -- We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes() for _, settings in dc.NodesSettings:iter() do if settings.ParentWindowId ~= 0 then local window_settings = ImGui.FindWindowSettingsByID(settings.ParentWindowId) @@ -767,6 +1406,8 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) end end + -- Count reference to dock ids from window settings + -- We guard against the possibility of an invalid .ini file (RootID may point to a missing node) for _, settings in g.SettingsWindows:iter() do local dock_id = settings.DockId if dock_id and dock_id ~= 0 then @@ -779,6 +1420,7 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) end end + -- Prune for _, settings in dc.NodesSettings:iter() do local data = pool[settings.ID] if data ~= nil and data.CountWindows <= 1 then @@ -786,8 +1428,8 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) local data_parent = (settings.ParentNodeId ~= 0) and pool[settings.ParentNodeId] or nil local remove = false - remove = remove or (data.CountWindows == 1 and settings.ParentNodeId == 0 and data.CountChildNodes == 0 and bit32.band(settings.Flags, ImGuiDockNodeFlags.CentralNode) == 0) - remove = remove or (data.CountWindows == 0 and settings.ParentNodeId == 0 and data.CountChildNodes == 0) + remove = remove or (data.CountWindows == 1 and settings.ParentNodeId == 0 and data.CountChildNodes == 0 and bit32.band(settings.Flags, ImGuiDockNodeFlags.CentralNode) == 0) -- Floating root node with only 1 window + remove = remove or (data.CountWindows == 0 and settings.ParentNodeId == 0 and data.CountChildNodes == 0) -- Leaf nodes with 0 window remove = remove or (data_root == nil or data_root.CountChildWindows == 0) if remove then DockSettingsRemoveNodeReferences({ settings.ID }, 1) @@ -802,6 +1444,7 @@ end --- @param node_settings_array table # 1-based array function ImGui.DockContextBuildNodesFromSettings(ctx, node_settings_array, node_settings_count) + -- Build nodes for node_n = 1, node_settings_count do local settings = node_settings_array[node_n] if settings.ID ~= 0 and ImGui.DockContextFindNodeByID(ctx, settings.ID) == nil then @@ -822,6 +1465,8 @@ function ImGui.DockContextBuildNodesFromSettings(ctx, node_settings_array, node_ node.SplitAxis = settings.SplitAxis node:SetLocalFlags(bit32.band(settings.Flags, ImGuiDockNodeFlags.SavedFlagsMask_)) + -- Bind host window immediately if it already exist (in case of a rebuild) + -- This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node.HostWindow to be set. local root_node = ImGui.DockNodeGetRootNode(node) node.HostWindow = ImGui.FindWindowByName(DockNodeGetHostWindowTitle(root_node)) end @@ -829,11 +1474,12 @@ function ImGui.DockContextBuildNodesFromSettings(ctx, node_settings_array, node_ end function ImGui.DockContextBuildAddWindowsToNodes(ctx, root_id) + -- Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame) local g = ctx for _, window in g.Windows:iter() do if window.DockId ~= 0 and window.LastFrameActive >= g.FrameCount - 1 and window.DockNode == nil then local node = ImGui.DockContextFindNodeByID(ctx, window.DockId) - IM_ASSERT(node ~= nil) + IM_ASSERT(node ~= nil) -- This should have been called after DockContextBuildNodesFromSettings() if root_id == 0 or ImGui.DockNodeGetRootNode(node).ID == root_id then ImGui.DockNodeAddWindow(node, window, true) end @@ -841,9 +1487,18 @@ function ImGui.DockContextBuildAddWindowsToNodes(ctx, root_id) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: ImGuiDockContext Docking/Undocking functions ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockContextQueueDock() +-- - DockContextQueueUndockWindow() +-- - DockContextQueueUndockNode() +-- - DockContextQueueNotifyRemovedNode() +-- - DockContextProcessDock() +-- - DockContextProcessUndockWindow() +-- - DockContextProcessUndockNode() +-- - DockContextCalcDropPosForDocking() +------------------------------------------------------------------------------- function ImGui.DockContextQueueDock(ctx, target, target_node, payload, split_dir, split_ratio, split_outer) IM_ASSERT(target ~= payload) @@ -883,26 +1538,30 @@ function ImGui.DockContextProcessDock(ctx, req) IM_ASSERT(req.DockTargetWindow ~= nil or req.DockTargetNode ~= nil) local g = ctx - local payload_window = req.DockPayload + local payload_window = req.DockPayload -- Optional local target_window = req.DockTargetWindow local node = req.DockTargetNode + -- Decide which Tab will be selected at the end of the operation local next_selected_id = 0 local payload_node = nil if payload_window then payload_node = payload_window.DockNodeAsHost - payload_window.DockNodeAsHost = nil + payload_window.DockNodeAsHost = nil -- Important to clear this as the node will have its life as a child which might be merged/deleted later. if payload_node and payload_node:IsLeafNode() then next_selected_id = (payload_node.TabBar.NextSelectedTabId ~= 0) and payload_node.TabBar.NextSelectedTabId or payload_node.TabBar.SelectedTabId end if payload_node == nil then next_selected_id = payload_window.TabId end end + -- FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well + -- When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==. if node then IM_ASSERT(node.LastFrameAlive <= g.FrameCount) end if node and target_window and node == target_window.DockNodeAsHost then IM_ASSERT(node.Windows.Size > 0 or node:IsSplitNode() or node:IsCentralNode()) end + -- Create new node and add existing window to it if node == nil then node = ImGui.DockContextAddNode(ctx, 0) node.Pos = ImVec2(target_window.Pos.x, target_window.Pos.y) @@ -917,10 +1576,11 @@ function ImGui.DockContextProcessDock(ctx, req) local split_dir = req.DockSplitDir if split_dir ~= ImGuiDir.None then + -- Split into two, one side will be our payload node unless we are dropping a loose window local split_axis = (split_dir == ImGuiDir.Left or split_dir == ImGuiDir.Right) and ImGuiAxis.X or ImGuiAxis.Y - local split_inheritor_child_idx = (split_dir == ImGuiDir.Left or split_dir == ImGuiDir.Up) and 1 or 0 + local split_inheritor_child_idx = (split_dir == ImGuiDir.Left or split_dir == ImGuiDir.Up) and 1 or 0 -- Current contents will be moved to the opposite side local split_ratio = req.DockSplitRatio - ImGui.DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node) + ImGui.DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node) -- payload_node may be nil here! local new_node = node.ChildNodes[bit32.bxor(split_inheritor_child_idx, 1)] new_node.HostWindow = node.HostWindow node = new_node @@ -928,6 +1588,7 @@ function ImGui.DockContextProcessDock(ctx, req) node:SetLocalFlags(bit32.band(node.LocalFlags, bit32.bnot(ImGuiDockNodeFlags.HiddenTabBar))) if node ~= payload_node then + -- Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!) if node.Windows.Size > 0 and node.TabBar == nil then ImGui.DockNodeAddTabBar(node) for n = 1, node.Windows.Size do @@ -936,9 +1597,13 @@ function ImGui.DockContextProcessDock(ctx, req) end if payload_node ~= nil then + -- Transfer full payload node (with 1+ child windows or child nodes) if payload_node:IsSplitNode() then if node.Windows.Size > 0 then - IM_ASSERT(payload_node.OnlyNodeWithWindows ~= nil) + -- We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node. + -- In this situation, we move the windows of the target node into the currently visible node of the payload. + -- This allows us to preserve some of the underlying dock tree settings nicely. + IM_ASSERT(payload_node.OnlyNodeWithWindows ~= nil) -- The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted. local visible_node = payload_node.OnlyNodeWithWindows if visible_node.TabBar then IM_ASSERT(visible_node.TabBar.Tabs.Size > 0) end ImGui.DockNodeMoveWindows(node, visible_node) @@ -946,6 +1611,8 @@ function ImGui.DockContextProcessDock(ctx, req) DockSettingsRenameNodeReferences(node.ID, visible_node.ID) end if node:IsCentralNode() then + -- Central node property needs to be moved to a leaf node, pick the last focused one. + -- FIXME-DOCK: If we had to transfer other flags here, what would the policy be? local last_focused_node = ImGui.DockContextFindNodeByID(ctx, payload_node.LastFocusedNodeId) IM_ASSERT(last_focused_node ~= nil) local last_focused_root_node = ImGui.DockNodeGetRootNode(last_focused_node) @@ -964,6 +1631,7 @@ function ImGui.DockContextProcessDock(ctx, req) end ImGui.DockContextRemoveNode(ctx, payload_node, true) elseif payload_window then + -- Transfer single window local payload_dock_id = payload_window.DockId node.VisibleWindow = payload_window ImGui.DockNodeAddWindow(node, payload_window, true) @@ -972,14 +1640,24 @@ function ImGui.DockContextProcessDock(ctx, req) end end else + -- When docking a floating single window node we want to reevaluate auto-hiding of the tab bar node.WantHiddenTabBarUpdate = true end + -- Update selection immediately local tab_bar = node.TabBar if tab_bar then tab_bar.NextSelectedTabId = next_selected_id end ImGui.MarkIniSettingsDirty() end +-- Problem: +-- Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more +-- than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic +-- with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be +-- due to missing ImGuiBackendFlags.HasMouseCursors backend flag). +-- Solution: +-- When undocking a window we currently force its maximum size to 90% of the host viewport. +-- Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch). local function FixLargeWindowsWhenUndocking(size, ref_viewport) if ref_viewport == nil then return size end local max_size = ImTrunc(ref_viewport.WorkSize * 0.90) @@ -1008,6 +1686,7 @@ function ImGui.DockContextProcessUndockNode(ctx, node) IM_ASSERT(node.Windows.Size >= 1) if node:IsRootNode() or node:IsCentralNode() then + -- In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload. local new_node = ImGui.DockContextAddNode(ctx, 0) new_node.Pos = ImVec2(node.Pos.x, node.Pos.y) new_node.Size = ImVec2(node.Size.x, node.Size.y) @@ -1016,11 +1695,12 @@ function ImGui.DockContextProcessUndockNode(ctx, node) DockSettingsRenameNodeReferences(node.ID, new_node.ID) node = new_node else + -- Otherwise extract our node and merge our sibling back into the parent node. IM_ASSERT(node.ParentNode.ChildNodes[0] == node or node.ParentNode.ChildNodes[1] == node) local index_in_parent = (node.ParentNode.ChildNodes[0] == node) and 0 or 1 node.ParentNode.ChildNodes[index_in_parent] = nil ImGui.DockNodeTreeMerge(ctx, node.ParentNode, node.ParentNode.ChildNodes[bit32.bxor(index_in_parent, 1)]) - node.ParentNode.AuthorityForViewport = ImGuiDataAuthority.Window + node.ParentNode.AuthorityForViewport = ImGuiDataAuthority.Window -- The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport node.ParentNode = nil end for _, window in node.Windows:iter() do @@ -1035,9 +1715,13 @@ function ImGui.DockContextProcessUndockNode(ctx, node) ImGui.MarkIniSettingsDirty() end +-- This is mostly used for automation. --- @return bool ok, ImVec2? out_pos function ImGui.DockContextCalcDropPosForDocking(target, target_node, payload_window, payload_node, split_dir, split_outer) if target ~= nil and target_node == nil then target_node = target.DockNode end + + -- In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects + -- (which would be functionally identical) we only show the outer one. Reflect this here. if target_node and target_node.ParentNode == nil and target_node:IsCentralNode() and split_dir ~= ImGuiDir.None then split_outer = true end @@ -1048,9 +1732,38 @@ function ImGui.DockContextCalcDropPosForDocking(target, target_node, payload_win return true, r:GetCenter() end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: ImGuiDockNode ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockNodeGetTabOrder() +-- - DockNodeAddWindow() +-- - DockNodeRemoveWindow() +-- - DockNodeMoveChildNodes() +-- - DockNodeMoveWindows() +-- - DockNodeApplyPosSizeToWindows() +-- - DockNodeHideHostWindow() +-- - ImGuiDockNodeFindInfoResults +-- - DockNodeFindInfo() +-- - DockNodeFindWindowByID() +-- - DockNodeUpdateFlagsAndCollapse() +-- - DockNodeUpdateHasCentralNodeFlag() +-- - DockNodeUpdateVisibleFlag() +-- - DockNodeStartMouseMovingWindow() +-- - DockNodeUpdate() +-- - DockNodeUpdateWindowMenu() +-- - DockNodeBeginAmendTabBar() +-- - DockNodeEndAmendTabBar() +-- - DockNodeUpdateTabBar() +-- - DockNodeAddTabBar() +-- - DockNodeRemoveTabBar() +-- - DockNodeIsDropAllowedOne() +-- - DockNodeIsDropAllowed() +-- - DockNodeCalcTabBarLayout() +-- - DockNodeCalcSplitRects() +-- - DockNodeCalcDropRectsAndTestMousePos() +-- - DockNodePreviewDockSetup() +-- - DockNodePreviewDockRender() +------------------------------------------------------------------------------- function ImGui.DockNodeGetTabOrder(window) local tab_bar = window.DockNode.TabBar @@ -1066,11 +1779,15 @@ end function ImGui.DockNodeAddWindow(node, window, add_to_tab_bar) if window.DockNode then + -- Can overwrite an existing window.DockNode (e.g. pointing to a disabled DockSpace node) IM_ASSERT(window.DockNode.ID ~= node.ID) ImGui.DockNodeRemoveWindow(window.DockNode, window, 0) end IM_ASSERT(window.DockNode == nil or window.DockNodeAsHost == nil) + -- If more than 2 windows appeared on the same frame leading to the creation of a new hosting window, + -- we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame). + -- We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin() if node.HostWindow == nil and node.Windows.Size == 1 and node.Windows.Data[1].WasActive == false then DockNodeHideWindowDuringHostWindowCreation(node.Windows.Data[1]) end @@ -1082,17 +1799,22 @@ function ImGui.DockNodeAddWindow(node, window, add_to_tab_bar) window.DockIsActive = (node.Windows.Size > 1) window.DockTabWantClose = false + -- When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage. + -- In particular it is important we init the viewport from the first window so we don't create two viewports and drop one. if node.HostWindow == nil and node:IsFloatingNode() then if node.AuthorityForPos == ImGuiDataAuthority.Auto then node.AuthorityForPos = ImGuiDataAuthority.Window end if node.AuthorityForSize == ImGuiDataAuthority.Auto then node.AuthorityForSize = ImGuiDataAuthority.Window end if node.AuthorityForViewport == ImGuiDataAuthority.Auto then node.AuthorityForViewport = ImGuiDataAuthority.Window end end + -- Add to tab bar if requested if add_to_tab_bar then if node.TabBar == nil then ImGui.DockNodeAddTabBar(node) node.TabBar.SelectedTabId = node.SelectedTabId node.TabBar.NextSelectedTabId = node.SelectedTabId + + -- Add existing windows for n = 1, node.Windows.Size - 1 do ImGui.TabBarAddTab(node.TabBar, ImGuiTabItemFlags.None, node.Windows.Data[n]) end @@ -1102,6 +1824,7 @@ function ImGui.DockNodeAddWindow(node, window, add_to_tab_bar) ImGui.DockNodeUpdateVisibleFlag(node) + -- Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame. if node.HostWindow then ImGui.UpdateWindowParentAndRootLinks(window, bit32.bor(window.Flags, ImGuiWindowFlags.ChildWindow), node.HostWindow) end @@ -1109,6 +1832,8 @@ end function ImGui.DockNodeRemoveWindow(node, window, save_dock_id) IM_ASSERT(window.DockNode == node) + -- IM_ASSERT(window.RootWindowDockTree == node.HostWindow) + -- IM_ASSERT(window.LastFrameActive < g.FrameCount) -- We may call this from Begin() IM_ASSERT(save_dock_id == 0 or save_dock_id == node.ID) window.DockNode = nil @@ -1117,20 +1842,24 @@ function ImGui.DockNodeRemoveWindow(node, window, save_dock_id) window.DockId = save_dock_id window.Flags = bit32.band(window.Flags, bit32.bnot(ImGuiWindowFlags.ChildWindow)) if window.ParentWindow then window.ParentWindow.DC.ChildWindows:find_erase(window) end - ImGui.UpdateWindowParentAndRootLinks(window, window.Flags, nil) + ImGui.UpdateWindowParentAndRootLinks(window, window.Flags, nil) -- Update immediately if node.HostWindow and node.HostWindow.ViewportOwned then + -- When undocking from a user interaction this will always run in NewFrame() and have not much effect. + -- But mid-frame, if we clear viewport we need to mark window as hidden as well. window.Viewport = nil window.ViewportId = 0 window.ViewportOwned = false window.Hidden = true end + -- Remove window local idx = node.Windows:find_index(window) IM_ASSERT(idx ~= nil) node.Windows:erase(idx) if node.VisibleWindow == window then node.VisibleWindow = nil end + -- Remove tab and possibly tab bar node.WantHiddenTabBarUpdate = true if node.TabBar then ImGui.TabBarRemoveTab(node.TabBar, window.TabId) @@ -1139,16 +1868,20 @@ function ImGui.DockNodeRemoveWindow(node, window, save_dock_id) ImGui.DockNodeRemoveTabBar(node) end end + if node.Windows.Size == 0 and not node:IsCentralNode() and not node:IsDockSpace() and window.DockId ~= node.ID then + -- Automatic dock node delete themselves if they are not holding at least one tab ImGui.DockContextRemoveNode(ImGui.GetCurrentContext(), node, true) return end if node.Windows.Size == 1 and not node:IsCentralNode() and node.HostWindow then local remaining_window = node.Windows.Data[1] + -- Note: we used to transport viewport ownership here. remaining_window.Collapsed = node.HostWindow.Collapsed end + -- Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree ImGui.DockNodeUpdateVisibleFlag(node) end @@ -1165,16 +1898,19 @@ function ImGui.DockNodeMoveChildNodes(dst_node, src_node) end function ImGui.DockNodeMoveWindows(dst_node, src_node) + -- Insert tabs in the same orders as currently ordered (node.Windows isn't ordered) IM_ASSERT(src_node and dst_node and dst_node ~= src_node) local src_tab_bar = src_node.TabBar if src_tab_bar ~= nil then IM_ASSERT(src_node.Windows.Size <= src_node.TabBar.Tabs.Size) end + -- If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.) local move_tab_bar = (src_tab_bar ~= nil) and (dst_node.TabBar == nil) if move_tab_bar then dst_node.TabBar = src_node.TabBar src_node.TabBar = nil end + -- Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar(). -- Snapshot: DockNodeAddWindow() won't touch src_node.Windows since window.DockNode is cleared first local windows = {} for i = 1, src_node.Windows.Size do windows[i] = src_node.Windows.Data[i] end @@ -1193,7 +1929,7 @@ end function ImGui.DockNodeApplyPosSizeToWindows(node) for _, window in node.Windows:iter() do - ImGui.SetWindowPos(window, node.Pos, ImGuiCond.Always) + ImGui.SetWindowPos(window, node.Pos, ImGuiCond.Always) -- We don't assign directly to Pos because it can break the calculation of SizeContents on next frame ImGui.SetWindowSize(window, node.Size, ImGuiCond.Always) end end @@ -1210,13 +1946,14 @@ function ImGui.DockNodeHideHostWindow(node) if node.TabBar then ImGui.DockNodeRemoveTabBar(node) end end +-- Search function called once by root node in DockNodeUpdate() local function DockNodeFindInfo(node, info) if node.Windows.Size > 0 then if info.FirstNodeWithWindows == nil then info.FirstNodeWithWindows = node end info.CountNodesWithWindows = info.CountNodesWithWindows + 1 end if node:IsCentralNode() then - IM_ASSERT(info.CentralNode == nil) + IM_ASSERT(info.CentralNode == nil) -- Should be only one IM_ASSERT(node:IsLeafNode(), "If you get this assert: please submit .ini file + repro of actions leading to this.") info.CentralNode = node end @@ -1233,18 +1970,27 @@ function ImGui.DockNodeFindWindowByID(node, id) return nil end +-- - Remove inactive windows/nodes. +-- - Update visibility flag. function ImGui.DockNodeUpdateFlagsAndCollapse(node) local g = ImGui.GetCurrentContext() IM_ASSERT(node.ParentNode == nil or node.ParentNode.ChildNodes[0] == node or node.ParentNode.ChildNodes[1] == node) + -- Inherit most flags if node.ParentNode then node.SharedFlags = bit32.band(node.ParentNode.SharedFlags, ImGuiDockNodeFlags.SharedFlagsInheritMask_) end + -- Recurse into children + -- There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'. + -- If 'node.ChildNode[0]' delete itself, then 'node.ChildNode[1].Windows' will be moved into 'node' + -- If 'node.ChildNode[1]' delete itself, then 'node.ChildNode[0].Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless) node.HasCentralNodeChild = false if node.ChildNodes[0] then ImGui.DockNodeUpdateFlagsAndCollapse(node.ChildNodes[0]) end if node.ChildNodes[1] then ImGui.DockNodeUpdateFlagsAndCollapse(node.ChildNodes[1]) end + -- Remove inactive windows, collapse nodes + -- Merge node flags overrides stored in windows node.LocalFlagsInWindows = ImGuiDockNodeFlags.None local window_n = 1 while window_n <= node.Windows.Size do @@ -1253,35 +1999,40 @@ function ImGui.DockNodeUpdateFlagsAndCollapse(node) local node_was_active = (node.LastFrameActive + 1 == g.FrameCount) local remove = false - remove = remove or (node_was_active and (window.WasActive == false)) - remove = remove or (node_was_active and (node.WantCloseAll or node.WantCloseTabId == window.TabId) and window.HasCloseButton and bit32.band(window.Flags, ImGuiWindowFlags.UnsavedDocument) == 0) + remove = remove or (node_was_active and (window.WasActive == false)) -- Can't use 'window.LastFrameActive + 1 < g.FrameCount'. (see #9151) + remove = remove or (node_was_active and (node.WantCloseAll or node.WantCloseTabId == window.TabId) and window.HasCloseButton and bit32.band(window.Flags, ImGuiWindowFlags.UnsavedDocument) == 0) -- Submit all _expected_ closure from last frame remove = remove or window.DockTabWantClose if remove then window.DockTabWantClose = false if node.Windows.Size == 1 and not node:IsCentralNode() then ImGui.DockNodeHideHostWindow(node) node.State = ImGuiDockNodeState.HostWindowHiddenBecauseSingleWindow - ImGui.DockNodeRemoveWindow(node, window, node.ID) + ImGui.DockNodeRemoveWindow(node, window, node.ID) -- Will delete the node so it'll be invalid on return return end ImGui.DockNodeRemoveWindow(node, window, node.ID) else + -- FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this. + -- node.LocalFlagsInWindow = bit32.band(node.LocalFlagsInWindow, bit32.bnot(window.WindowClass.DockNodeFlagsOverrideClear)) node.LocalFlagsInWindows = bit32.bor(node.LocalFlagsInWindows, window.WindowClass.DockNodeFlagsOverrideSet) window_n = window_n + 1 end end node:UpdateMergedFlags() + -- Auto-hide tab bar option local node_flags = node.MergedFlags if node.WantHiddenTabBarUpdate and node.Windows.Size == 1 and bit32.band(node_flags, ImGuiDockNodeFlags.AutoHideTabBar) ~= 0 and not node:IsHiddenTabBar() then node.WantHiddenTabBarToggle = true end node.WantHiddenTabBarUpdate = false + -- Cancel toggling if we know our tab bar is enforced to be hidden at all times if node.WantHiddenTabBarToggle and node.VisibleWindow and bit32.band(node.VisibleWindow.WindowClass.DockNodeFlagsOverrideSet, ImGuiDockNodeFlags.HiddenTabBar) ~= 0 then node.WantHiddenTabBarToggle = false end + -- Apply toggles at a single point of the frame (here!) local prev_local_flags = node.LocalFlags if node.Windows.Size > 1 then node:SetLocalFlags(bit32.band(node.LocalFlags, bit32.bnot(ImGuiDockNodeFlags.HiddenTabBar))) @@ -1289,13 +2040,14 @@ function ImGui.DockNodeUpdateFlagsAndCollapse(node) node:SetLocalFlags(bit32.bxor(node.LocalFlags, ImGuiDockNodeFlags.HiddenTabBar)) end if bit32.band(bit32.bxor(node.LocalFlags, prev_local_flags), ImGuiDockNodeFlags.SavedFlagsMask_) ~= 0 then - ImGui.MarkIniSettingsDirty() + ImGui.MarkIniSettingsDirty() -- Bit flaky to only do this here. Perhaps compare node flags every frame? #9380 end node.WantHiddenTabBarToggle = false ImGui.DockNodeUpdateVisibleFlag(node) end +-- This is rarely called as DockNodeUpdateForRootNode() generally does it most frames. function ImGui.DockNodeUpdateHasCentralNodeChild(node) node.HasCentralNodeChild = false if node.ChildNodes[0] then ImGui.DockNodeUpdateHasCentralNodeChild(node.ChildNodes[0]) end @@ -1310,6 +2062,7 @@ function ImGui.DockNodeUpdateHasCentralNodeChild(node) end function ImGui.DockNodeUpdateVisibleFlag(node) + -- Update visibility flag local is_visible = (node.ParentNode == nil) and node:IsDockSpace() or node:IsCentralNode() is_visible = is_visible or (node.Windows.Size > 0) is_visible = is_visible or (node.ChildNodes[0] ~= nil and node.ChildNodes[0].IsVisible) @@ -1322,13 +2075,17 @@ function ImGui.DockNodeStartMouseMovingWindow(node, window) IM_ASSERT(node.WantMouseMove == true) ImGui.StartMouseMovingWindow(window) ImVec2_Copy(g.ActiveIdClickOffset, g.IO.MouseClickedPos[0] - node.Pos) - g.MovingWindow = window + g.MovingWindow = window -- If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision. node.WantMouseMove = false end +-- Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class. function ImGui.DockNodeUpdateForRootNode(node) ImGui.DockNodeUpdateFlagsAndCollapse(node) + -- - Setup central node pointers + -- - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!) + -- Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing local info = { CentralNode = nil, FirstNodeWithWindows = nil, CountNodesWithWindows = 0 } DockNodeFindInfo(node, info) node.CentralNode = info.CentralNode @@ -1338,6 +2095,9 @@ function ImGui.DockNodeUpdateForRootNode(node) node.LastFocusedNodeId = info.FirstNodeWithWindows.ID end + -- Copy the window class from of our first window so it can be used for proper dock filtering. + -- When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy. + -- FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec. local first_node_with_windows = info.FirstNodeWithWindows if first_node_with_windows then node.WindowClass = first_node_with_windows.Windows.Data[1].WindowClass @@ -1357,6 +2117,11 @@ function ImGui.DockNodeUpdateForRootNode(node) end local function DockNodeSetupHostWindow(node, host_window) + -- Remove ourselves from any previous different host window + -- This can happen if a user mistakenly does (see #4295 for details): + -- - N+0: DockBuilderAddNode(id, 0) -- missing ImGuiDockNodeFlags.DockSpace + -- - N+1: NewFrame() -- will create floating host window for that node + -- - N+1: DockSpace(id) -- requalify node as dockspace, moving host window if node.HostWindow and node.HostWindow ~= host_window and node.HostWindow.DockNodeAsHost == node then node.HostWindow.DockNodeAsHost = nil end @@ -1374,8 +2139,10 @@ function ImGui.DockNodeUpdate(node) node.OnlyNodeWithWindows = nil if node:IsRootNode() then ImGui.DockNodeUpdateForRootNode(node) end + -- Remove tab bar if not needed if node.TabBar and node:IsNoTabBar() then ImGui.DockNodeRemoveTabBar(node) end + -- Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId) local want_to_hide_host_window = false if node:IsFloatingNode() then if node.Windows.Size <= 1 and node:IsLeafNode() then @@ -1387,6 +2154,7 @@ function ImGui.DockNodeUpdate(node) end if want_to_hide_host_window then if node.Windows.Size == 1 then + -- Floating window pos/size is authoritative local single_window = node.Windows.Data[1] node.Pos = ImVec2(single_window.Pos.x, single_window.Pos.y) node.Size = ImVec2(single_window.SizeFull.x, single_window.SizeFull.y) @@ -1394,6 +2162,7 @@ function ImGui.DockNodeUpdate(node) node.AuthorityForSize = ImGuiDataAuthority.Window node.AuthorityForViewport = ImGuiDataAuthority.Window + -- Transfer focus immediately so when we revert to a regular window it is immediately selected if node.HostWindow and g.NavWindow == node.HostWindow then ImGui.FocusWindow(single_window) end @@ -1418,9 +2187,20 @@ function ImGui.DockNodeUpdate(node) return end + -- In some circumstance we will defer creating the host window (so everything will be kept hidden), + -- while the expected visible window is resizing itself. + -- This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled, + -- otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up: + -- N+0: Begin(): window created (with no known size), node is created + -- N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible + -- N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible + -- We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code. + -- It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin(). + -- In reality it isn't very important as user quickly ends up with size data in .ini file. if node.IsVisible and node.HostWindow == nil and node:IsFloatingNode() and node:IsLeafNode() then IM_ASSERT(node.Windows.Size > 0) local ref_window = nil + -- Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them! if node.SelectedTabId ~= 0 then ref_window = ImGui.DockNodeFindWindowByID(node, node.SelectedTabId) end if ref_window == nil then ref_window = node.Windows.Data[1] end if ref_window.AutoFitFramesX > 0 or ref_window.AutoFitFramesY > 0 then @@ -1431,9 +2211,11 @@ function ImGui.DockNodeUpdate(node) local node_flags = node.MergedFlags + -- Decide if the node will have a close button and a window menu button node.HasWindowMenuButton = (node.Windows.Size > 0) and bit32.band(node_flags, ImGuiDockNodeFlags.NoWindowMenuButton) == 0 node.HasCloseButton = false for _, window in node.Windows:iter() do + -- FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call. node.HasCloseButton = node.HasCloseButton or window.HasCloseButton window.DockIsActive = (node.Windows.Size > 1) end @@ -1441,40 +2223,47 @@ function ImGui.DockNodeUpdate(node) node.HasCloseButton = false end + -- Bind or create host window local host_window = nil local beginned_into_host_window = false if node:IsDockSpace() then + -- [Explicit root dockspace node] IM_ASSERT(node.HostWindow) host_window = node.HostWindow else + -- [Automatic root or child nodes] if node:IsRootNode() and node.IsVisible then local ref_window = (node.Windows.Size > 0) and node.Windows.Data[1] or nil + -- Sync Pos if node.AuthorityForPos == ImGuiDataAuthority.Window and ref_window then ImGui.SetNextWindowPos(ref_window.Pos) elseif node.AuthorityForPos == ImGuiDataAuthority.DockNode then ImGui.SetNextWindowPos(node.Pos) end + -- Sync Size if node.AuthorityForSize == ImGuiDataAuthority.Window and ref_window then ImGui.SetNextWindowSize(ref_window.SizeFull) elseif node.AuthorityForSize == ImGuiDataAuthority.DockNode then ImGui.SetNextWindowSize(node.Size) end + -- Sync Collapsed if node.AuthorityForSize == ImGuiDataAuthority.Window and ref_window then ImGui.SetNextWindowCollapsed(ref_window.Collapsed) end ImGui.SetNextWindowClass(node.WindowClass) + -- Begin into the host window local window_label = DockNodeGetHostWindowTitle(node) local window_flags = bit32.bor(ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoScrollWithMouse, ImGuiWindowFlags.DockNodeHost) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoFocusOnAppearing) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoNavFocus, ImGuiWindowFlags.NoCollapse) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoTitleBar) - ImGui.SetNextWindowBgAlpha(0.0) + ImGui.SetNextWindowBgAlpha(0.0) -- Don't set ImGuiWindowFlags.NoBackground because it disables borders ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0, 0)) ImGui.Begin(window_label, nil, window_flags) ImGui.PopStyleVar() @@ -1486,6 +2275,12 @@ function ImGui.DockNodeUpdate(node) node.Pos = ImVec2(host_window.Pos.x, host_window.Pos.y) node.Size = ImVec2(host_window.Size.x, host_window.Size.y) + -- We set ImGuiWindowFlags.NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow) + -- But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags. + -- One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again. + -- When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window + -- during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back + -- after the dock host window, losing their top-most status. if node.HostWindow.Appearing then ImGui.BringWindowToDisplayFront(node.HostWindow) end node.AuthorityForPos = ImGuiDataAuthority.Auto @@ -1502,21 +2297,23 @@ function ImGui.DockNodeUpdate(node) ImGui.DockNodeStartMouseMovingWindow(node, node.HostWindow) end end - node.RefViewportId = 0 + node.RefViewportId = 0 -- Clear when we have a host window + -- Update focused node (the one whose title bar is highlight) within a node tree if node:IsSplitNode() then IM_ASSERT(node.TabBar == nil) end if node:IsRootNode() then local p_window = g.NavWindow and g.NavWindow.RootWindow or nil while p_window ~= nil and p_window.DockNode ~= nil do local p_node = ImGui.DockNodeGetRootNode(p_window.DockNode) if p_node == node then - node.LastFocusedNodeId = p_window.DockNode.ID + node.LastFocusedNodeId = p_window.DockNode.ID -- Note: not using root node ID! break end p_window = p_node.HostWindow and p_node.HostWindow.RootWindow or nil end end + -- Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace local central_node = node.CentralNode local central_node_hole = node:IsRootNode() and host_window ~= nil and bit32.band(node_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0 and central_node ~= nil and central_node:IsEmpty() local central_node_hole_register_hit_test_hole = central_node_hole @@ -1527,7 +2324,10 @@ function ImGui.DockNodeUpdate(node) end end if central_node_hole_register_hit_test_hole then - IM_ASSERT(node:IsDockSpace()) + -- We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily. + -- (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen + -- covering passthru node we'd have a gap on the edge not covered by the hole) + IM_ASSERT(node:IsDockSpace()) -- We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window.ParentNode local root_node = ImGui.DockNodeGetRootNode(central_node) local root_rect = ImRect(root_node.Pos, root_node.Pos + root_node.Size) local hole_rect = ImRect(central_node.Pos, central_node.Pos + central_node.Size) @@ -1535,6 +2335,7 @@ function ImGui.DockNodeUpdate(node) if hole_rect.Max.x < root_rect.Max.x then hole_rect.Max.x = hole_rect.Max.x - g.WindowsBorderHoverPadding end if hole_rect.Min.y > root_rect.Min.y then hole_rect.Min.y = hole_rect.Min.y + g.WindowsBorderHoverPadding end if hole_rect.Max.y < root_rect.Max.y then hole_rect.Max.y = hole_rect.Max.y - g.WindowsBorderHoverPadding end + -- GetForegroundDrawList():AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255)) if central_node_hole and not IsRectInverted(hole_rect) then ImGui.SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min) if host_window.ParentWindow then @@ -1543,6 +2344,7 @@ function ImGui.DockNodeUpdate(node) end end + -- Update position/size, process and draw resizing splitters if node:IsRootNode() and host_window then ImGui.DockNodeTreeUpdatePosSize(node, host_window.Pos, host_window.Size) ImGui.PushStyleColor(ImGuiCol.Separator, g.Style.Colors[ImGuiCol.Border]) @@ -1552,6 +2354,7 @@ function ImGui.DockNodeUpdate(node) ImGui.PopStyleColor(3) end + -- Draw empty node background (currently can only be the Central Node) if host_window and node:IsEmpty() and node.IsVisible then host_window.DrawList:ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG) node.LastBgColor = (bit32.band(node_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0) and 0 or ImGui.GetColorU32(ImGuiCol.DockingEmptyBg) @@ -1561,6 +2364,9 @@ function ImGui.DockNodeUpdate(node) node.IsBgDrawnThisFrame = true end + -- Draw whole dockspace background if ImGuiDockNodeFlags.PassthruCentralNode if set. + -- We need to draw a background at the root level if requested by ImGuiDockNodeFlags.PassthruCentralNode, but we will only know the correct pos/size + -- _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order! local render_dockspace_bg = node:IsRootNode() and host_window ~= nil and bit32.band(node_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0 if render_dockspace_bg and node.IsVisible then host_window.DrawList:ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG) @@ -1571,6 +2377,7 @@ function ImGui.DockNodeUpdate(node) end end + -- Draw and populate Tab Bar if host_window then host_window.DrawList:ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG) end if host_window and node.Windows.Size > 0 then ImGui.DockNodeUpdateTabBar(node, host_window) @@ -1585,20 +2392,27 @@ function ImGui.DockNodeUpdate(node) node.SelectedTabId = node.Windows.Data[1].TabId end + -- Draw payload drop target if host_window and node.IsVisible then if node:IsRootNode() and (g.MovingWindow == nil or g.MovingWindow.RootWindowDockTree ~= host_window) then ImGui.BeginDockableDragDropTarget(host_window) end end + -- We update this after DockNodeUpdateTabBar() node.LastFrameActive = g.FrameCount + -- Recurse into children + -- FIXME-DOCK FIXME-OPT: Should not need to recurse into children if host_window then if node.ChildNodes[0] then ImGui.DockNodeUpdate(node.ChildNodes[0]) end if node.ChildNodes[1] then ImGui.DockNodeUpdate(node.ChildNodes[1]) end + + -- Render outer borders last (after the tab bar) if node:IsRootNode() then ImGui.RenderWindowOuterBorders(host_window) end end + -- End host window if beginned_into_host_window then ImGui.End() end end @@ -1608,6 +2422,7 @@ local GWindowDockStyleColors = { } ImGui.GWindowDockStyleColors = GWindowDockStyleColors +-- Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame. local function TabItemComparerByDockOrder(ta, tb) local a, b = ta.Window, tb.Window local ao = (a.DockOrder == -1) and INT_MAX or a.DockOrder @@ -1616,12 +2431,19 @@ local function TabItemComparerByDockOrder(ta, tb) return a.BeginOrderWithinContext < b.BeginOrderWithinContext end +-- Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node. +-- This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented) +-- Custom overrides may want to decorate, group, sort entries. +-- Please note those are internal structures: if you copy this expect occasional breakage. +-- (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler) function ImGui.DockNodeWindowMenuHandler_Default(ctx, node, tab_bar) if tab_bar.Tabs.Size == 1 then + -- "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table. if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.DockingHideTabBar), nil, node:IsHiddenTabBar()) then node.WantHiddenTabBarToggle = true end else + -- Display a selectable list of windows in this docking node for tab_n = 1, tab_bar.Tabs.Size do local tab = tab_bar.Tabs.Data[tab_n] if bit32.band(tab.Flags, ImGuiTabItemFlags.Button) == 0 then @@ -1636,6 +2458,7 @@ function ImGui.DockNodeWindowMenuHandler_Default(ctx, node, tab_bar) end function ImGui.DockNodeWindowMenuUpdate(node, tab_bar) + -- Try to position the menu so it is more likely to stays within the same viewport local g = ImGui.GetCurrentContext() if g.Style.WindowMenuButtonPosition == ImGuiDir.Left then ImGui.SetNextWindowPos(ImVec2(node.Pos.x, node.Pos.y + ImGui.GetFrameHeight()), ImGuiCond.Always, ImVec2(0.0, 0.0)) @@ -1649,6 +2472,7 @@ function ImGui.DockNodeWindowMenuUpdate(node, tab_bar) end end +-- User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button. function ImGui.DockNodeBeginAmendTabBar(node) if node.TabBar == nil or node.HostWindow == nil then return false end if bit32.band(node.MergedFlags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then return false end @@ -1667,11 +2491,15 @@ function ImGui.DockNodeEndAmendTabBar() end local function IsDockNodeTitleBarHighlighted(node, root_node) + -- CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy) local g = ImGui.GetCurrentContext() if g.NavWindowingTarget then return g.NavWindowingTarget.DockNode == node end + + -- FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window) if g.NavWindow and root_node.LastFocusedNodeId == node.ID then + -- FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node) local parent_window = g.NavWindow.RootWindow while bit32.band(parent_window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 do parent_window = parent_window.ParentWindow.RootWindow @@ -1686,6 +2514,7 @@ local function IsDockNodeTitleBarHighlighted(node, root_node) return false end +-- Submit the tab bar corresponding to a dock node and various housekeeping details. function ImGui.DockNodeUpdateTabBar(node, host_window) local g = ImGui.GetCurrentContext() local style = g.Style @@ -1694,30 +2523,37 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) node.WantCloseAll = false node.WantCloseTabId = 0 + -- Decide if we should use a focused title bar color local is_focused = false local root_node = ImGui.DockNodeGetRootNode(node) if IsDockNodeTitleBarHighlighted(node, root_node) then is_focused = true end + -- Hidden tab bar will show a triangle on the upper-left (in Begin) if node:IsHiddenTabBar() or node:IsNoTabBar() then node.VisibleWindow = (node.Windows.Size > 0) and node.Windows.Data[1] or nil node.IsFocused = is_focused if is_focused then node.LastFrameFocused = g.FrameCount end if node.VisibleWindow then + -- Notify root of visible window (used to display title in OS task bar) if is_focused or root_node.VisibleWindow == nil then root_node.VisibleWindow = node.VisibleWindow end if node.TabBar then node.TabBar.VisibleTabId = node.VisibleWindow.TabId end end return end + -- Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed local backup_skip_item = host_window.SkipItems if not node:IsDockSpace() then host_window.SkipItems = false host_window.DC.NavLayerCurrent = ImGuiNavLayer.Menu end + -- Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID. + -- This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs, + -- as docked windows themselves will override the stack with their own root ID. ImGui.PushOverrideID(node.ID) local tab_bar = node.TabBar - local tab_bar_is_recreated = (tab_bar == nil) + local tab_bar_is_recreated = (tab_bar == nil) -- Tab bar are automatically destroyed when a node gets hidden if tab_bar == nil then ImGui.DockNodeAddTabBar(node) tab_bar = node.TabBar @@ -1729,6 +2565,8 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) local node_flags = node.MergedFlags local has_window_menu_button = bit32.band(node_flags, ImGuiDockNodeFlags.NoWindowMenuButton) == 0 and (style.WindowMenuButtonPosition ~= ImGuiDir.None) + -- In a dock node, the Collapse Button turns into the Window Menu button. + -- FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes? if has_window_menu_button and ImGui.IsPopupOpen("#WindowMenu") then local next_selected_tab_id = tab_bar.NextSelectedTabId ImGui.DockNodeWindowMenuUpdate(node, tab_bar) @@ -1738,8 +2576,10 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) is_focused = is_focused or node.IsFocused end + -- Layout local title_bar_rect, tab_bar_rect, window_menu_button_pos, close_button_pos = ImGui.DockNodeCalcTabBarLayout(node) + -- Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value. local tabs_count_old = tab_bar.Tabs.Size for window_n = 1, node.Windows.Size do local window = node.Windows.Data[window_n] @@ -1748,13 +2588,15 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) end end + -- Title bar if is_focused then node.LastFrameFocused = g.FrameCount end local title_bar_col = ImGui.GetColorU32(host_window.Collapsed and ImGuiCol.TitleBgCollapsed or (is_focused and ImGuiCol.TitleBgActive or ImGuiCol.TitleBg)) local rounding_flags = ImGui.CalcRoundingFlagsForRectInRect(title_bar_rect, host_window:Rect(), g.Style.DockingSeparatorSize) host_window.DrawList:AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window.WindowRounding, rounding_flags) + -- Docking/Collapse button if has_window_menu_button then - if ImGui.CollapseButton(host_window:GetID("#COLLAPSE"), window_menu_button_pos, node) then + if ImGui.CollapseButton(host_window:GetID("#COLLAPSE"), window_menu_button_pos, node) then -- == DockNodeGetWindowMenuButtonId(node) ImGui.OpenPopup("#WindowMenu") end if ImGui.IsItemActive() then focus_tab_id = tab_bar.SelectedTabId end @@ -1763,9 +2605,11 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) end end + -- If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value local tabs_unsorted_start = tab_bar.Tabs.Size -- 0-based local tab_n = tab_bar.Tabs.Size - 1 while tab_n >= 0 and bit32.band(tab_bar.Tabs.Data[tab_n + 1].Flags, ImGuiTabItemFlags.Unsorted) ~= 0 do + -- FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? local t = tab_bar.Tabs.Data[tab_n + 1] t.Flags = bit32.band(t.Flags, bit32.bnot(ImGuiTabItemFlags.Unsorted)) tabs_unsorted_start = tab_n @@ -1778,10 +2622,12 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) for i, t in ipairs(slice) do tab_bar.Tabs.Data[tabs_unsorted_start + i] = t end end + -- Apply NavWindow focus back to the tab bar if g.NavWindow and g.NavWindow.RootWindow.DockNode == node then tab_bar.SelectedTabId = g.NavWindow.RootWindow.TabId end + -- Selected newly added tabs, or persistent tab ID if the tab bar was just recreated if tab_bar_is_recreated and ImGui.TabBarFindTabByID(tab_bar, node.SelectedTabId) ~= nil then tab_bar.SelectedTabId = node.SelectedTabId tab_bar.NextSelectedTabId = node.SelectedTabId @@ -1790,27 +2636,32 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) tab_bar.NextSelectedTabId = tab_bar.SelectedTabId end - local tab_bar_flags = bit32.bor(ImGuiTabBarFlags.Reorderable, ImGuiTabBarFlags.AutoSelectNewTabs) + -- Begin tab bar + local tab_bar_flags = bit32.bor(ImGuiTabBarFlags.Reorderable, ImGuiTabBarFlags.AutoSelectNewTabs) -- | ImGuiTabBarFlags.NoTabListScrollingButtons) tab_bar_flags = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.SaveSettings, ImGuiTabBarFlags.DockNode) - tab_bar_flags = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.FittingPolicyMixed) + tab_bar_flags = bit32.bor(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 = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.DrawSelectedOverline) if not host_window.Collapsed and is_focused then tab_bar_flags = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.IsFocused) end - tab_bar.ID = node.ID - tab_bar.SeparatorMinX = node.Pos.x + host_window.WindowBorderSize + tab_bar.ID = node.ID -- GetID("#TabBar") + tab_bar.SeparatorMinX = node.Pos.x + host_window.WindowBorderSize -- Separator cover the whole node width tab_bar.SeparatorMaxX = node.Pos.x + node.Size.x - host_window.WindowBorderSize ImGui.BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags) + -- host_window.DrawList:AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255)) + -- Backup style colors local backup_style_cols = {} for color_n = 0, ImGuiWindowDockStyleCol.COUNT - 1 do local c = g.Style.Colors[GWindowDockStyleColors[color_n]] backup_style_cols[color_n] = ImVec4(c.x, c.y, c.z, c.w) end + -- Submit actual tabs node.VisibleWindow = nil for window_n = 1, node.Windows.Size do local window = node.Windows.Data[window_n] + -- FIXME: Not sure if that's still taken/useful, as windows are normally removed in DockNodeUpdateFlagsAndCollapse(). if not (window.LastFrameActive + 1 < g.FrameCount and node_was_active) then local tab_item_flags = 0 tab_item_flags = bit32.bor(tab_item_flags, window.WindowClass.TabItemFlagsOverrideSet or 0) @@ -1821,33 +2672,42 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) tab_item_flags = bit32.bor(tab_item_flags, ImGuiTabItemFlags.NoCloseWithMiddleMouseButton) end + -- Apply stored style overrides for the window for color_n = 0, ImGuiWindowDockStyleCol.COUNT - 1 do ImVec4_Copy(g.Style.Colors[GWindowDockStyleColors[color_n]], ImGui.ColorConvertU32ToFloat4(window.DockStyle.Colors[color_n])) end + -- Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so) local _, tab_open = ImGui.TabItemEx(tab_bar, window.Name, window.HasCloseButton and true or nil, tab_item_flags, window) if tab_open == false then node.WantCloseTabId = window.TabId end if tab_bar.VisibleTabId == window.TabId then node.VisibleWindow = window end + -- 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 = ImRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max) + -- Update navigation ID on menu layer if g.NavWindow and g.NavWindow.RootWindow == window and bit32.band(window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) == 0 then host_window.NavLastIds[1] = window.TabId end end end + -- Restore style colors for color_n = 0, ImGuiWindowDockStyleCol.COUNT - 1 do ImVec4_Copy(g.Style.Colors[GWindowDockStyleColors[color_n]], backup_style_cols[color_n]) end + -- Notify root of visible window (used to display title in OS task bar) if node.VisibleWindow then if is_focused or root_node.VisibleWindow == nil then root_node.VisibleWindow = node.VisibleWindow end end + -- Close button (after VisibleWindow was updated) + -- Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow.TabId may be ~= from tab_bar.SelectedTabId local close_button_is_enabled = node.HasCloseButton and node.VisibleWindow and node.VisibleWindow.HasCloseButton local close_button_is_visible = node.HasCloseButton + -- local close_button_is_visible = close_button_is_enabled -- Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one) if close_button_is_visible then if not close_button_is_enabled then ImGui.PushItemFlag(ImGuiItemFlags.Disabled, true) @@ -1858,39 +2718,55 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) node.WantCloseAll = true for n = 1, tab_bar.Tabs.Size do ImGui.TabBarCloseTab(tab_bar, tab_bar.Tabs.Data[n]) end end + -- if IsItemActive() then + -- focus_tab_id = tab_bar.SelectedTabId if not close_button_is_enabled then ImGui.PopStyleColor() ImGui.PopItemFlag() end end + -- When clicking on the title bar outside of tabs, we still focus the selected tab for that node + -- FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them. local title_bar_id = host_window:GetID("#TITLEBAR") if g.HoveredId == 0 or g.HoveredId == title_bar_id or g.ActiveId == title_bar_id then + -- AllowOverlap mode required for appending into dock node tab bar, + -- otherwise dragging window will steal HoveredId and amended tabs cannot get them. ImGui.KeepAliveID(title_bar_id) local _, _, held = ImGui.ButtonBehavior(title_bar_rect, title_bar_id, ImGuiButtonFlags.AllowOverlap) if g.HoveredId == title_bar_id then g.LastItemData.ID = title_bar_id end if held then if ImGui.IsMouseClicked(0) then focus_tab_id = tab_bar.SelectedTabId end + + -- Forward moving request to selected window local tab = ImGui.TabBarFindTabByID(tab_bar, tab_bar.SelectedTabId) if tab then - ImGui.StartMouseMovingWindowOrNode(tab.Window or node.HostWindow, node, false) + ImGui.StartMouseMovingWindowOrNode(tab.Window or node.HostWindow, node, false) -- Undock from tab bar empty space end end end + -- Forward focus from host node to selected window + -- if is_focused and g.NavWindow == host_window and not g.NavWindowingTarget then + -- focus_tab_id = tab_bar.SelectedTabId + + -- When clicked on a tab we requested focus to the docked child + -- This overrides the value set by "forward focus from host node to selected window". if tab_bar.NextSelectedTabId ~= 0 then focus_tab_id = tab_bar.NextSelectedTabId end + -- Apply navigation focus if focus_tab_id ~= 0 then local tab = ImGui.TabBarFindTabByID(tab_bar, focus_tab_id) if tab and tab.Window then ImGui.FocusWindow(tab.Window) - if g.NavId == 0 then ImGui.NavInitWindow(tab.Window, false) end + if g.NavId == 0 then ImGui.NavInitWindow(tab.Window, false) end -- only init if FocusWindow() didn't restore anything. end end ImGui.EndTabBar() ImGui.PopID() + -- Restore SkipItems flag if not node:IsDockSpace() then host_window.DC.NavLayerCurrent = ImGuiNavLayer.Main host_window.SkipItems = backup_skip_item @@ -1906,6 +2782,7 @@ function ImGui.DockNodeRemoveTabBar(node) if node.TabBar == nil then return end node.TabBar = nil end + local function DockNodeIsDropAllowedOne(payload, host_window) if host_window.DockNodeAsHost and host_window.DockNodeAsHost:IsDockSpace() and payload.BeginOrderWithinContext < host_window.BeginOrderWithinContext then return false @@ -1920,10 +2797,15 @@ local function DockNodeIsDropAllowedOne(payload, host_window) if not pass then return false end end + -- Prevent docking any window created above a popup + -- Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features), + -- by e.g. adding a 'if not ImGui.IsWindowWithinBeginStackOf(host_window, popup_window)' test. + -- But it would requires more work on our end because the dock host windows is technically created in NewFrame() + -- and our .ParentXXX and .RootXXX pointers inside windows are currently mislading or lacking. local g = ImGui.GetCurrentContext() for i = g.OpenPopupStack.Size, 1, -1 do local popup_window = g.OpenPopupStack.Data[i].Window - if popup_window and ImGui.IsWindowWithinBeginStackOf(payload, popup_window) then + if popup_window and ImGui.IsWindowWithinBeginStackOf(payload, popup_window) then -- Payload is created from within a popup begin stack. return false end end @@ -1931,7 +2813,7 @@ local function DockNodeIsDropAllowedOne(payload, host_window) end function ImGui.DockNodeIsDropAllowed(host_window, root_payload) - if root_payload.DockNodeAsHost and root_payload.DockNodeAsHost:IsSplitNode() then return true end + if root_payload.DockNodeAsHost and root_payload.DockNodeAsHost:IsSplitNode() then return true end -- FIXME-DOCK: Missing filtering local payload_count = root_payload.DockNodeAsHost and root_payload.DockNodeAsHost.Windows.Size or 1 for payload_n = 1, payload_count do local payload = root_payload.DockNodeAsHost and root_payload.DockNodeAsHost.Windows.Data[payload_n] or root_payload @@ -1940,6 +2822,8 @@ function ImGui.DockNodeIsDropAllowed(host_window, root_payload) return false end +-- window menu button == collapse button when not in a dock node. +-- FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code. --- @return ImRect title_rect, ImRect tab_bar_rect, ImVec2 window_menu_button_pos, ImVec2? close_button_pos function ImGui.DockNodeCalcTabBarLayout(node) local g = ImGui.GetCurrentContext() @@ -1978,6 +2862,7 @@ function ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir, pos_new[o] = pos_old[o] size_new[o] = size_old[o] + -- Distribute size on given axis (with a desired size or equally) local w_avail = size_old[a] - dock_spacing if size_new_desired[a] > 0.0 and size_new_desired[a] <= w_avail * 0.5 then size_new[a] = size_new_desired[a] @@ -1987,6 +2872,7 @@ function ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir, size_old[a] = IM_TRUNC(w_avail - size_new[a]) end + -- Position each node if dir == ImGuiDir.Right or dir == ImGuiDir.Down then pos_new[a] = pos_old[a] + size_old[a] + dock_spacing elseif dir == ImGuiDir.Left or dir == ImGuiDir.Up then @@ -2002,14 +2888,18 @@ local function ImGetDirQuadrantFromDeltaLocal(dx, dy) return (dy > 0.0) and ImGuiDir.Down or ImGuiDir.Up end +-- Retrieve the drop rectangles for a given direction or for the center + perform hit testing. --- @return bool hit, ImRect out_r function ImGui.DockNodeCalcDropRectsAndTestMousePos(parent, dir, outer_docking, test_mouse_pos) local g = ImGui.GetCurrentContext() local parent_smaller_axis = ImMin(parent:GetWidth(), parent:GetHeight()) local hs_for_central_nodes = ImMin(g.FontSize * 1.5, ImMax(g.FontSize * 0.5, parent_smaller_axis / 8.0)) - local hs_w, hs_h, off + local hs_w, hs_h, off -- Half-size, longer axis / Half-size, smaller axis / Distance from edge or center if outer_docking then + -- hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0, g.FontSize * 0.5, g.FontSize * 8.0)) + -- hs_h = ImTrunc(hs_w * 0.15) + -- off = ImVec2(ImTrunc(parent:GetWidth() * 0.5 - GetFrameHeightWithSpacing() * 1.4 - hs_h), ImTrunc(parent:GetHeight() * 0.5 - GetFrameHeightWithSpacing() * 1.4 - hs_h)) hs_w = ImTrunc(hs_for_central_nodes * 1.50) hs_h = ImTrunc(hs_for_central_nodes * 0.80) off = ImVec2(ImTrunc(parent:GetWidth() * 0.5 - hs_h), ImTrunc(parent:GetHeight() * 0.5 - hs_h)) @@ -2032,6 +2922,7 @@ function ImGui.DockNodeCalcDropRectsAndTestMousePos(parent, dir, outer_docking, local hit_r = ImRect(out_r.Min, out_r.Max) if not outer_docking then + -- Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides hit_r:Expand(ImTrunc(hs_w * 0.30)) local mdx, mdy = test_mouse_pos.x - c.x, test_mouse_pos.y - c.y local mouse_delta_len2 = mdx * mdx + mdy * mdy @@ -2047,13 +2938,19 @@ function ImGui.DockNodeCalcDropRectsAndTestMousePos(parent, dir, outer_docking, return hit_r:Contains(test_mouse_pos), out_r end +-- host_node may be nil if the window doesn't have a DockNode already. +-- FIXME-DOCK: This is misnamed since it's also doing the filtering. function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, payload_node, data, is_explicit_target, is_outer_docking) local g = ImGui.GetCurrentContext() + -- There is an edge case when docking into a dockspace which only has inactive nodes. + -- In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive. + -- Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference. if payload_node == nil then payload_node = payload_window.DockNodeAsHost end local ref_node_for_rect = (host_node and not host_node.IsVisible) and ImGui.DockNodeGetRootNode(host_node) or host_node if ref_node_for_rect then IM_ASSERT(ref_node_for_rect.IsVisible == true) end + -- Filter, figure out where we are allowed to dock local src_node_flags = payload_node and payload_node.MergedFlags or payload_window.WindowClass.DockNodeFlagsOverrideSet local dst_node_flags = host_node and host_node.MergedFlags or host_window.WindowClass.DockNodeFlagsOverrideSet data.IsCenterAvailable = true @@ -2065,7 +2962,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, data.IsCenterAvailable = false elseif host_node and bit32.band(dst_node_flags, ImGuiDockNodeFlags.NoDockingOverCentralNode) ~= 0 and host_node:IsCentralNode() then data.IsCenterAvailable = false - elseif (not host_node or not host_node:IsEmpty()) and payload_node and payload_node:IsSplitNode() and (payload_node.OnlyNodeWithWindows == nil) then + elseif (not host_node or not host_node:IsEmpty()) and payload_node and payload_node:IsSplitNode() and (payload_node.OnlyNodeWithWindows == nil) then -- Is _visibly_ split? data.IsCenterAvailable = false elseif bit32.band(src_node_flags, ImGuiDockNodeFlags.NoDockingOverOther) ~= 0 and (not host_node or not host_node:IsEmpty()) then data.IsCenterAvailable = false @@ -2082,6 +2979,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, data.IsSidesAvailable = false end + -- Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split) data.FutureNode.HasCloseButton = (host_node and host_node.HasCloseButton or (not host_node and host_window.HasCloseButton)) or payload_window.HasCloseButton data.FutureNode.HasWindowMenuButton = host_node and true or (bit32.band(host_window.Flags, ImGuiWindowFlags.NoCollapse) == 0) local rp = ref_node_for_rect and ref_node_for_rect.Pos or host_window.Pos @@ -2089,6 +2987,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, data.FutureNode.Pos = ImVec2(rp.x, rp.y) data.FutureNode.Size = ImVec2(rs.x, rs.y) + -- Calculate drop shapes geometry for allowed splitting directions data.SplitNode = host_node data.SplitDir = ImGuiDir.None data.IsSplitDirExplicit = false @@ -2105,11 +3004,13 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, end end + -- When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar data.IsDropAllowed = (data.SplitDir ~= ImGuiDir.None) or data.IsCenterAvailable if not is_explicit_target and not data.IsSplitDirExplicit and not g.IO.ConfigDockingWithShift then data.IsDropAllowed = false end + -- Calculate split area data.SplitRatio = 0.0 if data.SplitDir ~= ImGuiDir.None then local split_dir = data.SplitDir @@ -2118,6 +3019,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, local size_new, size_old = ImVec2(0, 0), ImVec2(data.FutureNode.Size.x, data.FutureNode.Size.y) ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window.Size) + -- Calculate split ratio so we can pass it down the docking request local split_ratio = ImSaturate(size_new[split_axis] / data.FutureNode.Size[split_axis]) data.FutureNode.Pos = pos_new data.FutureNode.Size = size_new @@ -2127,17 +3029,21 @@ end function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, data) local g = ImGui.GetCurrentContext() - IM_ASSERT(g.CurrentWindow == host_window) + IM_ASSERT(g.CurrentWindow == host_window) -- Because we rely on font size to calculate tab sizes + -- With this option, we only display the preview on the target viewport, and the payload viewport is made transparent. + -- To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes. local is_transparent_payload = g.IO.ConfigDockingTransparentPayload local overlay_draw_lists = { ImGui.GetForegroundDrawList(host_window.Viewport) } + -- Draw main preview rectangle local overlay_col_main = ImGui.GetColorU32(ImGuiCol.DockingPreview, is_transparent_payload and 0.60 or 0.40) local overlay_col_drop = ImGui.GetColorU32(ImGuiCol.DockingPreview, is_transparent_payload and 0.90 or 0.70) local overlay_col_drop_hovered = ImGui.GetColorU32(ImGuiCol.DockingPreview, is_transparent_payload and 1.20 or 1.00) local overlay_col_lines = ImGui.GetColorU32(ImGuiCol.NavWindowingHighlight, is_transparent_payload and 0.80 or 0.60) + -- Display area preview local can_preview_tabs = (root_payload.DockNodeAsHost == nil or root_payload.DockNodeAsHost.Windows.Size > 0) if data.IsDropAllowed then local overlay_rect = data.FutureNode:Rect() @@ -2151,27 +3057,32 @@ function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, d end end + -- Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read) if data.IsDropAllowed and can_preview_tabs and data.SplitDir == ImGuiDir.None and data.IsCenterAvailable then + -- Compute target tab bar geometry so we can locate our preview tabs local _, tab_bar_rect = ImGui.DockNodeCalcTabBarLayout(data.FutureNode) local tab_pos = ImVec2(tab_bar_rect.Min.x, tab_bar_rect.Min.y) if host_node and host_node.TabBar then if not host_node:IsHiddenTabBar() and not host_node:IsNoTabBar() then - tab_pos.x = tab_pos.x + host_node.TabBar.WidthAllTabs + g.Style.ItemInnerSpacing.x + tab_pos.x = tab_pos.x + host_node.TabBar.WidthAllTabs + g.Style.ItemInnerSpacing.x -- We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission. else tab_pos.x = tab_pos.x + g.Style.ItemInnerSpacing.x + ImGui.TabItemCalcSize(host_node.Windows.Data[1]).x end elseif bit32.band(host_window.Flags, ImGuiWindowFlags.DockNodeHost) == 0 then - tab_pos.x = tab_pos.x + g.Style.ItemInnerSpacing.x + ImGui.TabItemCalcSize(host_window).x + tab_pos.x = tab_pos.x + g.Style.ItemInnerSpacing.x + ImGui.TabItemCalcSize(host_window).x -- Account for slight offset which will be added when changing from title bar to tab bar end + -- Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows) if root_payload.DockNodeAsHost then IM_ASSERT(root_payload.DockNodeAsHost.Windows.Size <= root_payload.DockNodeAsHost.TabBar.Tabs.Size) end local tab_bar_with_payload = root_payload.DockNodeAsHost and root_payload.DockNodeAsHost.TabBar or nil local payload_count = tab_bar_with_payload and tab_bar_with_payload.Tabs.Size or 1 for payload_n = 1, payload_count do + -- DockNode's TabBar may have non-window Tabs manually appended by user local payload_window = tab_bar_with_payload and tab_bar_with_payload.Tabs.Data[payload_n].Window or root_payload if not (tab_bar_with_payload and payload_window == nil) and DockNodeIsDropAllowedOne(payload_window, host_window) then + -- Calculate the tab bounding box for each payload window local tab_size = ImGui.TabItemCalcSize(payload_window) local tab_bb = ImRect(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y) tab_pos.x = tab_pos.x + tab_size.x + g.Style.ItemInnerSpacing.x @@ -2193,7 +3104,8 @@ function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, d end end - local scale = g.Style._MainScale or 1.0 + -- Display drop boxes + local scale = g.Style._MainScale or 1.0 -- FIXME-DPI local overlay_rounding = ImMax(math.floor(3.0 * scale), g.Style.FrameRounding) for dir = ImGuiDir.None, ImGuiDir.COUNT - 1 do local draw_r = data.DropRectsDraw[dir + 1] @@ -2215,15 +3127,25 @@ function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, d end end end + + -- Stop after ImGuiDir.None if (host_node and bit32.band(host_node.MergedFlags, ImGuiDockNodeFlags.NoDockingSplit) ~= 0) or g.IO.ConfigDockingNoSplit then return end end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: ImGuiDockNode Tree manipulation functions ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockNodeTreeSplit() +-- - DockNodeTreeMerge() +-- - DockNodeTreeUpdatePosSize() +-- - DockNodeTreeUpdateSplitterFindTouchingNode() +-- - DockNodeTreeUpdateSplitter() +-- - DockNodeTreeFindFallbackLeafNode() +-- - DockNodeTreeFindNodeByPos() +------------------------------------------------------------------------------- function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_child_idx, split_ratio, new_node) local g = ImGui.GetCurrentContext() @@ -2248,7 +3170,7 @@ function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_c local a = split_axis local size_avail = parent_node.Size[a] - g.Style.DockingSeparatorSize size_avail = ImMax(size_avail, g.Style.WindowMinSize[a] * 2.0) - IM_ASSERT(size_avail > 0.0) + IM_ASSERT(size_avail > 0.0) -- If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting. child_0.SizeRef = ImVec2(parent_node.Size.x, parent_node.Size.y) child_1.SizeRef = ImVec2(parent_node.Size.x, parent_node.Size.y) child_0.SizeRef[a] = ImTrunc(size_avail * split_ratio) @@ -2259,6 +3181,7 @@ function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_c ImGui.DockNodeUpdateHasCentralNodeChild(ImGui.DockNodeGetRootNode(parent_node)) ImGui.DockNodeTreeUpdatePosSize(parent_node, parent_node.Pos, parent_node.Size) + -- Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags.CentralNode property) child_0.SharedFlags = bit32.band(parent_node.SharedFlags, ImGuiDockNodeFlags.SharedFlagsInheritMask_) child_1.SharedFlags = bit32.band(parent_node.SharedFlags, ImGuiDockNodeFlags.SharedFlagsInheritMask_) child_inheritor.LocalFlags = bit32.band(parent_node.LocalFlags, ImGuiDockNodeFlags.LocalFlagsTransferMask_) @@ -2272,6 +3195,7 @@ function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_c end function ImGui.DockNodeTreeMerge(ctx, parent_node, merge_lead_child) + -- When called from DockContextProcessUndockNode() it is possible that one of the child is nil. local child_0 = parent_node.ChildNodes[0] local child_1 = parent_node.ChildNodes[1] IM_ASSERT(child_0 or child_1) @@ -2284,7 +3208,7 @@ function ImGui.DockNodeTreeMerge(ctx, parent_node, merge_lead_child) local backup_last_explicit_size = ImVec2(parent_node.SizeRef.x, parent_node.SizeRef.y) ImGui.DockNodeMoveChildNodes(parent_node, merge_lead_child) if child_0 then - ImGui.DockNodeMoveWindows(parent_node, child_0) + ImGui.DockNodeMoveWindows(parent_node, child_0) -- Generally only 1 of the 2 child node will have windows DockSettingsRenameNodeReferences(child_0.ID, parent_node.ID) end if child_1 then @@ -2298,18 +3222,23 @@ function ImGui.DockNodeTreeMerge(ctx, parent_node, merge_lead_child) parent_node.VisibleWindow = merge_lead_child.VisibleWindow parent_node.SizeRef = backup_last_explicit_size + -- Flags transfer local M = ImGuiDockNodeFlags.LocalFlagsTransferMask_ - parent_node.LocalFlags = bit32.band(parent_node.LocalFlags, bit32.bnot(M)) + parent_node.LocalFlags = bit32.band(parent_node.LocalFlags, bit32.bnot(M)) -- Preserve Dockspace flag parent_node.LocalFlags = bit32.bor(parent_node.LocalFlags, bit32.band(child_0 and child_0.LocalFlags or 0, M)) parent_node.LocalFlags = bit32.bor(parent_node.LocalFlags, bit32.band(child_1 and child_1.LocalFlags or 0, M)) - parent_node.LocalFlagsInWindows = bit32.bor(child_0 and child_0.LocalFlagsInWindows or 0, child_1 and child_1.LocalFlagsInWindows or 0) + parent_node.LocalFlagsInWindows = bit32.bor(child_0 and child_0.LocalFlagsInWindows or 0, child_1 and child_1.LocalFlagsInWindows or 0) -- FIXME: Would be more consistent to update from actual windows parent_node:UpdateMergedFlags() if child_0 then ImGui.DockContextDeleteNode(ctx, child_0) end if child_1 then ImGui.DockContextDeleteNode(ctx, child_1) end end +-- Update Pos/Size for a node hierarchy (don't affect child Windows yet) +-- (Depth-first, Pre-Order) function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_node) + -- During the regular dock node update we write to all nodes. + -- 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away. local g = ImGui.GetCurrentContext() local write_to_node = only_write_to_single_node == nil or only_write_to_single_node == node if write_to_node then @@ -2334,8 +3263,15 @@ function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_n local a = node.SplitAxis local size_avail = ImMax(size[a] - spacing, 0.0) + -- Size allocation policy + -- 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows. local size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[a] * 2.0) * 0.5) + -- FIXME: Blocks 2) and 3) are essentially doing nearly the same thing. + -- Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc() + -- Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce + + -- 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge) if child_0.WantLockSizeOnce and not child_1.WantLockSizeOnce then child_0_size[a] = ImMin(size_avail - 1.0, child_0.Size[a]); child_0.SizeRef[a] = child_0_size[a] child_1_size[a] = size_avail - child_0_size[a]; child_1.SizeRef[a] = child_1_size[a] @@ -2343,9 +3279,13 @@ function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_n child_1_size[a] = ImMin(size_avail - 1.0, child_1.Size[a]); child_1.SizeRef[a] = child_1_size[a] child_0_size[a] = size_avail - child_1_size[a]; child_0.SizeRef[a] = child_0_size[a] elseif child_0.WantLockSizeOnce and child_1.WantLockSizeOnce then + -- FIXME-DOCK: We cannot honor the requested size, so apply ratio. + -- Currently this path will only be taken if code programmatically sets WantLockSizeOnce local split_ratio = child_0_size[a] / (child_0_size[a] + child_1_size[a]) child_0_size[a] = ImTrunc(size_avail * split_ratio); child_0.SizeRef[a] = child_0_size[a] child_1_size[a] = size_avail - child_0_size[a]; child_1.SizeRef[a] = child_1_size[a] + + -- 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node elseif child_0.SizeRef[a] ~= 0.0 and child_1.HasCentralNodeChild then child_0_size[a] = ImMin(size_avail - size_min_each, child_0.SizeRef[a]) child_1_size[a] = size_avail - child_0_size[a] @@ -2353,6 +3293,7 @@ function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_n child_1_size[a] = ImMin(size_avail - size_min_each, child_1.SizeRef[a]) child_0_size[a] = size_avail - child_1_size[a] else + -- 4) Otherwise distribute according to the relative ratio of each SizeRef value local split_ratio = child_0.SizeRef[a] / (child_0.SizeRef[a] + child_1.SizeRef[a]) child_0_size[a] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5)) child_1_size[a] = size_avail - child_0_size[a] @@ -2388,8 +3329,9 @@ local function DockNodeTreeUpdateSplitterFindTouchingNode(node, axis, side, touc end end -local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 +local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 -- Reduce visual noise by only highlighting the border after a certain time. +-- (Depth-First, Pre-Order) function ImGui.DockNodeTreeUpdateSplitter(node) if node:IsLeafNode() then return end @@ -2398,27 +3340,32 @@ function ImGui.DockNodeTreeUpdateSplitter(node) local child_0 = node.ChildNodes[0] local child_1 = node.ChildNodes[1] if child_0.IsVisible and child_1.IsVisible then + -- Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally) local axis = node.SplitAxis IM_ASSERT(axis ~= ImGuiAxis.None) local a, o = axis, 3 - axis -- the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index local bb = ImRect(ImVec2(child_0.Pos.x, child_0.Pos.y), ImVec2(child_1.Pos.x, child_1.Pos.y)) bb.Min[a] = bb.Min[a] + child_0.Size[a] bb.Max[o] = bb.Max[o] + child_1.Size[o] + -- if g.IO.KeyCtrl then GetForegroundDrawList(g.CurrentWindow.Viewport):AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255)) end - local merged_flags = bit32.bor(child_0.MergedFlags, child_1.MergedFlags) + local merged_flags = bit32.bor(child_0.MergedFlags, child_1.MergedFlags) -- Merged flags for BOTH childs local no_resize_axis_flag = (axis == ImGuiAxis.X) and ImGuiDockNodeFlags.NoResizeX or ImGuiDockNodeFlags.NoResizeY if bit32.band(merged_flags, ImGuiDockNodeFlags.NoResize) ~= 0 or bit32.band(merged_flags, no_resize_axis_flag) ~= 0 then local window = g.CurrentWindow window.DrawList:AddRectFilled(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.Separator), g.Style.FrameRounding) else + -- bb.Min[axis] = bb.Min[axis] + 1 -- Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node. + -- bb.Max[axis] = bb.Max[axis] - 1 ImGui.PushID(node.ID) + -- Find resizing limits by gathering list of nodes that are touching the splitter line. local touching_nodes = { [0] = {}, [1] = {} } local min_size = g.Style.WindowMinSize[a] local resize_limits = { [0] = node.ChildNodes[0].Pos[a] + min_size, [1] = node.ChildNodes[1].Pos[a] + node.ChildNodes[1].Size[a] - min_size } local splitter_id = ImGui.GetID("##Splitter") - if g.ActiveId == splitter_id then + if g.ActiveId == splitter_id then -- Only process when splitter is active DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, touching_nodes[0]) DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, touching_nodes[1]) for _, tn in ipairs(touching_nodes[0]) do @@ -2429,6 +3376,7 @@ function ImGui.DockNodeTreeUpdateSplitter(node) end end + -- Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters local cur_size_0 = child_0.Size[a] local cur_size_1 = child_1.Size[a] local min_size_0 = resize_limits[0] - child_0.Pos[a] @@ -2442,10 +3390,13 @@ function ImGui.DockNodeTreeUpdateSplitter(node) child_1.Pos[a] = child_1.Pos[a] - (cur_size_1 - child_1.Size[a]) child_1.Size[a] = cur_size_1; child_1.SizeRef[a] = cur_size_1 + -- Lock the size of every node that is a sibling of the node we are touching + -- This might be less desirable if we can merge sibling of a same axis into the same parental level. for side_n = 0, 1 do for _, touching_node in ipairs(touching_nodes[side_n]) do while touching_node.ParentNode ~= node do if touching_node.ParentNode.SplitAxis == axis then + -- Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize(). local node_to_preserve = touching_node.ParentNode.ChildNodes[side_n] node_to_preserve.WantLockSizeOnce = true end @@ -2478,6 +3429,7 @@ end function ImGui.DockNodeTreeFindVisibleNodeByPos(node, pos) if not node.IsVisible then return nil end + local r = ImRect(node.Pos, node.Pos + node.Size) if not r:Contains(pos) then return nil end if node:IsLeafNode() then return node end @@ -2485,22 +3437,32 @@ function ImGui.DockNodeTreeFindVisibleNodeByPos(node, pos) if hovered_node then return hovered_node end hovered_node = ImGui.DockNodeTreeFindVisibleNodeByPos(node.ChildNodes[1], pos) if hovered_node then return hovered_node end + + -- This means we are hovering over the splitter/spacing of a parent node return node end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - SetWindowDock() [Internal] +-- - DockSpace() +-- - DockSpaceOverViewport() +------------------------------------------------------------------------------- +-- [Internal] Called via SetNextWindowDockID() function ImGui.SetWindowDock(window, dock_id, cond) + -- Test condition (NB: bit 0 is always true) and clear flags for next time if cond and cond ~= 0 and bit32.band(window.SetWindowDockAllowFlags, cond) == 0 then return end window.SetWindowDockAllowFlags = bit32.band(window.SetWindowDockAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing))) if window.DockId == dock_id then return end + -- If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot local g = ImGui.GetCurrentContext() local new_node = ImGui.DockContextFindNodeByID(g, dock_id) if new_node and new_node:IsSplitNode() then + -- Policy: Find central node or latest focused node. We first move back to our root node. new_node = ImGui.DockNodeGetRootNode(new_node) if new_node.CentralNode then IM_ASSERT(new_node.CentralNode:IsCentralNode()) @@ -2516,6 +3478,10 @@ function ImGui.SetWindowDock(window, dock_id, cond) window.DockId = dock_id end +-- Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default. +-- The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors. +-- DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app. +-- When ImGuiDockNodeFlags.KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location). function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) if size_arg == nil then size_arg = ImVec2(0, 0) end if flags == nil then flags = 0 end @@ -2523,11 +3489,14 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) local window = ImGui.GetCurrentWindowRead() if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then return 0 end + -- Early out if parent window is hidden/collapsed + -- This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960. + -- If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true. if window.SkipItems then flags = bit32.bor(flags, ImGuiDockNodeFlags.KeepAliveOnly) end - if bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 then window = ImGui.GetCurrentWindow() end + if bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 then window = ImGui.GetCurrentWindow() end -- call to set window.WriteAccessed = true; - IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.DockSpace) == 0) - IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.CentralNode) == 0) + IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.DockSpace) == 0) -- Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! + IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.CentralNode) == 0) -- Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! (#8145) IM_ASSERT(dockspace_id ~= 0) local node = ImGui.DockContextFindNodeByID(g, dockspace_id) @@ -2538,6 +3507,8 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) node.SharedFlags = flags node.WindowClass = window_class or ImGuiWindowClass() + -- When a DockSpace transitioned form implicit to explicit this may be called a second time + -- It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again. if node.LastFrameActive == g.FrameCount and bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 then IM_ASSERT(node:IsDockSpace() == false, "Cannot call DockSpace() twice a frame with the same ID") node:SetLocalFlags(bit32.bor(node.LocalFlags, ImGuiDockNodeFlags.DockSpace)) @@ -2545,6 +3516,7 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) end node:SetLocalFlags(bit32.bor(node.LocalFlags, ImGuiDockNodeFlags.DockSpace)) + -- Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible if bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then node.LastFrameAlive = g.FrameCount return dockspace_id @@ -2552,7 +3524,7 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) local content_avail = ImGui.GetContentRegionAvail() local size = ImVec2(ImTrunc(size_arg.x), ImTrunc(size_arg.y)) - if size.x <= 0.0 then size.x = ImMax(content_avail.x + size.x, 4.0) end + if size.x <= 0.0 then size.x = ImMax(content_avail.x + size.x, 4.0) end -- Arbitrary minimum child size (0.0f causing too much issues) if size.y <= 0.0 then size.y = ImMax(content_avail.y + size.y, 4.0) end IM_ASSERT(size.x > 0.0 and size.y > 0.0) @@ -2563,6 +3535,8 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) ImGui.SetNextWindowSize(node.Size) g.NextWindowData.PosUndock = false + -- FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window? + -- FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented) local window_flags = bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.DockNodeHost) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoCollapse, ImGuiWindowFlags.NoTitleBar) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoScrollWithMouse) @@ -2581,29 +3555,41 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) IM_ASSERT(node:IsRootNode()) + -- We need to handle the rare case were a central node is missing. + -- This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags.Dockspace. + -- Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split. + -- It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining. + -- The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property, + -- as it doesn't make sense for an empty dockspace to not have this property. if node:IsLeafNode() and not node:IsCentralNode() then node:SetLocalFlags(bit32.bor(node.LocalFlags, ImGuiDockNodeFlags.CentralNode)) end + -- Update the node ImGui.DockNodeUpdate(node) ImGui.End() local bb = ImRect(node.Pos, node.Pos + size) ImGui.ItemSize(size) - ImGui.ItemAdd(bb, dockspace_id, nil, ImGuiItemFlags.NoNav) - if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) ~= 0 and ImGui.IsWindowChildOf(g.HoveredWindow, host_window, false, true) then + ImGui.ItemAdd(bb, dockspace_id, nil, ImGuiItemFlags.NoNav) -- Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?) + if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) ~= 0 and ImGui.IsWindowChildOf(g.HoveredWindow, host_window, false, true) then -- To fullfill IsItemHovered(), similar to EndChild() g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end return dockspace_id end +-- Tips: Use with ImGuiDockNodeFlags.PassthruCentralNode! +-- The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar(). +-- Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function. +-- If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it. function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, window_class) if dockspace_id == nil then dockspace_id = 0 end if dockspace_flags == nil then dockspace_flags = 0 end if viewport == nil then viewport = ImGui.GetMainViewport() end + -- Submit a window filling the entire viewport ImGui.SetNextWindowPos(viewport.WorkPos) ImGui.SetNextWindowSize(viewport.WorkSize) ImGui.SetNextWindowViewport(viewport.ID) @@ -2614,6 +3600,9 @@ function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, wi if bit32.band(dockspace_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0 then host_window_flags = bit32.bor(host_window_flags, ImGuiWindowFlags.NoBackground) end + + -- 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 bit32.band(dockspace_flags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then host_window_flags = bit32.bor(host_window_flags, ImGuiWindowFlags.NoMouseInputs) end @@ -2626,6 +3615,7 @@ function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, wi ImGui.Begin(label, nil, host_window_flags) ImGui.PopStyleVar(3) + -- Submit the dockspace if dockspace_id == 0 then dockspace_id = ImGui.GetID("DockSpace") end ImGui.DockSpace(dockspace_id, ImVec2(0.0, 0.0), dockspace_flags, window_class) @@ -2634,18 +3624,40 @@ function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, wi return dockspace_id end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Builder Functions ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Very early end-user API to manipulate dock nodes. +-- Only available in imgui_internal.h. Expect this API to change/break! +-- It is expected that those functions are all called _before_ the dockspace node submission. +------------------------------------------------------------------------------- +-- - DockBuilderDockWindow() +-- - DockBuilderGetNode() +-- - DockBuilderSetNodePos() +-- - DockBuilderSetNodeSize() +-- - DockBuilderAddNode() +-- - DockBuilderRemoveNode() +-- - DockBuilderRemoveNodeChildNodes() +-- - DockBuilderRemoveNodeDockedWindows() +-- - DockBuilderSplitNode() +-- - DockBuilderCopyNodeRec() +-- - DockBuilderCopyNode() +-- - DockBuilderCopyWindowSettings() +-- - DockBuilderCopyDockSpace() +-- - DockBuilderFinish() +------------------------------------------------------------------------------- function ImGui.DockBuilderDockWindow(window_name, node_id) + -- We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1) local window_id = ImHashStr(window_name) local window = ImGui.FindWindowByID(window_id) if window then + -- Apply to created window local prev_node_id = window.DockId ImGui.SetWindowDock(window, node_id, ImGuiCond.Always) if window.DockId ~= prev_node_id then window.DockOrder = -1 end else + -- Apply to settings local settings = ImGui.FindWindowSettingsByID(window_id) if settings == nil then settings = ImGui.CreateNewWindowSettings(window_name) end if settings.DockId ~= node_id then settings.DockOrder = -1 end @@ -2679,6 +3691,13 @@ function ImGui.DockBuilderSetNodeSize(node_id, size) node.AuthorityForSize = ImGuiDataAuthority.DockNode end +-- Make sure to use the ImGuiDockNodeFlags.DockSpace flag to create a dockspace node! Otherwise this will create a floating node! +-- - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node. +-- - Dockspace node: calling DockBuilderSetNodePos() is unnecessary. +-- - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand! +-- For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect. +-- - Use (id == 0) to let the system allocate a node identifier. +-- - Existing node with a same id will be removed. function ImGui.DockBuilderAddNode(node_id, flags) if node_id == nil then node_id = 0 end if flags == nil then flags = 0 end @@ -2693,7 +3712,7 @@ function ImGui.DockBuilderAddNode(node_id, flags) node = ImGui.DockContextAddNode(g, node_id) node:SetLocalFlags(flags) end - node.LastFrameAlive = g.FrameCount + node.LastFrameAlive = g.FrameCount -- Set this otherwise BeginDocked will undock during the same frame. return node.ID end @@ -2703,6 +3722,7 @@ function ImGui.DockBuilderRemoveNode(node_id) if node == nil then return end ImGui.DockBuilderRemoveNodeDockedWindows(node_id, true) ImGui.DockBuilderRemoveNodeChildNodes(node_id) + -- Node may have moved or deleted if e.g. any merge happened node = ImGui.DockContextFindNodeByID(g, node_id) if node == nil then return end if node:IsCentralNode() and node.ParentNode then @@ -2711,6 +3731,7 @@ function ImGui.DockBuilderRemoveNode(node_id) ImGui.DockContextRemoveNode(g, node, true) end +-- root_id = 0 to remove all, root_id != 0 to remove child of given node. function ImGui.DockBuilderRemoveNodeChildNodes(root_id) local g = ImGui.GetCurrentContext() local dc = g.DockContext @@ -2722,6 +3743,7 @@ function ImGui.DockBuilderRemoveNodeChildNodes(root_id) local backup_root_node_authority_for_pos = root_node and root_node.AuthorityForPos or ImGuiDataAuthority.Auto local backup_root_node_authority_for_size = root_node and root_node.AuthorityForSize or ImGuiDataAuthority.Auto + -- Process active windows local nodes_to_remove = {} for _, id in ipairs(DockContextNodesSorted(g)) do local node = dc.Nodes[id] @@ -2739,11 +3761,14 @@ function ImGui.DockBuilderRemoveNodeChildNodes(root_id) end end + -- DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge) + -- Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead) if root_node then root_node.AuthorityForPos = backup_root_node_authority_for_pos root_node.AuthorityForSize = backup_root_node_authority_for_size end + -- Apply to settings for _, settings in g.SettingsWindows:iter() do local window_settings_dock_id = settings.DockId if window_settings_dock_id and window_settings_dock_id ~= 0 then @@ -2756,6 +3781,7 @@ function ImGui.DockBuilderRemoveNodeChildNodes(root_id) end end + -- Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes if #nodes_to_remove > 1 then local depth = {} for _, n in ipairs(nodes_to_remove) do depth[n] = ImGui.DockNodeGetDepth(n) end @@ -2776,6 +3802,7 @@ end function ImGui.DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs) if clear_settings_refs == nil then clear_settings_refs = true end + -- Clear references in settings local g = ImGui.GetCurrentContext() if clear_settings_refs then for _, settings in g.SettingsWindows:iter() do @@ -2788,6 +3815,7 @@ function ImGui.DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs) end end + -- Clear references in windows for n = 1, g.Windows.Size do local window = g.Windows.Data[n] local want_removal = (root_id == 0) or (window.DockNode and ImGui.DockNodeGetRootNode(window.DockNode).ID == root_id) or (window.DockNodeAsHost and window.DockNodeAsHost.ID == root_id) @@ -2799,6 +3827,9 @@ function ImGui.DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs) end end +-- Returns (id_at_dir, id_at_opposite_dir): the IDs of the two new nodes created. +-- First return value is ID of the node at the specified direction. +-- FIXME-DOCK: We are not exposing nor using split_outer. --- @return ImGuiID id_at_dir, ImGuiID id_at_opposite_dir function ImGui.DockBuilderSplitNode(id, split_dir, size_ratio_for_node_at_dir) local g = ImGui.GetCurrentContext() @@ -2892,6 +3923,7 @@ function ImGui.DockBuilderCopyWindowSettings(src_name, dst_name) end end +-- FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed. --- @param in_window_remap_pairs table # 1-based array of window names: src0, dst0, src1, dst1, ... function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_window_remap_pairs) IM_ASSERT(src_dockspace_id ~= 0) @@ -2899,9 +3931,14 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w IM_ASSERT(in_window_remap_pairs ~= nil) IM_ASSERT((#in_window_remap_pairs % 2) == 0) + -- Duplicate entire dock + -- FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart, + -- whereas we could attempt to at least keep them together in a new, same floating node. local node_remap_pairs = {} ImGui.DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, node_remap_pairs) + -- Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes + -- (The windows associated to src_dockspace_id are staying in place) local src_windows = {} for remap_window_n = 1, #in_window_remap_pairs, 2 do local src_window_name = in_window_remap_pairs[remap_window_n] @@ -2909,6 +3946,7 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w local src_window_id = ImHashStr(src_window_name) src_windows[src_window_id] = true + -- Search in the remapping tables local src_dock_id = 0 local src_window = ImGui.FindWindowByID(src_window_id) if src_window then @@ -2921,17 +3959,24 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w for dock_remap_n = 1, #node_remap_pairs, 2 do if node_remap_pairs[dock_remap_n] == src_dock_id then dst_dock_id = node_remap_pairs[dock_remap_n + 1] + --node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0 -- Clear break end end if dst_dock_id ~= 0 then + -- Docked windows gets redocked into the new node hierarchy. ImGui.DockBuilderDockWindow(dst_window_name, dst_dock_id) else + -- Floating windows gets their settings transferred (regardless of whether the new window already exist or not) + -- When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together? ImGui.DockBuilderCopyWindowSettings(src_window_name, dst_window_name) end end + -- Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list. + -- Find those windows and move to them to the cloned dock node. This may be optional? + -- Dock those are a second step as undocking would invalidate source dock nodes. local dock_remaining_windows = {} for dock_remap_n = 1, #node_remap_pairs, 2 do local src_dock_id = node_remap_pairs[dock_remap_n] @@ -2940,6 +3985,7 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w local node = ImGui.DockBuilderGetNode(src_dock_id) for _, window in node.Windows:iter() do if not src_windows[window.ID] then + -- Docked windows gets redocked into the new node hierarchy. table.insert(dock_remaining_windows, { Window = window, DockId = dst_dock_id }) end end @@ -2950,19 +3996,27 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w end end +-- FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node. function ImGui.DockBuilderFinish(root_id) + --DockContextRebuild(g) ImGui.DockContextBuildAddWindowsToNodes(ImGui.GetCurrentContext(), root_id) end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Begin/End Support Functions (called from Begin/End) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - GetWindowAlwaysWantOwnTabBar() +-- - DockContextBindNodeToWindow() +-- - BeginDocked() +-- - BeginDockableDragDropSource() +-- - BeginDockableDragDropTarget() +------------------------------------------------------------------------------- function ImGui.GetWindowAlwaysWantOwnTabBar(window) local g = ImGui.GetCurrentContext() if g.IO.ConfigDockingAlwaysTabBar or window.WindowClass.DockingAlwaysTabBar then if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoDocking)) == 0 then - if not window.IsFallbackWindow then return true end + if not window.IsFallbackWindow then return true end -- We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise end end return false @@ -2973,11 +4027,13 @@ function ImGui.DockContextBindNodeToWindow(ctx, window) local node = ImGui.DockContextFindNodeByID(ctx, window.DockId) IM_ASSERT(window.DockNode == nil) + -- We should not be docking into a split node (SetWindowDock should avoid this) if node and node:IsSplitNode() then ImGui.DockContextProcessUndockWindow(ctx, window) return nil end + -- Create node if node == nil then node = ImGui.DockContextAddNode(ctx, window.DockId) node.AuthorityForPos = ImGuiDataAuthority.Window @@ -2986,6 +4042,10 @@ function ImGui.DockContextBindNodeToWindow(ctx, window) node.LastFrameAlive = g.FrameCount end + -- If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, + -- so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node). + -- If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout. + -- This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame. if not node.IsVisible then local ancestor_node = node while not ancestor_node.IsVisible and ancestor_node.ParentNode do @@ -2996,9 +4056,10 @@ function ImGui.DockContextBindNodeToWindow(ctx, window) ImGui.DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node.Pos, ancestor_node.Size, node) end + -- Add window to node local node_was_visible = node.IsVisible ImGui.DockNodeAddWindow(node, window, true) - node.IsVisible = node_was_visible + node.IsVisible = node_was_visible -- Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see) IM_ASSERT(node == window.DockNode) return node end @@ -3015,6 +4076,7 @@ ImGui.StoreDockStyleForWindow = StoreDockStyleForWindow function ImGui.BeginDocked(window, p_open) local g = ImGui.GetCurrentContext() + -- Specific extra processing for fallback window (#9151), could be in Begin() as well. if window.IsFallbackWindow and not window.WasActive then DockNodeHideWindowDuringHostWindowCreation(window) return p_open @@ -3027,6 +4089,7 @@ function ImGui.BeginDocked(window, p_open) window.DockId = ImGui.DockContextGenNodeID(g) end else + -- Calling SetNextWindowPos() undock windows by default (by setting PosUndock) local want_undock = false want_undock = want_undock or bit32.band(window.Flags, ImGuiWindowFlags.NoDocking) ~= 0 want_undock = want_undock or (bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) ~= 0 and bit32.band(window.SetWindowPosAllowFlags, g.NextWindowData.PosCond) ~= 0 and g.NextWindowData.PosUndock) @@ -3036,6 +4099,7 @@ function ImGui.BeginDocked(window, p_open) end end + -- Bind to our dock node local node = window.DockNode if node ~= nil then IM_ASSERT(window.DockId == node.ID) end if window.DockId ~= 0 and node == nil then @@ -3043,7 +4107,10 @@ function ImGui.BeginDocked(window, p_open) if node == nil then return p_open end end + -- Undock if our dockspace node disappeared + -- Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags.KeepAliveOnly. if node.LastFrameAlive < g.FrameCount then + -- If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking() local root_node = ImGui.DockNodeGetRootNode(node) if root_node.LastFrameAlive < g.FrameCount then ImGui.DockContextProcessUndockWindow(g, window) @@ -3053,47 +4120,58 @@ function ImGui.BeginDocked(window, p_open) return p_open end + -- Store style overrides StoreDockStyleForWindow(window) + -- Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window, + -- and never create neither a host window neither a tab bar. + -- FIXME-DOCK: replace .HostWindow nil compare with something more explicit (~was initially intended as a first frame test) if node.HostWindow == nil then if node.State == ImGuiDockNodeState.HostWindowHiddenBecauseWindowsAreResizing then window.DockIsActive = true end - if node.Windows.Size > 1 and window.Appearing then + if node.Windows.Size > 1 and window.Appearing then -- Only hide appearing window DockNodeHideWindowDuringHostWindowCreation(window) end return p_open end + -- We can have zero-sized nodes (e.g. children of a small-size dockspace) IM_ASSERT(node.HostWindow) IM_ASSERT(node:IsLeafNode()) IM_ASSERT(node.Size.x >= 0.0 and node.Size.y >= 0.0) node.State = ImGuiDockNodeState.HostWindowVisible + -- Undock if we are submitted earlier than the host window if bit32.band(node.MergedFlags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 and window.BeginOrderWithinContext < node.HostWindow.BeginOrderWithinContext then ImGui.DockContextProcessUndockWindow(g, window) return p_open end + -- Position/Size window ImGui.SetNextWindowPos(node.Pos) ImGui.SetNextWindowSize(node.Size) - g.NextWindowData.PosUndock = false + g.NextWindowData.PosUndock = false -- Cancel implicit undocking of SetNextWindowPos() window.DockIsActive = true window.DockNodeIsVisible = true window.DockTabIsVisible = false if bit32.band(node.MergedFlags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then return p_open end + -- When the window is selected we mark it as visible. if node.VisibleWindow == window then window.DockTabIsVisible = true end + -- Update window flag IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0) window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.NoResize) window.ChildFlags = bit32.bor(window.ChildFlags, ImGuiChildFlags.AlwaysUseWindowPadding) if node:IsHiddenTabBar() or node:IsNoTabBar() then window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.NoTitleBar) else - window.Flags = bit32.band(window.Flags, bit32.bnot(ImGuiWindowFlags.NoTitleBar)) + window.Flags = bit32.band(window.Flags, bit32.bnot(ImGuiWindowFlags.NoTitleBar)) -- Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed! end + -- Save new dock order only if the window has been visible once already + -- This allows multiple windows to be created in the same frame and have their respective dock orders preserved. if node.TabBar and window.WasActive then window.DockOrder = ImGui.DockNodeGetTabOrder(window) end @@ -3102,6 +4180,7 @@ function ImGui.BeginDocked(window, p_open) p_open = false end + -- Update ChildId to allow returning from Child to Parent with Escape local parent_window = window.DockNode.HostWindow window.ChildId = parent_window:GetID(window.Name) return p_open @@ -3113,7 +4192,11 @@ function ImGui.BeginDockableDragDropSource(window) IM_ASSERT(g.MovingWindow == window) IM_ASSERT(g.CurrentWindow == window) + -- 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking. if g.IO.ConfigDockingWithShift ~= g.IO.KeyShift then + -- When ConfigDockingWithShift is set, display a tooltip to increase UI affordance. + -- We cannot set for HoveredWindowUnderMovingWindow ~= nil 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) if g.IO.ConfigDockingWithShift and g.MouseStationaryTimer >= 1.0 and g.ActiveId >= 1 then ImGui.SetTooltip("%s", ImGui.LocalizeGetMsg(ImGuiLocKey.DockingHoldShiftToDock)) end @@ -3123,21 +4206,26 @@ function ImGui.BeginDockableDragDropSource(window) g.LastItemData.ID = window.MoveId window = window.RootWindowDockTree IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.NoDocking) == 0) - local is_drag_docking = g.IO.ConfigDockingWithShift or ImRect(0, 0, window.SizeFull.x, ImGui.GetFrameHeight()):Contains(g.ActiveIdClickOffset) + local is_drag_docking = g.IO.ConfigDockingWithShift or ImRect(0, 0, window.SizeFull.x, ImGui.GetFrameHeight()):Contains(g.ActiveIdClickOffset) -- FIXME-DOCKING: Need to make this stateful and explicit local drag_drop_flags = bit32.bor(ImGuiDragDropFlags.SourceNoPreviewTooltip, ImGuiDragDropFlags.SourceNoHoldToOpenOthers, ImGuiDragDropFlags.PayloadAutoExpire, ImGuiDragDropFlags.PayloadNoCrossContext, ImGuiDragDropFlags.PayloadNoCrossProcess) if is_drag_docking and ImGui.BeginDragDropSource(drag_drop_flags) then ImGui.SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, window) ImGui.EndDragDropSource() - StoreDockStyleForWindow(window) + StoreDockStyleForWindow(window) -- Store style overrides while dragging (even when not docked) because docking preview may need it. end end function ImGui.BeginDockableDragDropTarget(window) local g = ImGui.GetCurrentContext() + + --IM_ASSERT(window.RootWindowDockTree == window) -- May also be a DockSpace IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.NoDocking) == 0) if not g.DragDropActive then return end + --GetForegroundDrawList(window):AddRect(window.Pos, window.Pos + window.Size, IM_COL32(255, 255, 0, 255)) if not ImGui.BeginDragDropTargetCustom(window:Rect(), window.ID) then return end + -- Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering + -- (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly) local payload = g.DragDropPayload if not ImGuiPayload_IsDataType(payload, IMGUI_PAYLOAD_TYPE_WINDOW) or not ImGui.DockNodeIsDropAllowed(window, payload.Data) then ImGui.EndDragDropTarget() @@ -3146,10 +4234,17 @@ function ImGui.BeginDockableDragDropTarget(window) local payload_window = payload.Data if ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, bit32.bor(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoDrawDefaultRect)) then + -- Select target node + -- (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation) local dock_into_floating_window = false local node = nil if window.DockNodeAsHost then + -- Cannot assume that node will ~= nil even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos(). node = ImGui.DockNodeTreeFindVisibleNodeByPos(window.DockNodeAsHost, g.IO.MousePos) + + -- There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active) + -- In this case we need to fallback into any leaf mode, possibly the central node. + -- FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. if node and node:IsDockSpace() and node:IsRootNode() then node = (node.CentralNode and node:IsLeafNode()) and node.CentralNode or ImGui.DockNodeTreeFindFallbackLeafNode(node) end @@ -3157,7 +4252,7 @@ function ImGui.BeginDockableDragDropTarget(window) if window.DockNode then node = window.DockNode else - dock_into_floating_window = true + dock_into_floating_window = true -- Dock into a regular window end end @@ -3169,8 +4264,11 @@ function ImGui.BeginDockableDragDropTarget(window) end local is_explicit_target = g.IO.ConfigDockingWithShift or ImGui.IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max) + -- Preview docking request and find out split direction/ratio + --local do_preview = true -- Ignore testing for payload:IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window. local do_preview = ImGuiPayload_IsPreview(payload) or ImGuiPayload_IsDelivery(payload) if do_preview and (node ~= nil or dock_into_floating_window) then + -- If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear. local split_inner = ImGuiDockPreviewData() local split_outer = ImGuiDockPreviewData() local split_data = split_inner @@ -3186,9 +4284,11 @@ function ImGui.BeginDockableDragDropTarget(window) end if split_data == split_outer then split_inner.IsDropAllowed = false end + -- Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes ImGui.DockNodePreviewDockRender(window, node, payload_window, split_inner) ImGui.DockNodePreviewDockRender(window, node, payload_window, split_outer) + -- Queue docking request if split_data.IsDropAllowed and ImGuiPayload_IsDelivery(payload) then ImGui.DockContextQueueDock(g, window, split_data.SplitNode, payload_window, split_data.SplitDir, split_data.SplitRatio, split_data == split_outer) end @@ -3197,24 +4297,36 @@ function ImGui.BeginDockableDragDropTarget(window) ImGui.EndDragDropTarget() end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Settings ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockSettingsRenameNodeReferences() +-- - DockSettingsRemoveNodeReferences() +-- - DockSettingsFindNodeSettings() +-- - DockSettingsHandler_ApplyAll() +-- - DockSettingsHandler_ReadOpen() +-- - DockSettingsHandler_ReadLine() +-- - DockSettingsHandler_DockNodeToSettings() +-- - DockSettingsHandler_WriteAll() +------------------------------------------------------------------------------- DockSettingsRenameNodeReferences = function(old_node_id, new_node_id) local g = ImGui.GetCurrentContext() for _, window in g.Windows:iter() do if window.DockId == old_node_id and window.DockNode == nil then window.DockId = new_node_id end end + ---- FIXME-OPT: We could remove this loop by storing the index in the map for _, settings in g.SettingsWindows:iter() do if settings.DockId == old_node_id then settings.DockId = new_node_id end end end +-- Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings --- @param node_ids table # 1-based array DockSettingsRemoveNodeReferences = function(node_ids, node_ids_count) local g = ImGui.GetCurrentContext() local found = 0 + ---- FIXME-OPT: We could remove this loop by storing the index in the map for _, settings in g.SettingsWindows:iter() do for node_n = 1, node_ids_count do if settings.DockId == node_ids[node_n] then @@ -3229,19 +4341,23 @@ DockSettingsRemoveNodeReferences = function(node_ids, node_ids_count) end DockSettingsFindNodeSettings = function(ctx, id) + -- FIXME-OPT for _, s in ctx.DockContext.NodesSettings:iter() do if s.ID == id then return s end end return nil end +-- Clear settings data DockSettingsHandler_ClearAll = function(ctx, handler) local dc = ctx.DockContext dc.NodesSettings:clear() ImGui.DockContextClearNodes(ctx, 0, true) end +-- Recreate nodes based on settings data DockSettingsHandler_ApplyAll = function(ctx, handler) + -- Prune settings at boot time only local dc = ctx.DockContext if ctx.Windows.Size == 0 then ImGui.DockContextPruneUnusedSettingsNodes(ctx) end ImGui.DockContextBuildNodesFromSettings(ctx, dc.NodesSettings.Data or {}, dc.NodesSettings.Size) @@ -3254,6 +4370,10 @@ DockSettingsHandler_ReadOpen = function(ctx, handler, name) end DockSettingsHandler_ReadLine = function(ctx, handler, entry, line) + -- Parsing, e.g. + -- " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 " + -- " DockNode ID=0x00000002 Parent=0x00000001 " + -- Important: this code expect currently fields in a fixed order. local node = ImGuiDockNodeSettings() line = line:gsub("^[ \t]+", "") if line:sub(1, 8) == "DockNode" then @@ -3335,6 +4455,8 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) local dc = ctx.DockContext if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then return end + -- Gather settings data + -- (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer) dc.NodesSettings:resize(0) for _, id in ipairs(DockContextNodesSorted(ctx)) do local node = dc.Nodes[id] @@ -3346,9 +4468,10 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) local max_depth = 0 for _, s in dc.NodesSettings:iter() do max_depth = ImMax(s.Depth, max_depth) end + -- Write to text buffer buf:appendf("[%s][Data]\n", handler.TypeName) for _, s in dc.NodesSettings:iter() do - buf:append(string.rep(" ", s.Depth * 2) .. ((bit32.band(s.Flags, ImGuiDockNodeFlags.DockSpace) ~= 0) and "DockSpace" or "DockNode ") .. string.rep(" ", (max_depth - s.Depth) * 2)) + buf:append(string.rep(" ", s.Depth * 2) .. ((bit32.band(s.Flags, ImGuiDockNodeFlags.DockSpace) ~= 0) and "DockSpace" or "DockNode ") .. string.rep(" ", (max_depth - s.Depth) * 2)) -- Text align nodes to facilitate looking at .ini file buf:appendf(" ID=0x%08X", s.ID) if s.ParentNodeId ~= 0 then buf:appendf(" Parent=0x%08X SizeRef=%d,%d", s.ParentNodeId, s.SizeRef.x, s.SizeRef.y) @@ -3369,9 +4492,9 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) buf:append("\n") end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: helpers (imgui_internal.h inlines) + widgets used by docking ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.DockNodeGetRootNode(node) while node.ParentNode do node = node.ParentNode end @@ -3411,10 +4534,14 @@ function ImGui.SetNextWindowDockID(id, cond) g.NextWindowData.DockId = id end +-- We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them. function ImGui.StartMouseMovingWindowOrNode(window, node, undock) local g = ImGui.GetCurrentContext() local can_undock_node = false if undock and node ~= nil and node.VisibleWindow and bit32.band(node.VisibleWindow.Flags, ImGuiWindowFlags.NoMove) == 0 and bit32.band(node.MergedFlags, ImGuiDockNodeFlags.NoUndocking) == 0 then + -- 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. Undocking from a fixed/central node will create a new node and copy windows. local root_node = ImGui.DockNodeGetRootNode(node) if root_node.OnlyNodeWithWindows ~= node or root_node.CentralNode ~= nil then can_undock_node = true @@ -3424,18 +4551,21 @@ function ImGui.StartMouseMovingWindowOrNode(window, node, undock) local clicked = ImGui.IsMouseClicked(0) local dragging = ImGui.IsMouseDragging(0) if can_undock_node and dragging then - ImGui.DockContextQueueUndockNode(g, node) + ImGui.DockContextQueueUndockNode(g, node) -- Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame elseif not can_undock_node and (clicked or dragging) and g.MovingWindow ~= window then ImGui.StartMouseMovingWindow(window) end end +-- This is less wide than RenderArrow() and we use in dock nodes instead of the regular RenderArrow() to denote a change of functionality, +-- and because the saved space means that the left-most tab label can stay at exactly the same position as the label of a loose window. function ImGui.RenderArrowDockMenu(draw_list, p_min, sz, col) draw_list:AddRectFilled(p_min + ImVec2(sz * 0.20, sz * 0.15), p_min + ImVec2(sz * 0.80, sz * 0.30), col) ImGui.RenderArrowPointingAt(draw_list, p_min + ImVec2(sz * 0.50, sz * 0.85), ImVec2(sz * 0.30, sz * 0.40), ImGuiDir.Down, col) end -- Upstream CollapseButton (docking branch): replaces the port's simpler version +-- The Collapse button also functions as a Dock Menu button. function ImGui.CollapseButton(id, pos, dock_node) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow @@ -3445,6 +4575,8 @@ function ImGui.CollapseButton(id, pos, dock_node) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, ImGuiButtonFlags.None) if is_clipped then return pressed end + -- Render + --local is_dock_menu = (window.DockNodeAsHost and not window.Collapsed) local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.ButtonActive or (hovered and ImGuiCol.ButtonHovered or ImGuiCol.Button)) local text_col = ImGui.GetColorU32(ImGuiCol.Text) if hovered or held then @@ -3458,13 +4590,15 @@ function ImGui.CollapseButton(id, pos, dock_node) ImGui.RenderArrow(window.DrawList, bb.Min, text_col, window.Collapsed and ImGuiDir.Right or ImGuiDir.Down, 1.0) end + -- Switch to moving the window after mouse is moved beyond the initial drag threshold if ImGui.IsItemActive() and ImGui.IsMouseDragging(0) then - ImGui.StartMouseMovingWindowOrNode(window, dock_node, true) + ImGui.StartMouseMovingWindowOrNode(window, dock_node, true) -- Undock from window/collapse menu button end return pressed end +-- Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise. --- @return bool held, float size1, float size2 function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2, hover_extend, hover_visibility_delay, bg_col) hover_extend = hover_extend or 0.0 @@ -3475,13 +4609,16 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 if not ImGui.ItemAdd(bb, id, nil, ImGuiItemFlags.NoNav) then return false, size1, size2 end + -- FIXME: AFAIK the only leftover reason for passing ImGuiButtonFlags.AllowOverlap here is + -- to allow caller of SplitterBehavior() to call SetItemAllowOverlap() after the item. + -- Nowadays we would instead want to use SetNextItemAllowOverlap() before the item. local button_flags = bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.AllowOverlap) local bb_interact = ImRect(bb.Min, bb.Max) bb_interact:Expand(axis == ImGuiAxis.Y and ImVec2(0.0, hover_extend) or ImVec2(hover_extend, 0.0)) local _, hovered, held = ImGui.ButtonBehavior(bb_interact, id, button_flags) if hovered then - g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) + g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) -- for IsItemHovered(), because bb_interact is larger than bb end if held or (hovered and g.HoveredIdPreviousFrame == id and g.HoveredIdTimer >= hover_visibility_delay) then @@ -3493,11 +4630,13 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 local d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min local mouse_delta = d[axis] + -- Minimum pane size local size_1_maximum_delta = ImMax(0.0, size1 - min_size1) local size_2_maximum_delta = ImMax(0.0, size2 - min_size2) if mouse_delta < -size_1_maximum_delta then mouse_delta = -size_1_maximum_delta end if mouse_delta > size_2_maximum_delta then mouse_delta = size_2_maximum_delta end + -- Apply resize if mouse_delta ~= 0.0 then size1 = ImMax(size1 + mouse_delta, min_size1) size2 = ImMax(size2 - mouse_delta, min_size2) @@ -3506,6 +4645,7 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 end end + -- Render at new position if bit32.band(bg_col, IM_COL32_A_MASK) ~= 0 then window.DrawList:AddRectFilled(bb_render.Min, bb_render.Max, bg_col, 0.0) end @@ -3516,19 +4656,22 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 end end --[[ [SECTION] imgui_docking (was imgui_docking.lua) ]] -local IMGUI_DEBUG_NAV_SCORING = false -local IMGUI_DEBUG_NAV_RECTS = false +-- Debug options +local IMGUI_DEBUG_NAV_SCORING = false -- Display navigation scoring preview when hovering items. Hold Ctrl to display for all candidates. Ctrl+Arrow to change last direction. +local IMGUI_DEBUG_NAV_RECTS = false -- Display the reference navigation rectangle for each window +-- Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls. local FONT_DEFAULT_SIZE_BASE = 20 -local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 -local WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70 +local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 -- Reduce visual noise by only highlighting the border after a certain time. +local WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70 -- Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved. +-- Tooltip offset local TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10) -- Multiplied by g.Style.MouseCursorScale local TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20) -- Multiplied by g.Style.MouseCursorScale local TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5, 1.0) -- Multiplied by g.Style.MouseCursorScale -local IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111 +local 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. local string = string ImFormatString = string.format -- TODO: an simplified version that operates on byte tables directly? @@ -3539,9 +4682,9 @@ ImStd.sscanf = IM_INCLUDE"imstd_minstdio.lua" local math = math local bit32 = bit32 ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] MISC HELPERS/UTILITIES (File functions) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- This closes the _file. --- @param _file any # File object @@ -3577,6 +4720,7 @@ if gmod then IM_FILE_READ = FindMetaTable("File").Read --- @type function end +-- Default file functions if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then --- [GMod] Another Platform specific if gmod then @@ -3606,6 +4750,8 @@ if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then end end + -- Helper: Load file content into memory + -- This can't really be used with "rt" because fseek size won't match read size. --- @param filename string --- @param mode string --- @return table?, integer? @@ -3637,6 +4783,9 @@ local CalcNextScrollFromScrollTargetAndClamp local MT = ImGui.GetMetatables() +-- Scale all spacing/padding/thickness values. Do not scale fonts. +-- Consider not calling this if your initial scale factor if <1.0. +-- 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. --- @param scale_factor float function MT.ImGuiStyle:ScaleAllSizes(scale_factor) self._MainScale = self._MainScale * scale_factor @@ -3693,17 +4842,20 @@ function MT.ImGuiStyle:ScaleAllSizes(scale_factor) self.MouseCursorScale = ImTrunc(self.MouseCursorScale * scale_factor) end +-- Data for resizing from resize grip / corner local ImGuiResizeGripDef = { - {CornerPosN = ImVec2(1, 1), InnerDir = ImVec2(-1, -1), AngleMin12 = 0, AngleMax12 = 3}, -- Bottom right grip - {CornerPosN = ImVec2(0, 1), InnerDir = ImVec2( 1, -1), AngleMin12 = 3, AngleMax12 = 6} -- Bottom left + {CornerPosN = ImVec2(1, 1), InnerDir = ImVec2(-1, -1), AngleMin12 = 0, AngleMax12 = 3}, -- Lower-right + {CornerPosN = ImVec2(0, 1), InnerDir = ImVec2( 1, -1), AngleMin12 = 3, AngleMax12 = 6} -- Lower-left } +-- Data for resizing from borders +-- InnerDir: Normal toward inside, SegmentN1/SegmentN2: End positions, normalized (0,0: upper left), OuterAngle: Angle toward outside --- [1] Left, [2] Right, [3] Up, [4] Down local ImGuiResizeBorderDef = { - {InnerDir = ImVec2( 1, 0), SegmentN1 = ImVec2( 0, 1), SegmentN2 = ImVec2( 0, 0), OuterAngle = IM_PI * 1.00}, - {InnerDir = ImVec2(-1, 0), SegmentN1 = ImVec2( 1, 0), SegmentN2 = ImVec2( 1, 1), OuterAngle = IM_PI * 0.00}, - {InnerDir = ImVec2( 0, 1), SegmentN1 = ImVec2( 0, 0), SegmentN2 = ImVec2( 1, 0), OuterAngle = IM_PI * 1.50}, - {InnerDir = ImVec2( 0, -1), SegmentN1 = ImVec2( 1, 1), SegmentN2 = ImVec2( 0, 1), OuterAngle = IM_PI * 0.50} + {InnerDir = ImVec2( 1, 0), SegmentN1 = ImVec2( 0, 1), SegmentN2 = ImVec2( 0, 0), OuterAngle = IM_PI * 1.00}, -- Left + {InnerDir = ImVec2(-1, 0), SegmentN1 = ImVec2( 1, 0), SegmentN2 = ImVec2( 1, 1), OuterAngle = IM_PI * 0.00}, -- Right + {InnerDir = ImVec2( 0, 1), SegmentN1 = ImVec2( 0, 0), SegmentN2 = ImVec2( 1, 0), OuterAngle = IM_PI * 1.50}, -- Up + {InnerDir = ImVec2( 0, -1), SegmentN1 = ImVec2( 1, 1), SegmentN2 = ImVec2( 0, 1), OuterAngle = IM_PI * 0.50} -- Down } --- @param window ImGuiWindow @@ -3733,6 +4885,8 @@ local function GetResizeBorderRect(window, border_n, perp_padding, thickness) return ImRect() end +-- Known size hash +-- It is ok to call ImHashData on a string with known length but the ### operator won't be supported. --- @param data table|number --- @param size int? # size = -1 to indicate that `data` is a single number --- @param seed int? @@ -3759,6 +4913,8 @@ function ImHashData(data, size, seed) return hash end +-- Zero-terminated string hash, with support for ### to reset back to seed value. +-- e.g. "label###id" outputs the same hash as "id" (and "label" is generally displayed by the UI functions) -- Use FNV1a, as one ImGui FIXME suggested --- @param str string --- @param size int? @@ -3828,6 +4984,9 @@ local shifte = {0, 6, 4, 2, 0} local s = {0, 0, 0, 0} +-- Convert UTF-8 to 32-bit character, process single character input. +-- A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8). +-- We handle UTF-8 decoding error by skipping forward. --- @param in_text ImString --- @param pos int --- @param in_text_end int @@ -3837,15 +4996,19 @@ function ImStd.ImTextCharFromUtf8(in_text, pos, in_text_end) local len = lengths[bit32.rshift(ImStrByte(in_text, pos), 3) + 1] local wanted = len > 0 and len or 1 + -- IMPORTANT: if in_text_end == nil it assume we have enough space! if in_text_end == nil then - in_text_end = pos + wanted + in_text_end = pos + wanted -- Max length, nulls will be taken into account. end + -- Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here, + -- so it is fast even with excessive branching. s[1] = (pos < in_text_end) and ImStrByte(in_text, pos) or 0 s[2] = (pos + 1 < in_text_end) and ImStrByte(in_text, pos + 1) or 0 s[3] = (pos + 2 < in_text_end) and ImStrByte(in_text, pos + 2) or 0 s[4] = (pos + 3 < in_text_end) and ImStrByte(in_text, pos + 3) or 0 + -- Assume a four-byte character and load four bytes. Unused bits are shifted out. local out_char out_char = bit32.lshift(bit32.band(s[1], masks[len + 1]), 18) out_char = bit32.bor(out_char, bit32.lshift(bit32.band(s[2], 0x3f), 12)) @@ -3853,17 +5016,22 @@ function ImStd.ImTextCharFromUtf8(in_text, pos, in_text_end) out_char = bit32.bor(out_char, bit32.lshift(bit32.band(s[4], 0x3f), 0)) out_char = bit32.rshift(out_char, shiftc[len + 1]) + -- Accumulate the various error conditions. local e = 0 - e = bit32.lshift((out_char < mins[len + 1]) and 1 or 0, 6) - e = bit32.bor(e, bit32.lshift((bit32.rshift(out_char, 11) == 0x1b) and 1 or 0, 7)) - e = bit32.bor(e, bit32.lshift((out_char > IM_UNICODE_CODEPOINT_MAX) and 1 or 0, 8)) + e = bit32.lshift((out_char < mins[len + 1]) and 1 or 0, 6) -- non-canonical encoding + e = bit32.bor(e, bit32.lshift((bit32.rshift(out_char, 11) == 0x1b) and 1 or 0, 7)) -- surrogate half? + e = bit32.bor(e, bit32.lshift((out_char > IM_UNICODE_CODEPOINT_MAX) and 1 or 0, 8)) -- out of range we can store in ImWchar (FIXME: May evolve) e = bit32.bor(e, bit32.rshift(bit32.band(s[2], 0xc0), 2)) e = bit32.bor(e, bit32.rshift(bit32.band(s[3], 0xc0), 4)) e = bit32.bor(e, bit32.rshift(s[4], 6)) - e = bit32.bxor(e, 0x2a) + e = bit32.bxor(e, 0x2a) -- top two bits of each tail byte correct? e = bit32.rshift(e, shifte[len + 1]) if e ~= 0 then + -- No bytes are consumed when in_text[pos] == 0 || pos == in_text_end. + -- One byte is consumed in case of invalid first byte of in_text. + -- All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes. + -- Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s. wanted = ImMin(wanted, (s[1] ~= 0 and 1 or 0) + (s[2] ~= 0 and 1 or 0) + (s[3] ~= 0 and 1 or 0) + (s[4] ~= 0 and 1 or 0)) out_char = IM_UNICODE_CODEPOINT_INVALID end @@ -3873,6 +5041,7 @@ end end +-- Based on stb_to_utf8() from github.com/nothings/stb/ --- @param buf char[] --- @param buf_size int --- @param c unsigned_int @@ -3921,6 +5090,7 @@ function ImStd.ImTextCharToUtf8(out_buf, c) return count end +-- Not optimal but we very rarely use this function. --- @param in_text ImString --- @param pos int --- @param in_text_end int @@ -4052,6 +5222,7 @@ function ImStd.ImStrncpy(dst, dst_pos, src, src_pos, count) dst[dst_pos + (count - 1)] = 0 end +-- find beginning-of-line --- @param str char[] --- @param mid_line int --- @param begin int @@ -4063,31 +5234,55 @@ function ImStd.ImStrbol(str, mid_line, begin) return mid_line end +-- Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. --- @param buf char[] function ImStd.ImStrTrimBlanks(buf) local p = 1 -- buf_begin - while buf[p] == 32 or buf[p] == 9 do + while buf[p] == 32 or buf[p] == 9 do -- Leading blanks p = p + 1 end local p_start = p - while buf[p] ~= 0 do + while buf[p] ~= 0 do -- Find end of string p = p + 1 end - while p > p_start and (buf[p - 1] == 32 or buf[p - 1] == 9) do + while p > p_start and (buf[p - 1] == 32 or buf[p - 1] == 9) do -- Trailing blanks p = p - 1 end - if p_start > 1 then + if p_start > 1 then -- Copy memory if we had leading blanks ImStd.memmove(buf, 1, buf, p_start, p - p_start) end - buf[p - p_start + 1] = 0 + buf[p - p_start + 1] = 0 -- Zero terminate end +------------------------------------------------------------------------------- +-- [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] +-- - RegisterFontAtlas() [Internal] +-- - UnregisterFontAtlas() [Internal] +-- - SetCurrentFont() [Internal] +-- - UpdateCurrentFontSize() [Internal] +-- - PushFont() +-- - PopFont() +------------------------------------------------------------------------------- + function ImGui.UpdateCurrentFontSize(restore_font_size_after_scaling) local g = GImGui local window = g.CurrentWindow g.Style.FontSizeBase = g.FontSizeBase + -- Early out to avoid hidden window keeping bakes referenced and out of GC reach. + -- - However this leave a pretty subtle and damning error surface area if g.FontBaked was mismatching. + -- Probably needs to be reevaluated into e.g. setting g.FontBaked = nil to mark it as dirty. + -- - Note that 'PushFont(); Begin(); End(); PopFont()' from within any collapsed window is not compromised, because Begin() calls SetCurrentWindow()->...->UpdateCurrentSize() -- if (window ~= nil and window.SkipItems) then -- local table = g.CurrentTable -- if (table == nil or (table.CurrentColumn ~= -1 and table.Columns[table.CurrentColumn].IsSkipItems == false)) then @@ -4095,17 +5290,24 @@ function ImGui.UpdateCurrentFontSize(restore_font_size_after_scaling) -- end -- end + -- Restoring is pretty much only used by PopFont() local final_size = (restore_font_size_after_scaling > 0.0) and restore_font_size_after_scaling or 0.0 if final_size == 0.0 then final_size = g.FontSizeBase - final_size = final_size * g.Style.FontScaleMain - final_size = final_size * g.Style.FontScaleDpi + -- Global scale factors + final_size = final_size * g.Style.FontScaleMain -- Main global scale factor + final_size = final_size * g.Style.FontScaleDpi -- Per-monitor/viewport DPI scale factor (in docking branch: automatically updated when io.ConfigDpiScaleFonts is enabled). + + -- Window scale (mostly obsolete now) if window ~= nil then final_size = final_size * window.FontWindowScale end end + -- 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 = ImGui.GetRoundedFontSize(final_size) final_size = ImClamp(final_size, 4.0, IMGUI_FONT_SIZE_MAX) if (g.Font ~= nil and bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) ~= 0) then @@ -4118,6 +5320,14 @@ function ImGui.UpdateCurrentFontSize(restore_font_size_after_scaling) g.DrawListSharedData.FontScale = g.FontBakedScale end +-- 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() ? function ImGui.SetCurrentFont(font, font_size_before_scaling, font_size_after_scaling) local g = GImGui @@ -4126,7 +5336,7 @@ function ImGui.SetCurrentFont(font, font_size_before_scaling, font_size_after_sc ImGui.UpdateCurrentFontSize(font_size_after_scaling) if font ~= nil then - IM_ASSERT(font and font:IsLoaded()) + IM_ASSERT(font and font:IsLoaded()) -- Font Atlas not created. Did you call io.Fonts:GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? local atlas = font.OwnerAtlas g.DrawListSharedData.FontAtlas = atlas g.DrawListSharedData.Font = font @@ -4137,10 +5347,11 @@ function ImGui.SetCurrentFont(font, font_size_before_scaling, font_size_after_sc end end +-- If you want to scale an existing font size! Read comments in imgui.h! function ImGui.PushFont(font, font_size_base) local g = GImGui - if font == nil then + if font == nil then -- Before 1.92 (June 2025), PushFont(nil) == PushFont(GetDefaultFont()) font = g.Font end @@ -4150,7 +5361,7 @@ function ImGui.PushFont(font, font_size_base) g.FontStack:push_back(ImFontStackData(font, g.FontSizeBase, g.FontSize)) if font_size_base == 0.0 then - font_size_base = g.FontSizeBase + font_size_base = g.FontSizeBase -- Keep current font size end ImGui.SetCurrentFont(font, font_size_base, 0.0) @@ -4172,12 +5383,17 @@ function ImGui.PopFont() end function 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. local g = GImGui local has_textures = bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) ~= 0 for _, atlas in g.FontAtlases:iter() do if (atlas.OwnerContext == g) then 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 ~= nil and atlas.Builder.FrameCount ~= -1) IM_ASSERT(atlas.RendererHasTextures == has_textures) end @@ -4188,11 +5404,14 @@ function ImGui.UpdateTexturesNewFrame() end end +-- Build a single texture list function ImGui.UpdateTexturesEndFrame() local g = GImGui g.PlatformIO.Textures:resize(0) for _, atlas in g.FontAtlases:iter() do for _, tex in atlas.TexList:iter() do + -- 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 = atlas.RefCount g.PlatformIO.Textures:push_back(tex) end @@ -4215,16 +5434,18 @@ function ImGui.UpdateFontsNewFrame() g.Style._NextFrameFontSizeBase = 0.0 end + -- Apply default font size the first time local font = ImGui.GetDefaultFont() if g.Style.FontSizeBase <= 0.0 then g.Style.FontSizeBase = ((font.LegacySize > 0.0) and font.LegacySize or FONT_DEFAULT_SIZE_BASE) end + -- Set initial font g.Font = font g.FontSizeBase = g.Style.FontSizeBase g.FontSize = 0.0 - local font_stack_data = ImFontStackData(font, g.Style.FontSizeBase, g.Style.FontSizeBase) - ImGui.SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0) + local font_stack_data = ImFontStackData(font, g.Style.FontSizeBase, g.Style.FontSizeBase) -- <--- Will restore FontSize + ImGui.SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0) -- <--- but use 0.0f to enable scale g.FontStack:push_back(font_stack_data) IM_ASSERT(g.Font:IsLoaded()) end @@ -4269,6 +5490,11 @@ function ImGui.UnregisterFontAtlas(atlas) end end +------------------------------------------------------------------------------- +-- [SECTION] INITIALIZATION, SHUTDOWN +------------------------------------------------------------------------------- + +-- Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself function ImGui.GetCurrentContext() return GImGui end @@ -4300,12 +5526,14 @@ local function ImGuiLocEntry(key, text) return { Key = key, Text = text } end +-- IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation. local GLocalizationEntriesEnUS = { ImGuiLocEntry(ImGuiLocKey.VersionStr, "Dear ImGui WIP"), ImGuiLocEntry(ImGuiLocKey.TableSizeOne, "Size column to fit###SizeOne"), ImGuiLocEntry(ImGuiLocKey.TableSizeAllFit, "Size all columns to fit###SizeAll"), ImGuiLocEntry(ImGuiLocKey.TableSizeAllDefault, "Size all columns to default###SizeAll"), ImGuiLocEntry(ImGuiLocKey.TableReset, "Reset"), + --ImGuiLocEntry(ImGuiLocKey.TableResetAll, "Reset to default###ResetAll"), ImGuiLocEntry(ImGuiLocKey.TableResetOrder, "Reset order###ResetOrder"), ImGuiLocEntry(ImGuiLocKey.TableResetVisibility, "Reset visibility###ResetVisibility"), ImGuiLocEntry(ImGuiLocKey.WindowingMainMenuBar, "(Main menu bar)"), @@ -4322,11 +5550,15 @@ function ImGui.Initialize() local g = GImGui IM_ASSERT(not g.Initialized and not g.SettingsLoaded) + -- Add .ini handle for ImGuiWindow and ImGuiTable types ImGui.WindowSettingsAddSettingsHandler() if ImGui.TableSettingsAddSettingsHandler then ImGui.TableSettingsAddSettingsHandler() end + -- Initialize Docking ImGui.DockContextInitialize(g) + -- Setup default localization table ImGui.LocalizeRegisterEntries(GLocalizationEntriesEnUS, #GLocalizationEntriesEnUS) + -- Create default viewport local viewport = ImGuiViewportP() viewport.ID = IMGUI_VIEWPORT_DEFAULT_ID viewport.Idx = 1 @@ -4336,6 +5568,7 @@ function ImGui.Initialize() g.ViewportCreatedCount = g.ViewportCreatedCount + 1 g.PlatformIO.Viewports:push_back(g.Viewports.Data[1]) + -- Build KeysMayBeCharInput[] lookup table (1 bit per named key) for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do if (key >= ImGuiKey.K0 and key <= ImGuiKey.K9) or (key >= ImGuiKey.A and key <= ImGuiKey.Z) or (key >= ImGuiKey.Keypad0 and key <= ImGuiKey.Keypad9) or key == ImGuiKey.Tab or key == ImGuiKey.Space or key == ImGuiKey.Apostrophe or key == ImGuiKey.Comma or key == ImGuiKey.Minus or key == ImGuiKey.Period @@ -4345,6 +5578,8 @@ function ImGui.Initialize() end end + -- 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. local atlas = g.IO.Fonts g.DrawListSharedData.Context = g ImGui.RegisterFontAtlas(atlas) @@ -4375,6 +5610,7 @@ function ImGui.DestroyContext(ctx) ImGui.SetCurrentContext((prev_ctx ~= ctx) and prev_ctx or nil) end +-- This is faster if you are holding on a Window already as we don't need to perform a search. --- @param window ImGuiWindow --- @return any function ImGui.FindWindowSettingsByWindow(window) @@ -4385,6 +5621,8 @@ function ImGui.FindWindowSettingsByWindow(window) return ImGui.FindWindowSettingsByID(window.ID) end +-- We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names. +-- This is called once per window .ini entry + once per newly instantiated window. --- @param id ImGuiID --- @return any function ImGui.FindWindowSettingsByID(id) @@ -4460,6 +5698,8 @@ local function ApplyWindowSettings(window, settings) end end +-- Note that 'settings' may be nil. +-- Sets _Once, _Appearing, _FirstUseEver. _FirstUseEver will be cleared again if there are settings. --- @param window ImGuiWindow --- @param settings ImGuiWindowSettings local function InitOrLoadWindowSettings(window, settings) @@ -4484,6 +5724,8 @@ end --- @param flags ImGuiWindowFlags --- @return ImGuiWindow local function CreateNewWindow(name, flags) + -- Create window the first time + --IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags) local g = GImGui local window_id = ImHashStr(name) @@ -4506,7 +5748,7 @@ local function CreateNewWindow(name, flags) InitOrLoadWindowSettings(window, settings) if bit32.band(flags, ImGuiWindowFlags.NoBringToFrontOnFocus) ~= 0 then - g.Windows:push_front(window) + g.Windows:push_front(window) -- Quite slow but rare and only once else g.Windows:push_back(window) end @@ -4515,21 +5757,41 @@ local function CreateNewWindow(name, flags) end ---------------------------------------------------------------------------------------- --- [SECTION] SETTINGS (in-memory .ini; Roblox has no disk) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] SETTINGS +-- (in-memory .ini; Roblox has no disk) +------------------------------------------------------------------------------- +-- - UpdateSettings() [Internal] +-- - MarkIniSettingsDirty() [Internal] +-- - FindSettingsHandler() [Internal] +-- - ClearIniSettings() [Internal] +-- - LoadIniSettingsFromDisk() +-- - LoadIniSettingsFromMemory() +-- - SaveIniSettingsToDisk() +-- - SaveIniSettingsToMemory() +------------------------------------------------------------------------------- +-- - CreateNewWindowSettings() [Internal] +-- - FindWindowSettingsByID() [Internal] +-- - FindWindowSettingsByWindow() [Internal] +-- - ClearWindowSettings() [Internal] +-- - WindowSettingsHandler_***() [Internal] +------------------------------------------------------------------------------- +-- Called by NewFrame() function ImGui.UpdateSettings() + -- Load settings on first frame (if not explicitly loaded manually before) local g = GImGui if not g.SettingsLoaded then if g.IO.IniFilename then ImGui.LoadIniSettingsFromDisk(g.IO.IniFilename) end g.SettingsLoaded = true end + + -- Save settings (with a delay after the last modification, so we don't spam disk too much) if g.SettingsDirtyTimer > 0.0 then g.SettingsDirtyTimer = g.SettingsDirtyTimer - g.IO.DeltaTime if g.SettingsDirtyTimer <= 0.0 then -- No disk: always let the user know they can call SaveIniSettingsToMemory() - g.IO.WantSaveIniSettings = true + g.IO.WantSaveIniSettings = true -- Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. g.SettingsDirtyTimer = 0.0 end end @@ -4567,6 +5829,7 @@ function ImGui.FindSettingsHandler(type_name) return nil end +-- Clear all settings (windows, tables, docking etc.) function ImGui.ClearIniSettings() local g = GImGui g.SettingsIniData = "" @@ -4594,13 +5857,20 @@ function ImGui.LoadIniSettingsFromDisk(ini_filename) ImGui.LoadIniSettingsFromMemory(table.concat(parts)) end ---- Zero-tolerance, cheap .ini parsing. `ini_size` ignored (Lua strings know their length). +-- Zero-tolerance, no error reporting, cheap .ini parsing +-- Set ini_size==0 (or nil) to use the whole string (Lua strings know their length). function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) local g = GImGui IM_ASSERT(g.Initialized) + --IM_ASSERT(not g.WithinFrameScope, "Cannot be called between NewFrame() and EndFrame()") + --IM_ASSERT(g.SettingsLoaded == false and g.FrameCount == 0) + + -- For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). if ini_size and ini_size > 0 then ini_data = ini_data:sub(1, ini_size) end g.SettingsIniData = ini_data + -- Call pre-read handlers + -- Some types will clear their data (e.g. dock information) some types will allow merge/override (window) for _, handler in g.SettingsHandlers:iter() do if handler.ReadInitFn then handler.ReadInitFn(g, handler) end end @@ -4611,7 +5881,7 @@ function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) if c == ";" then -- comment elseif c == "[" and line:sub(-1) == "]" then - -- "[Type][Name]" (Name may contain [] characters) + -- Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. local type_name, name = line:match("^%[([^%]]*)%]%[(.*)%]$") if type_name then entry_handler = ImGui.FindSettingsHandler(type_name) @@ -4620,11 +5890,13 @@ function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) entry_handler, entry_data = nil, nil end elseif entry_handler ~= nil and entry_data ~= nil then + -- Let type handler parse the line entry_handler.ReadLineFn(g, entry_handler, entry_data, line) end end g.SettingsLoaded = true + -- Call post-read handlers for _, handler in g.SettingsHandlers:iter() do if handler.ApplyAllFn then handler.ApplyAllFn(g, handler) end end @@ -4636,6 +5908,7 @@ function ImGui.SaveIniSettingsToDisk(ini_filename) -- Roblox: no disk. Call SaveIniSettingsToMemory() and persist the string yourself (e.g. DataStore). end +-- Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer --- @return string ini_data, int size function ImGui.SaveIniSettingsToMemory() local g = GImGui @@ -4650,6 +5923,8 @@ end function ImGui.CreateNewWindowSettings(name) local g = GImGui + + -- Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier. if not g.IO.ConfigDebugIniSettings then -- ImHashSkipUncontributingPrefix: skip everything up to the last "###" local p = name:match("^.*()###") @@ -4662,7 +5937,9 @@ function ImGui.CreateNewWindowSettings(name) return settings end +-- This will revert window to its initial state, including enabling the ImGuiCond.FirstUseEver/ImGuiCond.Once conditions once more. function ImGui.ClearWindowSettings(name) + --IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name) local window = ImGui.FindWindowByName(name) if window ~= nil then window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.NoSavedSettings) @@ -4685,6 +5962,7 @@ local function WindowSettingsHandler_ReadOpen(ctx, handler, name) local id = ImHashStr(name) local settings = ImGui.FindWindowSettingsByID(id) if settings then + -- Clear existing if recycling previous entry local fresh = ImGuiWindowSettings() for k, v in pairs(fresh) do settings[k] = v end settings.Name = name @@ -4719,6 +5997,7 @@ local function WindowSettingsHandler_ReadLine(ctx, handler, settings, line) if x then settings.ClassId = tonumber(x, 16) return end end +-- Apply to existing windows (if any) local function WindowSettingsHandler_ApplyAll(ctx, handler) local g = ctx for _, settings in g.SettingsWindows:iter() do @@ -4731,6 +6010,8 @@ local function WindowSettingsHandler_ApplyAll(ctx, handler) end local function WindowSettingsHandler_WriteAll(ctx, handler, buf) + -- Gather data from windows that were active during this session + -- (if a window wasn't opened in this session we preserve its settings) local g = ctx for _, window in g.Windows:iter() do if bit32.band(window.Flags, ImGuiWindowFlags.NoSavedSettings) == 0 then @@ -4748,14 +6029,15 @@ local function WindowSettingsHandler_WriteAll(ctx, handler, buf) settings.ClassId = window.WindowClass and window.WindowClass.ClassId or 0 settings.DockOrder = window.DockOrder or -1 settings.Collapsed = window.Collapsed - settings.IsChild = (window.RootWindow ~= window) + settings.IsChild = (window.RootWindow ~= window) -- Cannot rely on ImGuiWindowFlags.ChildWindow here as docked windows have this set. settings.WantDelete = false end end + -- Write to text buffer for _, settings in g.SettingsWindows:iter() do if not settings.WantDelete then - buf:appendf("[%s][%s]\n", handler.TypeName, settings.Name) + buf:appendf("[%s][%s]\n", handler.TypeName, settings.Name) -- [Window][name] if settings.IsChild then buf:appendf("IsChild=1\n") buf:appendf("Size=%d,%d\n", settings.Size.x, settings.Size.y) @@ -4772,6 +6054,7 @@ local function WindowSettingsHandler_WriteAll(ctx, handler, buf) end buf:appendf("Collapsed=%d\n", settings.Collapsed and 1 or 0) if settings.DockId ~= 0 then + --buf:appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings.ID)) -- window.TabId: this is not read back but writing it makes "debugging" the .ini data easier. if settings.DockOrder == -1 then buf:appendf("DockId=0x%08X\n", settings.DockId) else @@ -4797,14 +6080,18 @@ function ImGui.WindowSettingsAddSettingsHandler() ImGui.AddSettingsHandler(ini_handler) end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] LOGGING/CAPTURING ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- All text output from the interface can be captured into tty/file/clipboard. +-- By default, tree nodes are automatically opened during logging. +------------------------------------------------------------------------------- ImGuiLogFlags = ImGuiLogFlags or { None = 0, OutputTTY = 1, OutputFile = 2, OutputBuffer = 4, OutputClipboard = 8, OutputMask_ = 15, } +-- Pass text data straight to log (without being displayed) local function LogTextV_Internal(g, fmt, ...) local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt if g.LogFile then @@ -4821,7 +6108,9 @@ function ImGui.LogText(fmt, ...) end ImGui.LogTextV = ImGui.LogText ---- Internal version that takes a position to decide on newline placement and pad items according to their depth. +-- Internal version that takes a position to decide on newline placement and pad items according to their depth. +-- We split text into individual lines to add current tree level padding +-- FIXME: This code is a little complicated perhaps, considering simplifying the whole system. --- `text` is a Lua string, `text_begin/text_end` optional 1-based byte range (text_end exclusive). function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) local g = GImGui @@ -4840,13 +6129,16 @@ function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) g.LogLineFirstItem = true end - if prefix then ImGui.LogRenderedText(ref_pos, prefix, #prefix + 1) end + if prefix then ImGui.LogRenderedText(ref_pos, prefix, #prefix + 1) end -- 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 then g.LogDepthRef = window.DC.TreeDepth end local tree_depth = window.DC.TreeDepth - g.LogDepthRef local text_remaining = text_begin while true do + -- Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry. + -- We don't add a trailing \n yet to allow a subsequent item on the same line to be captured. local line_start = text_remaining local nl = string.find(text, "\n", line_start, true) local line_end = (nl and nl < text_end) and nl or text_end @@ -4867,6 +6159,7 @@ function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) if suffix then ImGui.LogRenderedText(ref_pos, suffix, #suffix + 1) end end +-- Start logging/capturing text output function ImGui.LogBegin(flags, auto_open_depth) local g = GImGui local window = g.CurrentWindow @@ -4882,6 +6175,7 @@ function ImGui.LogBegin(flags, auto_open_depth) g.LogBuffer = ImGuiTextBuffer() end +-- Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText) function ImGui.LogSetNextTextDecoration(prefix, suffix) local g = GImGui g.LogNextPrefix = prefix @@ -4895,11 +6189,13 @@ function ImGui.LogToTTY(auto_open_depth) g.LogFile = "stdout" end +-- Start logging/capturing text output to given file function ImGui.LogToFile(auto_open_depth, filename) -- Roblox: no file access. Falls back to TTY (output window). ImGui.LogToTTY(auto_open_depth) end +-- Start logging/capturing text output to clipboard function ImGui.LogToClipboard(auto_open_depth) local g = GImGui if g.LogEnabled then return end @@ -4926,6 +6222,8 @@ function ImGui.LogFinish() g.LogBuffer = ImGuiTextBuffer() end +-- Helper to display logging buttons +-- FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!) function ImGui.LogButtons() local g = GImGui ImGui.PushID("LogButtons") @@ -4937,6 +6235,8 @@ function ImGui.LogButtons() g.LogDepthToExpandDefault = ImGui.SliderInt("Default Depth", g.LogDepthToExpandDefault, 0, 9, nil) ImGui.PopItemFlag() ImGui.PopID() + + -- Start logging at the end of the function so that the buttons don't appear in the log if log_to_tty then ImGui.LogToTTY() end if log_to_file then ImGui.LogToFile() end if log_to_clipboard then ImGui.LogToClipboard() end @@ -4952,6 +6252,7 @@ local function GetWindowForTitleDisplay(window) end end +-- Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID(). --- @param id ImGuiID @native function ImGui.KeepAliveID(id) @@ -4966,6 +6267,9 @@ function ImGui.KeepAliveID(id) end end +-- Test if mouse cursor is hovering given rectangle +-- NB- Rectangle is clipped by our current clip setting +-- NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) --- @param r_min ImVec2 --- @param r_max ImVec2 --- @param clip? bool @@ -4975,6 +6279,7 @@ function ImGui.IsMouseHoveringRect(r_min, r_max, clip) local g = GImGui -- [Luau] scalar version of: rect_clipped = ImRect(r_min, r_max); ClipWith(window.ClipRect); ContainsWithPad(); viewport Overlaps() + -- Clip local x0, y0, x1, y1 = r_min.x, r_min.y, r_max.x, r_max.y if clip then local cr = g.CurrentWindow.ClipRect @@ -4983,6 +6288,7 @@ function ImGui.IsMouseHoveringRect(r_min, r_max, clip) x1 = math.min(x1, cmax.x); y1 = math.min(y1, cmax.y) end + -- Hit testing, expanded for touch input local p, pad = g.IO.MousePos, g.Style.TouchExtraPadding if not (p.x >= x0 - pad.x and p.y >= y0 - pad.y and p.x < x1 + pad.x and p.y < y1 + pad.y) then return false @@ -5025,6 +6331,8 @@ function ImGui.IsMouseDragging(button, lock_threshold) return ImGui.IsMouseDragPastThreshold(button, lock_threshold) end +-- This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well. +-- It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags.HasSetMousePos) is set and supported by backend. --- @param pos ImVec2 function ImGui.TeleportMousePos(pos) local g = GImGui @@ -5035,11 +6343,12 @@ function ImGui.TeleportMousePos(pos) -- IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y) end +-- Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData --- @param id ImGuiID function ImGui.ItemHandleShortcut(id) local g = GImGui local flags = g.NextItemData.ShortcutFlags - IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetNextItemShortcut)) == 0) + IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetNextItemShortcut)) == 0) -- Passing flags not supported by SetNextItemShortcut()! if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.Disabled) ~= 0 then return @@ -5052,13 +6361,19 @@ function ImGui.ItemHandleShortcut(id) return end - g.NavActivateId = id + -- FIXME: Generalize Activation queue? + g.NavActivateId = id -- Will effectively disable clipping. g.NavActivateFlags = bit32.bor(ImGuiActivateFlags.PreferInput, ImGuiActivateFlags.FromShortcut) + -- if (g.ActiveId == 0 || g.ActiveId == id) g.NavActivateDownId = id g.NavActivatePressedId = id ImGui.NavHighlightActivated(id) end +-- Declare item bounding box for clipping and interaction. +-- Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface +-- declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction. +-- THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN) --- @param bb ImRect --- @param id ImGuiID --- @param nav_bb_arg? ImRect @@ -5070,16 +6385,30 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) local g = GImGui local window = g.CurrentWindow + -- Set item data + -- (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags.HasDisplayRect is set) g.LastItemData.ID = id ImRect_Copy(g.LastItemData.Rect, bb) ImRect_Copy(g.LastItemData.NavRect, nav_bb_arg and nav_bb_arg or bb) g.LastItemData.ItemFlags = bit32.bor(g.CurrentItemFlags, g.NextItemData.ItemFlagsSet, extra_flags) g.LastItemData.StatusFlags = ImGuiItemStatusFlags.None + -- Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared. if id ~= 0 then ImGui.KeepAliveID(id) + -- Directional navigation processing + -- Runs prior to clipping early-out + -- (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget + -- (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests + -- unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of + -- thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. + -- We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able + -- to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick). + -- We intentionally don't check if g.NavWindow ~= nil because g.NavAnyRequest should only be set when it is non nil. + -- If we crash on a nil g.NavWindow we need to fix the bug elsewhere. if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoNav) == 0 then + -- FIXME-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test. window.DC.NavLayersActiveMaskNext = bit32.bor(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, window.DC.NavLayerCurrent)) if g.NavId == id or g.NavAnyRequest then @@ -5096,9 +6425,13 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) end end + -- Lightweight clear of SetNextItemXXX data. g.NextItemData.HasFlags = ImGuiNextItemDataFlags.None g.NextItemData.ItemFlagsSet = ImGuiItemFlags.None + -- Clipping test + -- (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false') + -- g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts) local bmin, bmax, cr = bb.Min, bb.Max, window.ClipRect local is_rect_visible = bmin.x <= cr.Max.x and bmax.x >= cr.Min.x and bmin.y <= cr.Max.y and bmax.y >= cr.Min.y if not is_rect_visible then @@ -5111,6 +6444,7 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) g.DeactivatedItemData.ElapseFrame = g.FrameCount end + -- 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 then g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) end @@ -5122,6 +6456,39 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) return true end +------------------------------------------------------------------------------- +-- [SECTION] LAYOUT +------------------------------------------------------------------------------- +-- - ItemSize() +-- - SameLine() +-- - GetCursorScreenPos() +-- - SetCursorScreenPos() +-- - GetCursorPos(), GetCursorPosX(), GetCursorPosY() +-- - SetCursorPos(), SetCursorPosX(), SetCursorPosY() +-- - GetCursorStartPos() +-- - Indent() +-- - Unindent() +-- - SetNextItemWidth() +-- - PushItemWidth() +-- - PushMultiItemsWidths() +-- - PopItemWidth() +-- - CalcItemWidth() +-- - CalcItemSize() +-- - GetTextLineHeight() +-- - GetTextLineHeightWithSpacing() +-- - GetFrameHeight() +-- - GetFrameHeightWithSpacing() +-- - GetContentRegionMax() +-- - GetContentRegionAvail(), +-- - BeginGroup() +-- - EndGroup() +-- Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns. +------------------------------------------------------------------------------- + +-- Advance cursor given item size for layout. +-- Register minimum needed size so it can extend the bounding box used for auto-fit calculation. +-- See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different. +-- THIS IS IN THE PERFORMANCE CRITICAL PATH. --- @param size_or_bb ImVec2|ImRect --- @param text_baseline_y? float @native @@ -5147,6 +6514,9 @@ function ImGui.ItemSize(size_or_bb, text_baseline_y) local dc = window.DC local mathMax = math.max + -- We increase the height in this function to accommodate for baseline offset. + -- In theory we should be offsetting the starting position (window.DC.CursorPos), that will be the topic of a larger refactor, + -- but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect. local offset_to_match_baseline_y if text_baseline_y >= 0 then offset_to_match_baseline_y = mathMax(0, dc.CurrLineTextBaseOffset - text_baseline_y) @@ -5165,12 +6535,15 @@ function ImGui.ItemSize(size_or_bb, text_baseline_y) local line_height = mathMax(dc.CurrLineSize.y, cursor.y - line_y1 + size_y + offset_to_match_baseline_y) local spacing_y = g.Style.ItemSpacing.y + -- Always align ourselves on pixel boundaries + -- if (g.IO.KeyAlt) window.DrawList:AddRect(window.DC.CursorPos, window.DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)) -- [DEBUG] prev_line.x = cursor.x + size_x prev_line.y = line_y1 - cursor.x = math.floor(window.Pos.x + dc.Indent.x + dc.ColumnsOffset.x) - cursor.y = math.floor(line_y1 + line_height + spacing_y) + cursor.x = math.floor(window.Pos.x + dc.Indent.x + dc.ColumnsOffset.x) -- Next line + cursor.y = math.floor(line_y1 + line_height + spacing_y) -- Next line max_pos.x = mathMax(max_pos.x, prev_line.x) max_pos.y = mathMax(max_pos.y, cursor.y - spacing_y) + -- if (g.IO.KeyAlt) window.DrawList:AddCircle(window.DC.CursorMaxPos, 3.0, IM_COL32(255,0,0,255), 4) -- [DEBUG] dc.PrevLineSize.y = line_height dc.CurrLineSize.y = 0 @@ -5179,12 +6552,17 @@ function ImGui.ItemSize(size_or_bb, text_baseline_y) dc.IsSetPos = false dc.IsSameLine = false - --- Horizontal layout mode + -- Horizontal layout mode if (dc.LayoutType == ImGuiLayoutType.Horizontal) then ImGui.SameLine() end end +-- Gets back to previous line and continue with horizontal layout +-- offset_from_start_x == 0 : follow right after previous item +-- offset_from_start_x != 0 : align to specified x position (relative to window/group left) +-- spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0 +-- spacing_w >= 0 : enforce spacing amount --- @param offset_from_start_x float? --- @param spacing_w float? @native @@ -5245,7 +6623,7 @@ function ImGui.Unindent(indent_w) window.DC.CursorPos.x = window.Pos.x + window.DC.Indent.x + window.DC.ColumnsOffset.x end --- Affect large frame+labels widgets only +-- Affect large frame+labels widgets only. --- @param item_width float function ImGui.SetNextItemWidth(item_width) local g = GImGui @@ -5253,11 +6631,12 @@ function ImGui.SetNextItemWidth(item_width) g.NextItemData.Width = item_width end +-- FIXME: Remove the == 0.0f behavior? --- @param item_width float function ImGui.PushItemWidth(item_width) local g = GImGui local window = g.CurrentWindow - window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) + window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) -- Backup current width window.DC.ItemWidth = (item_width == 0.0) and window.DC.ItemWidthDefault or item_width g.NextItemData.HasFlags = bit32.band(g.NextItemData.HasFlags, bit32.bnot(ImGuiNextItemDataFlags.HasWidth)) end @@ -5280,7 +6659,7 @@ function ImGui.PushMultiItemsWidths(components, w_full) local window = g.CurrentWindow IM_ASSERT(components > 0) local style = g.Style - window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) + window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) -- Backup current width local w_items = w_full - style.ItemInnerSpacing.x * (components - 1) local prev_split = w_items for i = components - 1, 1, -1 do @@ -5328,10 +6707,12 @@ end function ImGui.SetCursorScreenPos(pos) local window = ImGui.GetCurrentWindow() ImVec2_Copy(window.DC.CursorPos, pos) + -- window.DC.CursorMaxPos = ImMax(window.DC.CursorMaxPos, window.DC.CursorPos) window.DC.IsSetPos = true end --- [window-local] cursor position, in window coordinates (relative to window position, including scrolling) +-- User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. +-- Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. --- @return ImVec2 function ImGui.GetCursorPos() local window = ImGui.GetCurrentWindowRead() @@ -5352,6 +6733,7 @@ end function ImGui.SetCursorPos(local_pos) local window = ImGui.GetCurrentWindow() ImVec2_CopyV(window.DC.CursorPos, window.Pos.x - window.Scroll.x + local_pos.x, window.Pos.y - window.Scroll.y + local_pos.y) + -- window.DC.CursorMaxPos = ImMax(window.DC.CursorMaxPos, window.DC.CursorPos) window.DC.IsSetPos = true end @@ -5359,6 +6741,7 @@ end function ImGui.SetCursorPosX(x) local window = ImGui.GetCurrentWindow() window.DC.CursorPos.x = window.Pos.x - window.Scroll.x + x + -- window.DC.CursorMaxPos.x = ImMax(window.DC.CursorMaxPos.x, window.DC.CursorPos.x) window.DC.IsSetPos = true end @@ -5366,6 +6749,7 @@ end function ImGui.SetCursorPosY(y) local window = ImGui.GetCurrentWindow() window.DC.CursorPos.y = window.Pos.y - window.Scroll.y + y + -- window.DC.CursorMaxPos.y = ImMax(window.DC.CursorMaxPos.y, window.DC.CursorPos.y) window.DC.IsSetPos = true end @@ -5385,6 +6769,8 @@ function ImGui.GetTextLineHeightWithSpacing() return g.FontSize + g.Style.ItemSpacing.y end +-- You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()! +-- They are bizarre local-coordinates which don't play well with scrolling. --- @return ImVec2 function ImGui.GetContentRegionMax() local window = GImGui.CurrentWindow @@ -5443,7 +6829,7 @@ function ImGui.BeginGroup() ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorPos) ImVec2_CopyV(window.DC.CurrLineSize, 0.0, 0.0) if (g.LogEnabled) then - g.LogLinePosY = -FLT_MAX + g.LogLinePosY = -FLT_MAX -- To enforce a carriage return end end @@ -5460,6 +6846,7 @@ function ImGui.EndGroup() -- TODO: ImGui.ErrorCheckUsingSetCursorPosToExtendParentBoundaries() end + -- Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543) local group_bb = ImRect(group_data.BackupCursorPos, ImMax(ImMax(window.DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos)) ImVec2_Copy(window.DC.CursorPos, group_data.BackupCursorPos) ImVec2_Copy(window.DC.CursorPosPrevLine, group_data.BackupCursorPosPrevLine) @@ -5478,7 +6865,7 @@ function ImGui.EndGroup() return end - window.DC.CurrLineTextBaseOffset = ImMax(window.DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset) -- FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now + window.DC.CurrLineTextBaseOffset = ImMax(window.DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset) -- FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. ImGui.ItemSize(group_bb:GetSize()) ImGui.ItemAdd(group_bb, 0, nil, ImGuiItemFlags.NoTabStop) @@ -5518,6 +6905,8 @@ function ImGui.EndGroup() end end +-- Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(). +-- The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags() @native function ImGui.CalcItemWidth() local g = GImGui @@ -5539,6 +6928,10 @@ function ImGui.CalcItemWidth() return w end +-- [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth(). +-- Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. +-- Note that only CalcItemWidth() is publicly exposed. +-- The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) --- @param size ImVec2 --- @param default_w float --- @param default_h float @@ -5552,13 +6945,13 @@ function ImGui.CalcItemSize(size, default_w, default_h) if size.x == 0.0 then size.x = default_w elseif size.x < 0.0 then - size.x = ImMax(4.0, avail.x + size.x) -- size.x is negative here so we are subtracting + size.x = ImMax(4.0, avail.x + size.x) -- <-- size.x is negative here so we are subtracting end if size.y == 0.0 then size.y = default_h elseif size.y < 0.0 then - size.y = ImMax(4.0, avail.y + size.y) -- size.y is negative here so we are subtracting + size.y = ImMax(4.0, avail.y + size.y) -- <-- size.y is negative here so we are subtracting end return size @@ -5579,12 +6972,15 @@ function ImGui.IsItemActive() return false end +-- == (GetItemID() == GetFocusID() && GetFocusID() != 0) function ImGui.IsItemFocused() local g = GImGui if g.NavId ~= g.LastItemData.ID or g.NavId == 0 then return false end + -- Special handling for the dummy item after Begin() which represent the title bar or tab. + -- When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. local window = g.CurrentWindow if g.LastItemData.ID == window.ID and window.WriteAccessed then return false @@ -5601,6 +6997,7 @@ function ImGui.IsItemDeactivated() return g.DeactivatedItemData.ID == g.LastItemData.ID and g.LastItemData.ID ~= 0 and g.DeactivatedItemData.ElapseFrame >= g.FrameCount end +-- Since 1.92.9: consider using NoLiveEdit flags if all you need to that values are not written bo backing variable while typing. function ImGui.IsItemDeactivatedAfterEdit() local g = GImGui return ImGui.IsItemDeactivated() and g.DeactivatedItemData.HasBeenEditedBefore @@ -5617,6 +7014,7 @@ function ImGui.IsItemActivated() end -- Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()! +-- Most widgets have specific reactions based on mouse-up/down state, mouse position etc. --- @param mouse_button? ImGuiMouseButton function ImGui.IsItemClicked(mouse_button) if mouse_button == nil then mouse_button = 0 end @@ -5627,12 +7025,21 @@ function ImGui.IsItemToggledOpen() return bit32.band(GImGui.LastItemData.StatusFlags, ImGuiItemStatusFlags.ToggledOpen) ~= 0 end +-- Call after a Selectable() or TreeNode() items inside a BeginMultiSelect()/EndMultiSelect() scope. +-- - Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose. +-- Outside of a multi-select block: +-- - It would be misleading/ambiguous to report this signal, as widgets return e.g. a pressed event, +-- and user code is in charge of altering selection in ways we cannot predict. +-- Prefer using 'if (IsItemClicked() && !IsItemToggledOpen())' for a manual reimplementation of selection. function ImGui.IsItemToggledSelection() local g = GImGui IM_ASSERT(g.CurrentMultiSelect ~= nil) -- Can only be used inside a BeginMultiSelect()/EndMultiSelect() return bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.ToggledSelection) ~= 0 end +-- IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, +-- you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! +-- Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. function ImGui.IsAnyItemHovered() local g = GImGui return g.HoveredId ~= 0 or g.HoveredIdPreviousFrame ~= 0 @@ -5656,6 +7063,8 @@ function ImGui.IsItemEdited() end -- Allow next item to be overlapped by subsequent items. +-- This works by requiring HoveredId to match for two subsequent frames, +-- so if a following items overwrite it our interactions will naturally be disabled. function ImGui.SetNextItemAllowOverlap() local g = GImGui g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.AllowOverlap) @@ -5679,10 +7088,23 @@ function ImGui.GetHoveredID() return (g.HoveredId ~= 0) and g.HoveredId or g.HoveredIdPreviousFrame end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] WINDOW FOCUS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - SetWindowFocus() +-- - SetNextWindowFocus() +-- - IsWindowFocused() +-- - UpdateWindowInFocusOrderList() [Internal] +-- - BringWindowToFocusFront() [Internal] +-- - BringWindowToDisplayFront() [Internal] +-- - BringWindowToDisplayBack() [Internal] +-- - BringWindowToDisplayBehind() [Internal] +-- - FindWindowDisplayIndex() [Internal] +-- - FocusWindow() [Internal] +-- - FocusTopMostWindowUnderOne() [Internal] +------------------------------------------------------------------------------- +-- Moving window to front of display and set focus (which happens to be back of our sorted list) --- @param window? ImGuiWindow --- @param flags? ImGuiFocusRequestFlags function ImGui.FocusWindow(window, flags) @@ -5690,28 +7112,34 @@ function ImGui.FocusWindow(window, flags) local g = GImGui - if bit32.band(flags, ImGuiFocusRequestFlags.UnlessBelowModal) ~= 0 and g.NavWindow ~= window then + -- Modal check? + if bit32.band(flags, ImGuiFocusRequestFlags.UnlessBelowModal) ~= 0 and g.NavWindow ~= window then -- Early out in common case. local blocking_modal = ImGui.FindBlockingModal(window) if blocking_modal then + -- 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 == nil) -- IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".", window ? window->Name : "", blocking_modal->Name) if window and window == window.RootWindow and bit32.band(window.Flags, ImGuiWindowFlags.NoBringToFrontOnFocus) == 0 then - ImGui.BringWindowToDisplayBehind(window, blocking_modal) + ImGui.BringWindowToDisplayBehind(window, blocking_modal) -- Still bring right under modal. (FIXME: Could move in focus list too?) end - ImGui.ClosePopupsOverWindow(ImGui.GetTopMostPopupModal(), false) + ImGui.ClosePopupsOverWindow(ImGui.GetTopMostPopupModal(), false) -- Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals return end end + -- Find last focused child (if any) and focus it instead. if bit32.band(flags, ImGuiFocusRequestFlags.RestoreFocusedChild) ~= 0 and window ~= nil then window = ImGui.NavRestoreLastChildNavWindow(window) end + -- Apply focus if g.NavWindow ~= window then ImGui.SetNavWindow(window) if window and g.NavHighlightItemUnderNav then g.NavMousePosDirty = true end - g.NavId = window and window.NavLastIds[0] or 0 + g.NavId = window and window.NavLastIds[0] or 0 -- Restore NavId g.NavLayer = ImGuiNavLayer.Main ImGui.SetNavFocusScope(window and window.NavRootFocusScopeId or 0) g.NavIdIsAlive = false @@ -5721,23 +7149,35 @@ function ImGui.FocusWindow(window, flags) ImGui.ClosePopupsOverWindow(window, false) end + -- Move the root window to the top of the pile IM_ASSERT(window == nil or window.RootWindowDockTree ~= nil) local focus_front_window = window and window.RootWindow or nil local display_front_window = window and window.RootWindowDockTree or nil local dock_node = window and window.DockNode or nil local active_id_window_is_dock_node_host = g.ActiveIdWindow and dock_node and 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 and g.ActiveIdWindow and g.ActiveIdWindow.RootWindow ~= focus_front_window then if not g.ActiveIdNoClearOnFocusLoss and not active_id_window_is_dock_node_host then ImGui.ClearActiveID() end end + -- Passing nil allow to disable keyboard focus if not window then return end 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 ImGui.BringWindowToFocusFront(focus_front_window) if bit32.band(bit32.bor(window.Flags, focus_front_window.Flags, display_front_window.Flags), ImGuiWindowFlags.NoBringToFrontOnFocus) == 0 then ImGui.BringWindowToDisplayFront(display_front_window) @@ -5755,6 +7195,9 @@ function ImGui.FindWindowFocusIndex(window) return order end +-- 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. --- @param window ImGuiWindow --- @return bool function ImGui.IsWindowNavFocusable(window) @@ -5765,7 +7208,7 @@ end --- @param i_stop int --- @param dir int --- @return ImGuiWindow? -function ImGui.FindWindowNavFocusable(i_start, i_stop, dir) +function ImGui.FindWindowNavFocusable(i_start, i_stop, dir) -- FIXME-OPT O(N) local g = GImGui local i = i_start while i >= 1 and i <= g.WindowsFocusOrder.Size and i ~= i_stop do @@ -5826,13 +7269,15 @@ function ImGui.BringWindowToFocusFront(window) window.FocusOrder = new_order end +-- Note technically focus related but rather adjacent and close to BringWindowToFocusFront() +-- FIXME-FOCUS: Could opt-in/opt-out enable modal check like in FocusWindow(). --- @param window? ImGuiWindow function ImGui.BringWindowToDisplayFront(window) local g = GImGui local current_front_window = g.Windows:back() - if current_front_window == window or current_front_window.RootWindowDockTree == window then + if current_front_window == window or current_front_window.RootWindowDockTree == window then -- Cheap early out (could be better) return end @@ -5875,6 +7320,7 @@ function ImGui.FocusTopMostWindowUnderOne(under_this_window, ignore_window, filt end for i = start_idx, 1, -1 do repeat + -- 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. local window = g.WindowsFocusOrder.Data[i] if window == ignore_window or not window.WasActive then break @@ -5883,6 +7329,11 @@ function ImGui.FocusTopMostWindowUnderOne(under_this_window, ignore_window, filt break end if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs)) ~= bit32.bor(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs) then + -- 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? ImGui.FocusWindow(window, flags) return end @@ -5902,6 +7353,8 @@ function ImGui.SetFocusID(id, window) ImGui.SetNavWindow(window) end + -- Assume that SetFocusID() is called in the context where its window.DC.NavLayerCurrent and g.CurrentFocusScopeId are valid. + -- Note that window may be ~= g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text) local nav_layer = window.DC.NavLayerCurrent g.NavId = id g.NavLayer = nav_layer @@ -5921,23 +7374,33 @@ function ImGui.SetFocusID(id, window) g.NavCursorVisible = false end + -- Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y) end +-- This is not 100% symmetric 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). function ImGui.StopMouseMovingWindow() local g = GImGui local window = g.MovingWindow + -- Ref commits 6b7766817, 36055213c for some partial history on checking if viewport ~= nil. if window and window.Viewport then + -- 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 bit32.band(g.ConfigFlagsCurrFrame, ImGuiConfigFlags.ViewportsEnable) ~= 0 then ImGui.UpdateTryMergeWindowIntoHostViewport(window.RootWindowDockTree, g.MouseViewport) end + -- 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 (not ImGui.IsDragDropPayloadBeingAccepted()) then g.MouseViewport = window.Viewport end + -- Clear the NoInputs window flag set by the Viewport system in AddUpdateViewport() local window_can_use_inputs = bit32.band(window.Flags, ImGuiWindowFlags.NoMouseInputs) == 0 or bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) == 0 if window_can_use_inputs then window.Viewport.Flags = bit32.band(window.Viewport.Flags, bit32.bnot(ImGuiViewportFlags.NoInputs)) @@ -5952,23 +7415,32 @@ end function ImGui.SetActiveID(id, window) local g = GImGui + -- Clear previous active id if g.ActiveId ~= 0 then + -- Store deactivate data local deactivated_data = g.DeactivatedItemData deactivated_data.ID = g.ActiveId deactivated_data.ElapseFrame = (g.LastItemData.ID == g.ActiveId) and g.FrameCount or 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 then ImGui.InputTextDeactivateHook(g.ActiveId) end + -- 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 and (g.ActiveId == g.MovingWindow.MoveId) then print("SetActiveID() cancel MovingWindow") ImGui.StopMouseMovingWindow() end end + -- Set active id g.ActiveIdIsJustActivated = (g.ActiveId ~= id) if (g.ActiveIdIsJustActivated) then -- IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() 0x%08X in \"%s\"%*s(previously 0x%08X in \"%s\")\n", id, window ? window->Name : "", @@ -6000,14 +7472,20 @@ function ImGui.SetActiveID(id, window) IM_ASSERT(g.ActiveIdSource ~= ImGuiInputSource.None) end + -- Clear declaration of inputs claimed by the widget + -- (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet) g.ActiveIdUsingNavDirMask = 0x00 g.ActiveIdUsingAllKeyboardKeys = false end function ImGui.ClearActiveID() - ImGui.SetActiveID(0, nil) + ImGui.SetActiveID(0, nil) -- g.ActiveId = 0 end +------------------------------------------------------------------------------- +-- [SECTION] ID STACK +------------------------------------------------------------------------------- + --- @param str_id string|int @native function ImGui.PushID(str_id) @@ -6017,6 +7495,7 @@ function ImGui.PushID(str_id) window.IDStack:push_back(id) end +-- Push a given id value ignoring the ID stack as a seed. --- @param id ImGuiID function ImGui.PushOverrideID(id) local g = GImGui @@ -6034,6 +7513,8 @@ function ImGui.PopID() window.IDStack:pop_back() end +-- This is one of the very rare legacy case where we use ImGuiWindow methods, +-- it should ideally be flattened at some point but it's been used a lots by widgets. --- @param id string|int --- @return ImGuiID @native @@ -6053,7 +7534,7 @@ function MT.ImGuiWindow:GetID(id) return h end --- This is only used in rare/specific situations to manufacture an ID out of nowhere +-- This is only used in rare/specific situations to manufacture an ID out of nowhere. -- FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those? --- @param p_abs ImVec2 --- @return ImGuiID @@ -6084,6 +7565,9 @@ function ImGui.GetID(str_or_int, str_end) return window:GetID(str_or_int) end +-- Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call +-- (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level. +-- for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more) -- Overloads: GetIDWithSeed(str, str_end, seed) / GetIDWithSeed(n, seed) function ImGui.GetIDWithSeed(a, b, c) local id @@ -6126,6 +7610,7 @@ end --- @param user_flags ImGuiHoveredFlags --- @param shared_flags ImGuiHoveredFlags local function ApplyHoverFlagsForTooltip(user_flags, shared_flags) + -- Allow instance flags to override shared flags if bit32.band(user_flags, bit32.bor(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.DelayNormal)) ~= 0 then shared_flags = bit32.band(shared_flags, bit32.bnot(bit32.bor(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.DelayNormal))) end @@ -6138,6 +7623,7 @@ function ImGui.MarkItemEdited(id) -- ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data. local g = GImGui + -- IM_ASSERT(g.LastItemData.ID == id) -- Failing cases include: "widgets_inputtext_scrolling", "widgets_inputtext_multiline_status", "widgets_selectable_input" = case of e.g TempInputText() overlayed manually with different ID (#2718) g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal) if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited) ~= 0 then return @@ -6200,6 +7686,9 @@ function ImGui.IsWindowContentHoverable(window, flags) return true end +-- This is roughly matching the behavior of internal-facing ItemHoverable() +-- - we allow hovering to be true when ActiveId==window.MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() +-- - this should work even for non-interactive items that have no ID, so we cannot use LastItemId --- @param flags? ImGuiHoveredFlags @native function ImGui.IsItemHovered(flags) @@ -6221,6 +7710,7 @@ function ImGui.IsItemHovered(flags) flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav) end else + -- Test for bounding box overlap, as updated as ItemAdd() local status_flags = g.LastItemData.StatusFlags if bit32.band(status_flags, ImGuiItemStatusFlags.HoveredRect) == 0 then return false @@ -6230,19 +7720,31 @@ function ImGui.IsItemHovered(flags) flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse) end + -- Done with rectangle culling so we can perform heavier checks now + -- Test if we are hovering the right window (our window could be behind another window) + -- [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851) + -- [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable + -- to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was + -- the test that has been running for a long while. if g.HoveredWindow ~= window and bit32.band(status_flags, ImGuiItemStatusFlags.HoveredWindow) == 0 then if bit32.band(flags, ImGuiHoveredFlags.AllowWhenOverlappedByWindow) == 0 then return false end end + -- Test if another item is active (e.g. being dragged) local id = g.LastItemData.ID if bit32.band(flags, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) == 0 then if g.ActiveId ~= 0 and g.ActiveId ~= id and not g.ActiveIdAllowOverlap and not g.ActiveIdFromShortcut then + -- 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. local cancel_is_hovered = true if g.ActiveId == window.MoveId and (id == 0 or g.ActiveIdDisabledId == id) then cancel_is_hovered = false end + -- When ActiveId == TabId it means user clicked docking tab for the window. if g.ActiveId == window.TabId then cancel_is_hovered = false end @@ -6252,18 +7754,25 @@ function ImGui.IsItemHovered(flags) end end + -- Test if interactions on this window are blocked by an active popup or modal. + -- The ImGuiHoveredFlags.AllowWhenBlockedByPopup flag will be tested here. if not ImGui.IsWindowContentHoverable(window, flags) and bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoWindowHoverableCheck) == 0 then return false end + -- Test if the item is disabled if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.Disabled) ~= 0 and bit32.band(flags, ImGuiHoveredFlags.AllowWhenDisabled) == 0 then return false end + -- Special handling for calling after Begin() which represent the title bar or tab. + -- When the window is skipped/collapsed (SkipItems==true) that last item (always .MoveId submitted by Begin) + -- will never be overwritten so we need to detect the case. if id == window.MoveId and window.WriteAccessed then return false end + -- Test if using AllowOverlap and overlapped if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowOverlap) ~= 0 and id ~= 0 then if bit32.band(flags, ImGuiHoveredFlags.AllowWhenOverlappedByItem) == 0 then if g.HoveredIdPreviousFrame ~= g.LastItemData.ID then @@ -6273,6 +7782,8 @@ function ImGui.IsItemHovered(flags) end end + -- Handle hover delay + -- (some ideas: https://www.nngroup.com/articles/timing-exposing-content) local delay = CalcDelayFromHoveredFlags(flags) if delay > 0.0 or bit32.band(flags, ImGuiHoveredFlags.Stationary) ~= 0 then local hover_delay_id @@ -6286,6 +7797,9 @@ function ImGui.IsItemHovered(flags) end g.HoverItemDelayId = hover_delay_id + -- When changing hovered item we requires a bit of stationary delay before activating hover timer, + -- but once unlocked on a given item we also moving. + -- if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); } if bit32.band(flags, ImGuiHoveredFlags.Stationary) ~= 0 and g.HoverItemUnlockedStationaryId ~= hover_delay_id then return false end @@ -6298,6 +7812,13 @@ function ImGui.IsItemHovered(flags) return true end +-- 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: +-- - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'. +-- - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags.None) unless you want to benefit from special behavior handled by ItemHoverable. --- @param bb ImRect --- @param id ImGuiID --- @param item_flags ImGuiItemFlags @@ -6306,6 +7827,8 @@ function ImGui.ItemHoverable(bb, id, item_flags) local g = GImGui local 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) if not IMGUI_DISABLE_DEBUG_TOOLS then if id ~= 0 and g.HoveredIdPreviousFrame == id and bit32.band(item_flags, ImGuiItemFlags.AllowDuplicateId) == 0 then g.HoveredIdPreviousFrameItemCount = g.HoveredIdPreviousFrameItemCount + 1 @@ -6333,18 +7856,24 @@ end end end + -- We are done with rectangle culling so we can perform heavier checks now. if (bit32.band(item_flags, ImGuiItemFlags.NoWindowHoverableCheck) == 0) and not ImGui.IsWindowContentHoverable(window, ImGuiHoveredFlags.None) then g.HoveredIdIsDisabled = true return false end + -- We exceptionally allow this function to be called with id==0 to allow using it for easy high-level + -- hover test in widgets code. We could also decide to split this function is two. if id ~= 0 then + -- Drag source doesn't report as hovered if g.DragDropActive and g.DragDropPayload.SourceId == id and (bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceNoDisableHover) == 0) then return false end ImGui.SetHoveredID(id) + -- AllowOverlap mode (rarely used) requires previous frame HoveredId to be nil or to match. + -- This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test. if bit32.band(item_flags, ImGuiItemFlags.AllowOverlap) ~= 0 then g.HoveredIdAllowOverlap = true if g.HoveredIdPreviousFrame ~= id then @@ -6352,6 +7881,8 @@ end end end + -- Display shortcut (only works with mouse) + -- (ImGuiItemStatusFlags.HasShortcut in LastItemData denotes we want a tooltip) if id == g.LastItemData.ID and (bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasShortcut) ~= 0) and g.ActiveId ~= id then if ImGui.IsItemHovered(bit32.bor(ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.DelayNormal)) then ImGui.SetTooltip("%s", ImGui.GetKeyChordName(g.LastItemData.Shortcut)) @@ -6359,6 +7890,7 @@ end end end + -- When disabled we'll return false but still set HoveredId if bit32.band(item_flags, ImGuiItemFlags.Disabled) ~= 0 then -- Release active id if turning disabled if g.ActiveId == id and id ~= 0 then @@ -6375,6 +7907,8 @@ end return true end +-- FIXME: This is inlined/duplicated in ItemAdd() +-- FIXME: The id ~= 0 path is not used by our codebase, may get rid of it? --- @param bb ImRect --- @param id ImGuiID --- @return bool @@ -6391,6 +7925,8 @@ function ImGui.IsClippedEx(bb, id) return false end +-- This is also inlined in ItemAdd() +-- Note: if ImGuiItemStatusFlags.HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect. --- @param item_id ImGuiID --- @param item_flags ImGuiItemFlags --- @param status_flags ImGuiItemStatusFlags @@ -6415,6 +7951,10 @@ function ImGui.SetLastItemDataForWindow(window, rect) end end +-- Pass in translated ASCII characters for text input. +-- - with glfw you can get those from the callback set in glfwSetCharCallback() +-- - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message +-- FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API --- @param c unsigned_int function MT.ImGuiIO:AddInputCharacter(c) IM_ASSERT(self.Ctx ~= nil) @@ -6434,6 +7974,8 @@ function MT.ImGuiIO:AddInputCharacter(c) g.InputEventsQueue:push_back(e) end +-- UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so +-- we should save the high surrogate. --- @param c ImWchar16 function MT.ImGuiIO:AddInputCharacterUTF16(c) if (c == 0 and self.InputQueueSurrogate == 0) or not self.AppAcceptingEvents then @@ -6450,11 +7992,11 @@ function MT.ImGuiIO:AddInputCharacterUTF16(c) local cp = c if self.InputQueueSurrogate ~= 0 then - if bit32.band(c, 0xFC00) ~= 0xDC00 then -- Invalid low surrogate + if bit32.band(c, 0xFC00) ~= 0xDC00 then -- Invalid low surrogate self:AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID) else -- #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF - cp = IM_UNICODE_CODEPOINT_INVALID + cp = IM_UNICODE_CODEPOINT_INVALID -- Codepoint will not fit in ImWchar -- #endif end @@ -6463,12 +8005,14 @@ function MT.ImGuiIO:AddInputCharacterUTF16(c) self:AddInputCharacter(cp) end +-- Clear all incoming events. function MT.ImGuiIO:ClearEventsQueue() IM_ASSERT(self.Ctx ~= nil) local g = GImGui g.InputEventsQueue:clear() end +-- Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. function MT.ImGuiIO:ClearInputKeys() local g = self.Ctx for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do @@ -6484,7 +8028,7 @@ function MT.ImGuiIO:ClearInputKeys() self.KeyAlt = false self.KeySuper = false self.KeyMods = ImGuiMod_None - self.InputQueueCharacters:resize(0) + self.InputQueueCharacters:resize(0) -- Behavior of old ClearInputCharacters(). end function MT.ImGuiIO:ClearInputMouse() @@ -6531,18 +8075,25 @@ function MT.ImGuiIO:FindLatestInputEvent(ctx, type, arg) return nil end +-- Queue a new key down/up event. +-- - ImGuiKey key: Translated key (as in, generally ImGuiKey.A matches the key end-user would use to emit an 'A' character) +-- - bool down: Is the key down? use false to signify a key release. +-- - float analog_value: 0.0f..1.0f +-- IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE. +-- WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT. --- @param key ImGuiKey --- @param down bool --- @param analog_value float function MT.ImGuiIO:AddKeyAnalogEvent(key, down, analog_value) + -- if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); } IM_ASSERT(self.Ctx ~= nil) if key == ImGuiKey.None or not self.AppAcceptingEvents then return end local g = self.Ctx - IM_ASSERT(ImGui.IsNamedKeyOrMod(key)) - IM_ASSERT(ImGui.IsAliasKey(key) == false) + IM_ASSERT(ImGui.IsNamedKeyOrMod(key)) -- Backend needs to pass a valid ImGuiKey constant. 0..511 values are legacy native key codes which are not accepted by this API. + IM_ASSERT(ImGui.IsAliasKey(key) == false) -- Backend cannot submit ImGuiKey.MouseXXX values they are automatically inferred from AddMouseXXX() events. -- MacOS: swap Cmd(Super) and Ctrl if (g.IO.ConfigMacOSXBehaviors) then @@ -6555,6 +8106,7 @@ function MT.ImGuiIO:AddKeyAnalogEvent(key, down, analog_value) end end + -- Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed) local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.Key, key) local key_data = ImGui.GetKeyData(g, key) local latest_key_down = latest_event and latest_event.Key.Down or key_data.Down @@ -6563,6 +8115,7 @@ function MT.ImGuiIO:AddKeyAnalogEvent(key, down, analog_value) return end + -- Add event local e = ImGuiInputEvent() e.Type = ImGuiInputEventType.Key e.Source = ImGui.IsGamepadKey(key) and ImGuiInputSource.Gamepad or ImGuiInputSource.Keyboard @@ -6584,11 +8137,14 @@ function MT.ImGuiIO:AddKeyEvent(key, down) self:AddKeyAnalogEvent(key, down, (down and 1.0 or 0.0)) end +-- 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. --- @param accepting_events bool function MT.ImGuiIO:SetAppAcceptingEvents(accepting_events) self.AppAcceptingEvents = accepting_events end +-- This is not a real event, the data is latched in order to be stored in actual Mouse events. +-- This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes. --- @param source ImGuiMouseSource function MT.ImGuiIO:AddMouseSourceEvent(source) IM_ASSERT(self.Ctx ~= nil) @@ -6600,7 +8156,7 @@ end function MT.ImGuiIO:AddMouseViewportEvent(viewport_id) IM_ASSERT(self.Ctx ~= nil) local g = self.Ctx - -- IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags.HasMouseHoveredViewport); + -- IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags.HasMouseHoveredViewport) if (not self.AppAcceptingEvents) then return end @@ -6630,6 +8186,7 @@ function MT.ImGuiIO:AddFocusEvent(focused) IM_ASSERT(self.Ctx ~= nil) local g = self.Ctx + -- Filter duplicate local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.Focus) local latest_focused = latest_event and latest_event.AppFocused.Focused or (not g.IO.AppFocusLost) if latest_focused == focused or (self.ConfigDebugIgnoreFocusLoss and not focused) then @@ -6645,6 +8202,7 @@ function MT.ImGuiIO:AddFocusEvent(focused) g.InputEventsQueue:push_back(e) end +-- Queue a mouse move event --- @param x float --- @param y float function MT.ImGuiIO:AddMousePosEvent(x, y) @@ -6655,6 +8213,7 @@ function MT.ImGuiIO:AddMousePosEvent(x, y) local g = self.Ctx + -- Apply same flooring as UpdateMouseInputs() local x_val = x if x > -FLT_MAX then x_val = ImFloor(x) @@ -6664,6 +8223,7 @@ function MT.ImGuiIO:AddMousePosEvent(x, y) y_val = ImFloor(y) end + -- Filter duplicate local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.MousePos) local latest_pos = latest_event and ImVec2(latest_event.MousePos.PosX, latest_event.MousePos.PosY) or self.MousePos if latest_pos.x == x_val and latest_pos.y == y_val then @@ -6701,6 +8261,7 @@ function MT.ImGuiIO:AddMouseButtonEvent(mouse_button, down) end end + -- Filter duplicate local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.MouseButton, mouse_button) local latest_button_down = latest_event and latest_event.MouseButton.Down or self.MouseDown[mouse_button] if latest_button_down == down then @@ -6732,11 +8293,13 @@ function MT.ImGuiIO:AddMouseButtonEvent(mouse_button, down) g.InputEventsQueue:push_back(e) end +-- Queue a mouse wheel event (some mouse/API may only have a Y component) --- @param wheel_x float --- @param wheel_y float function MT.ImGuiIO:AddMouseWheelEvent(wheel_x, wheel_y) IM_ASSERT(self.Ctx ~= nil) local g = self.Ctx + -- Filter duplicate (unlike most events, wheel values are relative and easy to filter) if not self.AppAcceptingEvents or (wheel_x == 0 and wheel_y == 0) then return end @@ -6753,6 +8316,73 @@ function MT.ImGuiIO:AddMouseWheelEvent(wheel_x, wheel_y) g.InputEventsQueue:push_back(e) end +------------------------------------------------------------------------------- +-- [SECTION] INPUTS +------------------------------------------------------------------------------- +-- - GetModForLRModKey() [Internal] +-- - FixupKeyChord() [Internal] +-- - GetKeyData() [Internal] +-- - GetKeyIndex() [Internal] +-- - GetKeyName() +-- - GetKeyChordName() [Internal] +-- - CalcTypematicRepeatAmount() [Internal] +-- - GetTypematicRepeatRate() [Internal] +-- - GetKeyPressedAmount() [Internal] +-- - GetKeyMagnitude2d() [Internal] +------------------------------------------------------------------------------- +-- - UpdateKeyRoutingTable() [Internal] +-- - GetRoutingIdFromOwnerId() [Internal] +-- - GetShortcutRoutingData() [Internal] +-- - CalcRoutingScore() [Internal] +-- - SetShortcutRouting() [Internal] +-- - TestShortcutRouting() [Internal] +------------------------------------------------------------------------------- +-- - IsKeyDown() +-- - IsKeyPressed() +-- - IsKeyReleased() +------------------------------------------------------------------------------- +-- - IsMouseDown() +-- - IsMouseClicked() +-- - IsMouseReleased() +-- - IsMouseDoubleClicked() +-- - GetMouseClickedCount() +-- - GetItemClickedCountWithSingleClickDelay() +-- - IsMouseHoveringRect() [Internal] +-- - IsMouseDragPastThreshold() [Internal] +-- - IsMouseDragging() +-- - GetMousePos() +-- - SetMousePos() [Internal] +-- - GetMousePosOnOpeningCurrentPopup() +-- - IsMousePosValid() +-- - IsAnyMouseDown() +-- - GetMouseDragDelta() +-- - ResetMouseDragDelta() +-- - GetMouseCursor() +-- - SetMouseCursor() +------------------------------------------------------------------------------- +-- - UpdateAliasKey() +-- - GetMergedModsFromKeys() +-- - UpdateKeyboardInputs() +-- - UpdateMouseInputs() +------------------------------------------------------------------------------- +-- - LockWheelingWindow [Internal] +-- - FindBestWheelingWindow [Internal] +-- - UpdateMouseWheel() [Internal] +------------------------------------------------------------------------------- +-- - SetNextFrameWantCaptureKeyboard() +-- - SetNextFrameWantCaptureMouse() +------------------------------------------------------------------------------- +-- - GetInputSourceName() [Internal] +-- - DebugPrintInputEvent() [Internal] +-- - UpdateInputEvents() [Internal] +------------------------------------------------------------------------------- +-- - GetKeyOwner() [Internal] +-- - TestKeyOwner() [Internal] +-- - SetKeyOwner() [Internal] +-- - SetItemKeyOwner() [Internal] +-- - Shortcut() [Internal] +------------------------------------------------------------------------------- + --- @param key ImGuiKey local function GetModForLRModKey(key) if key == ImGuiKey.LeftCtrl or key == ImGuiKey.RightCtrl then @@ -6772,6 +8402,7 @@ end --- @param key_chord ImGuiKeyChord function ImGui.FixupKeyChord(key_chord) + -- Add ImGuiMod_XXXX when a corresponding ImGuiKey.LeftXXX/ImGuiKey.RightXXX is specified. local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if ImGui.IsLRModKey(key) then key_chord = bit32.bor(key_chord, GetModForLRModKey(key)) @@ -6785,6 +8416,7 @@ end function ImGui.GetKeyData(ctx, key) if ctx == nil then ctx = GImGui end + -- Special storage location for mods if bit32.band(key, ImGuiMod_Mask_) ~= 0 then key = ImGui.ConvertSingleModFlagToKey(key) end @@ -6794,6 +8426,7 @@ function ImGui.GetKeyData(ctx, key) return ctx.IO.KeysData[idx], idx end +-- Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey.GamepadLStick* values). --- @param key_left ImGuiKey --- @param key_right ImGuiKey --- @param key_up ImGuiKey @@ -6805,6 +8438,10 @@ function ImGui.GetKeyMagnitude2d(key_left, key_right, key_up, key_down) ) end +-- TestKeyOwner(..., ID) : (owner == None || owner == ID) +-- TestKeyOwner(..., None) : (owner == None) +-- TestKeyOwner(..., Any) : no owner test +-- All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags.LockXXX flags. --- @param key ImGuiKey --- @param owner_id ImGuiID function ImGui.TestKeyOwner(key, owner_id) @@ -6824,6 +8461,9 @@ function ImGui.TestKeyOwner(key, owner_id) return not owner_data.LockThisFrame end + -- Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId + -- are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things. + -- Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions. if owner_data.OwnerCurr ~= owner_id then if owner_data.LockThisFrame then return false @@ -6836,6 +8476,8 @@ function ImGui.TestKeyOwner(key, owner_id) return true end +-- Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes. +-- Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey.A) (>= 1.87) --- @param key ImGuiKey --- @param owner_id? ImGuiID function ImGui.IsKeyDown(key, owner_id) @@ -6875,6 +8517,7 @@ function ImGui.IsKeyReleased(key, owner_id) return true end +-- Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat. --- @param key ImGuiKey --- @param flags ImGuiInputFlags --- @param owner_id? ImGuiID @@ -6884,8 +8527,7 @@ function ImGui.IsKeyPressedEx(key, flags, owner_id) local g = GImGui local key_data = ImGui.GetKeyData(g, key) - -- In theory this should already be encoded as (DownDuration < 0.0), but testing this facilitates eating mechanism (until we finish work on key ownership) - if not key_data.Down then + if not key_data.Down then -- In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership) return false end local t = key_data.DownDuration @@ -6928,6 +8570,7 @@ function ImGui.IsKeyPressedEx(key, flags, owner_id) end -- TODO: +-- Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super. function ImGui.GetKeyChordName(key_chord) local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if ImGui.IsLRModKey(key) then @@ -6944,6 +8587,7 @@ function ImGui.GetKeyChordName(key_chord) return s end +-- Those names are provided for debugging purpose and are not meant to be saved persistently nor compared. local GKeyNames = { "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown", "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape", @@ -7004,6 +8648,10 @@ function ImGui.GetKeyOwner(key) return owner_id end +-- t0 = previous time (e.g.: g.Time - g.IO.DeltaTime) +-- t1 = current time (e.g.: g.Time) +-- An event is triggered at: +-- t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N --- @param t0 float --- @param t1 float --- @param repeat_delay float @@ -7047,6 +8695,8 @@ function ImGui.GetTypematicRepeatRate(flags) else repeat_delay = g.IO.KeyRepeatDelay * 1.00; repeat_rate = g.IO.KeyRepeatRate * 1.00; return repeat_delay, repeat_rate end end +-- Return value representing the number of presses in the last time period, for the given repeat rate +-- (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate) --- @param key ImGuiKey --- @param repeat_delay float --- @param repeat_rate float @@ -7060,6 +8710,10 @@ function ImGui.GetKeyPressedAmount(key, repeat_delay, repeat_rate) return ImGui.CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate) end +-- Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data. +-- Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D +-- Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6 +-- See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation. --- @param rt ImGuiKeyRoutingTable function ImGui.UpdateKeyRoutingTable(rt) local g = GImGui --[[@as ImGuiContext]] @@ -7072,19 +8726,22 @@ function ImGui.UpdateKeyRoutingTable(rt) repeat routing_entry = rt.Entries[old_routing_idx] routing_entry.RoutingCurrScore = routing_entry.RoutingNextScore - routing_entry.RoutingCurr = routing_entry.RoutingNext + routing_entry.RoutingCurr = routing_entry.RoutingNext -- Update entry routing_entry.RoutingNext = ImGuiKeyOwner_NoOwner routing_entry.RoutingNextScore = 0 if routing_entry.RoutingCurr == ImGuiKeyOwner_NoOwner then break end - rt.EntriesNext:push_back(routing_entry) + rt.EntriesNext:push_back(routing_entry) -- Write alive ones into new buffer + -- Apply routing to owner if there's no owner already (RoutingCurr == None at this point) + -- This is the result of previous frame's SetShortcutRouting() call. if routing_entry.Mods == g.IO.KeyMods then local owner_data = ImGui.GetKeyOwnerData(g, key) if owner_data.OwnerCurr == ImGuiKeyOwner_NoOwner then owner_data.OwnerCurr = routing_entry.RoutingCurr + -- IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr); end end @@ -7093,15 +8750,16 @@ function ImGui.UpdateKeyRoutingTable(rt) old_routing_idx = routing_entry.NextEntryIndex end + -- Rewrite linked-list rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] = (new_routing_start_idx <= rt.EntriesNext.Size and new_routing_start_idx or -1) for n = new_routing_start_idx, rt.EntriesNext.Size do rt.EntriesNext[n].NextEntryIndex = (n + 1 <= rt.EntriesNext.Size) and (n + 1) or -1 end end - rt.Entries:swap(rt.EntriesNext) + rt.Entries:swap(rt.EntriesNext) -- Swap new and old indexes end --- owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope() +-- owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope(). --- @param owner_id ImGuiID local function GetRoutingIdFromOwnerId(owner_id) local g = GImGui @@ -7111,6 +8769,12 @@ end --- @param key_chord ImGuiKeyChord --- @return ImGuiKeyRoutingData function ImGui.GetShortcutRoutingData(key_chord) + -- Majority of shortcuts will be Key + any number of Mods + -- We accept _Single_ mod with ImGuiKey.None. + -- - Shortcut(ImGuiKey.S | ImGuiMod_Ctrl) -- Legal + -- - Shortcut(ImGuiKey.S | ImGuiMod_Ctrl | ImGuiMod_Shift) -- Legal + -- - Shortcut(ImGuiMod_Ctrl) -- Legal + -- - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift) -- Not legal local g = GImGui local rt = g.KeysRoutingTable local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) @@ -7120,6 +8784,8 @@ function ImGui.GetShortcutRoutingData(key_chord) end IM_ASSERT(ImGui.IsNamedKey(key)) + -- Get (in the majority of case, the linked list will have one element so this should be 2 reads. + -- Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame). local routing_data local idx = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] while idx ~= -1 do @@ -7131,32 +8797,51 @@ function ImGui.GetShortcutRoutingData(key_chord) idx = routing_data.NextEntryIndex end + -- Add to linked-list local routing_data_idx = rt.Entries.Size + 1 rt.Entries:push_back(ImGuiKeyRoutingData()) routing_data = rt.Entries[routing_data_idx] routing_data.Mods = mods - routing_data.NextEntryIndex = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] + routing_data.NextEntryIndex = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] -- Setup linked list rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] = routing_data_idx return routing_data end +-- Current score encoding +-- - 0: Never route +-- - 1: ImGuiInputFlags.RouteGlobal (lower priority) +-- - 100..199: ImGuiInputFlags.RouteFocused (if window in focus-stack) +-- 200: ImGuiInputFlags.RouteGlobal | ImGuiInputFlags.RouteOverFocused +-- 300: ImGuiInputFlags.RouteActive or ImGuiInputFlags.RouteFocused (if item active) +-- 400: ImGuiInputFlags.RouteGlobal | ImGuiInputFlags.RouteOverActive +-- - 500..599: ImGuiInputFlags.RouteFocused | ImGuiInputFlags.RouteOverActive (if window in focus-stack) (higher priority) +-- 'flags' should include an explicit routing policy --- @param focus_scope_id ImGuiID --- @param owner_id ImGuiID --- @param flags ImGuiInputFlags local function CalcRoutingScore(focus_scope_id, owner_id, flags) local g = GImGui if bit32.band(flags, ImGuiInputFlags.RouteFocused) ~= 0 then + -- ActiveID gets high priority + -- (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it) if owner_id ~= 0 and g.ActiveId == owner_id then return 300 end + -- Score based on distance to focused window (lower is better) + -- Assuming both windows are submitting a routing request, + -- - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match) + -- - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best) + -- Assuming only WindowA is submitting a routing request, + -- - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score. + -- This essentially follow the window.ParentWindowForFocusRoute chain. if focus_scope_id == 0 then return 0 end for index_in_focus_path = 1, g.NavFocusRoute.Size do if g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id then - if bit32.band(flags, ImGuiInputFlags.RouteOverActive) ~= 0 then + if bit32.band(flags, ImGuiInputFlags.RouteOverActive) ~= 0 then -- && g.ActiveId != 0 && g.ActiveId != owner_id) return 599 - (index_in_focus_path - 1) else return 199 - (index_in_focus_path - 1) @@ -7185,16 +8870,22 @@ local function CalcRoutingScore(focus_scope_id, owner_id, flags) return 0 end +-- - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active +-- e.g. ImGuiKey.G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey.G can be. +-- - This is also used by UpdateInputEvents() to avoid trickling in the most common case of e.g. pressing ImGuiKey.G also emitting a G character. --- @param key_chord ImGuiKeyChord local function IsKeyChordPotentiallyCharInput(key_chord) + -- Mimic 'ignore_char_inputs' logic in InputText() local g = GImGui + -- When the right mods are pressed it cannot be a char input so we won't filter the shortcut out. local mods = bit32.band(key_chord, ImGuiMod_Mask_) local ignore_char_inputs = ((bit32.band(mods, ImGuiMod_Ctrl) ~= 0) and (bit32.band(mods, ImGuiMod_Alt) == 0)) or (g.IO.ConfigMacOSXBehaviors and (bit32.band(mods, ImGuiMod_Ctrl) ~= 0)) if ignore_char_inputs then return false end + -- Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered. local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if key == ImGuiKey.None then return false @@ -7202,6 +8893,11 @@ local function IsKeyChordPotentiallyCharInput(key_chord) return g.KeysMayBeCharInput:TestBit(key + 1) -- TestBit requires 1-based index end +-- Request a desired route for an input chord (key + mods). +-- Return true if the route is available this frame. +-- - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state. +-- (Conceptually this does a "Submit for next frame" + "Test for current frame". +-- As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.) --- @param key_chord ImGuiKeyChord --- @param flags ImGuiInputFlags --- @param owner_id ImGuiID @@ -7221,8 +8917,10 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiInputFlags.RouteGlobal, ImGuiInputFlags.RouteFocused)) ~= 0) end + -- Add ImGuiMod_XXXX when a corresponding ImGuiKey.LeftXXX/ImGuiKey.RightXXX is specified. key_chord = ImGui.FixupKeyChord(key_chord) + -- [DEBUG] Debug break requested by user if g.DebugBreakInShortcutRouting == key_chord then -- IM_DEBUG_BREAK() end @@ -7233,21 +8931,29 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) end end + -- Note how ImGuiInputFlags.RouteAlways won't set routing and thus won't set owner. May want to rework this? if bit32.band(flags, ImGuiInputFlags.RouteAlways) ~= 0 then -- IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register", ImGui.GetKeyChordName(key_chord), flags, owner_id) return true end + -- Specific culling when there's an active item. if g.ActiveId ~= 0 and g.ActiveId ~= owner_id then if bit32.band(flags, ImGuiInputFlags.RouteActive) ~= 0 then return false end + -- Cull shortcuts with no modifiers when it could generate a character. + -- e.g. Shortcut(ImGuiKey.G) also generates 'g' character, should not trigger when InputText() is active. + -- but Shortcut(Ctrl+G) should generally trigger when InputText() is active. + -- TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active. + -- (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined) if g.IO.WantTextInput and IsKeyChordPotentiallyCharInput(key_chord) then -- IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input", ImGui.GetKeyChordName(key_chord), flags, owner_id) return false end + -- ActiveIdUsingAllKeyboardKeys trumps all for ActiveId if bit32.band(flags, ImGuiInputFlags.RouteOverActive) == 0 and g.ActiveIdUsingAllKeyboardKeys then local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if key == ImGuiKey.None then @@ -7259,9 +8965,10 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) end end + -- Where do we evaluate route for? local focus_scope_id = g.CurrentFocusScopeId if bit32.band(flags, ImGuiInputFlags.RouteFromRootWindow) ~= 0 then - focus_scope_id = g.CurrentWindow.RootWindow.ID + focus_scope_id = g.CurrentWindow.RootWindow.ID -- See PushFocusScope() call in Begin() end local score = CalcRoutingScore(focus_scope_id, owner_id, flags) @@ -7270,18 +8977,23 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) return false end + -- Submit routing for NEXT frame (assuming score is sufficient) + -- FIXME: Could expose a way to use a "serve last" policy for same score resolution (using >= instead of >). local routing_data = ImGui.GetShortcutRoutingData(key_chord) + -- const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score >= routing_data->RoutingNextScore) : (score > routing_data->RoutingNextScore); if score > routing_data.RoutingNextScore then routing_data.RoutingNext = owner_id routing_data.RoutingNextScore = score end + -- Return routing state for CURRENT frame if routing_data.RoutingCurr == owner_id then -- IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route") end return routing_data.RoutingCurr == owner_id end +-- We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position. --- @param mouse_pos? ImVec2 function ImGui.IsMousePosValid(mouse_pos) local MOUSE_INVALID = -256000.0 @@ -7290,6 +9002,7 @@ function ImGui.IsMousePosValid(mouse_pos) return p.x >= MOUSE_INVALID and p.y >= MOUSE_INVALID end +-- [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. --- @return bool function ImGui.IsAnyMouseDown() local g = GImGui @@ -7308,7 +9021,7 @@ function ImGui.IsMouseDown(button, owner_id) local g = GImGui IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown) - return g.IO.MouseDown[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) + return g.IO.MouseDown[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) -- Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array. end --- @param button ImGuiMouseButton @@ -7329,14 +9042,14 @@ function ImGui.IsMouseClickedEx(button, flags, owner_id) local g = GImGui IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown) - if not g.IO.MouseDown[button] then + if not g.IO.MouseDown[button] then -- In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership) return false end local t = g.IO.MouseDownDuration[button] if t < 0.0 then return false end - IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedByIsMouseClicked)) == 0) + IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedByIsMouseClicked)) == 0) -- Passing flags not supported by this function! -- FIXME: Could support RepeatRate and RepeatUntil flags here. local is_repeat = (bit32.band(flags, ImGuiInputFlags.Repeat) ~= 0) local pressed = (t == 0.0) or (is_repeat and t > g.IO.KeyRepeatDelay and ImGui.CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0) @@ -7359,10 +9072,13 @@ function ImGui.IsMouseReleased(button, owner_id) local g = GImGui IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown) - return g.IO.MouseReleased[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) + return g.IO.MouseReleased[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) -- Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id) end +-- Prefer higher-level helper GetItemClickedCountWithSingleClickDelay() -- 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. --- @param button ImGuiMouseButton --- @param delay? float function ImGui.IsMouseReleasedWithDelay(button, delay) @@ -7414,6 +9130,22 @@ local function LastItemOverlayButtonForNullId(mouse_button) return id end +-- [BETA] Building block for disambiguation between single-click and double-click. +-- - Returns 1 on single-click but delayed by io.MouseSingleClickDelay (which is always > io.MouseDoubleClickTime) after mouse release. +-- - Returns 2+ on double-click and subsequent repeated clicks. +-- In order use that to replicate Windows Explorer's "click on label to rename after a delay", +-- When the function returns 1 for a delayed single click, you can add with further tests: +-- - If you want to test that the mouse position AT THE TIME of the click (before the delay): you can use the 'io.MouseClickedPos[mouse_button]' position. +-- - If you want to test that the mouse position is still over the item at the end of delay: you can use '&& IsItemHovered()'. +-- - If you want to test that the item was selected or the sole selection AT THE TIME of the click (before the delay): you can test for 'g.LastActiveIdWasSelected' or 'g.LastActiveIdWasSoleSelected'. +-- e.g. +-- local click_count = ImGui.GetItemClickedCountWithSingleClickDelay(mouse_button) +-- if click_count == 1 and ImGui.GetCurrentContext().LastActiveIdWasSoleSelected then +-- StartRename() +-- end +-- if click_count == 2 then +-- Launch() +-- end --- @param mouse_button? ImGuiMouseButton --- @param delay? float --- @return int @@ -7457,6 +9189,8 @@ function ImGui.GetMousePosOnOpeningCurrentPopup() end -- Return the delta from the initial clicking position while the mouse button is clicked or was just released. +-- This is locked and return 0.0f until the mouse moves past a distance threshold at least once. +-- NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window. --- @param button? ImGuiMouseButton --- @param lock_threshold? float --- @return ImVec2 @@ -7491,11 +9225,18 @@ do local key_changed_mask = ImBitArray(ImGuiKey.NamedKey_COUNT) +-- Process input queue +-- We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'. +-- - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost) +-- - trickle_fast_inputs = true : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87) --- @param trickle_fast_inputs bool function ImGui.UpdateInputEvents(trickle_fast_inputs) local g = GImGui local io = g.IO + -- Only trickle chars<>key when working with InputText() + -- FIXME: InputText() could parse event trail? + -- FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters) local trickle_interleaved_nonchar_keys_and_text = trickle_fast_inputs and g.WantTextInputNextFrame == 1 local mouse_moved = false @@ -7516,7 +9257,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) if g.IO.WantSetMousePos then break end - + -- Trickling Rule: Stop processing queued events if we already handled a mouse button change if trickle_fast_inputs and (mouse_button_changed ~= 0 or mouse_wheeled or key_changed or text_inputted) then stop_3231 = true; break end @@ -7525,12 +9266,13 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) io.MouseSource = e.MousePos.MouseSource mouse_moved = true elseif e.Type == ImGuiInputEventType.MouseButton then + -- Trickling Rule: Stop processing queued events if we got multiple action on the same button local button = e.MouseButton.Button IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT) if trickle_fast_inputs and ((bit32.band(mouse_button_changed, bit32.lshift(1, button)) ~= 0) or mouse_wheeled) then stop_3231 = true; break end - if trickle_fast_inputs and e.MouseButton.MouseSource == ImGuiMouseSource.TouchScreen and mouse_moved then + if trickle_fast_inputs and e.MouseButton.MouseSource == ImGuiMouseSource.TouchScreen and mouse_moved then -- #2702: TouchScreen have no initial hover. stop_3231 = true; break end @@ -7538,6 +9280,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) io.MouseSource = e.MouseButton.MouseSource mouse_button_changed = bit32.bor(mouse_button_changed, bit32.lshift(1, button)) elseif e.Type == ImGuiInputEventType.MouseWheel then + -- Trickling Rule: Stop processing queued events if we got multiple action on the event if trickle_fast_inputs and (mouse_moved or mouse_button_changed ~= 0) then stop_3231 = true; break end @@ -7569,7 +9312,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) stop_3231 = true; break end - if key_data.Down ~= e.Key.Down then + if key_data.Down ~= e.Key.Down then -- 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 + 1) if trickle_interleaved_nonchar_keys_and_text and not key_is_potentially_for_char_input then @@ -7583,7 +9326,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoKeyboard) ~= 0 then break end - + -- Trickling Rule: Stop processing queued events if keys/mouse have been interacted with if trickle_fast_inputs and (mouse_button_changed ~= 0 or mouse_moved or mouse_wheeled) then stop_3231 = true; break end @@ -7596,6 +9339,8 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) text_inputted = true end elseif e.Type == ImGuiInputEventType.Focus then + -- We intentionally overwrite this and process in NewFrame(), in order to give a chance + -- to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame. local focus_lost = not e.AppFocused.Focused io.AppFocusLost = focus_lost else @@ -7608,6 +9353,9 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) event_n = event_n + 1 end + -- Remaining events will be processed on the next frame + -- FIXME-MULTITHREADING: io.AddKeyEvent() etc. calls are mostly thread-safe apart from the fact they push to this + -- queue which may be resized here. Could potentially rework this to narrow down the section needing a mutex? (#5772) if event_n == g.InputEventsQueue.Size + 1 then g.InputEventsQueue:resize(0) else @@ -7616,6 +9364,10 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) end end + -- Clear buttons state when focus is lost + -- - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle. + -- - we clear in EndFrame() and not now in order allow application/user code polling this flag + -- (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event). if g.IO.AppFocusLost then g.IO:ClearInputKeys() g.IO:ClearInputMouse() @@ -7624,6 +9376,12 @@ end end +-- _LockXXX flags are useful to lock keys away from code which is not input-owner aware. +-- When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone. +-- - SetKeyOwner(..., None) : clears owner +-- - SetKeyOwner(..., Any, !Lock) : illegal (assert) +-- - SetKeyOwner(..., Any or None, Lock) : set lock +-- Ownership is automatically released on the frame after a release, see code in UpdateKeyboardInputs(). --- @param key ImGuiKey --- @param owner_id ImGuiID --- @param flags? ImGuiInputFlags @@ -7633,11 +9391,14 @@ function ImGui.SetKeyOwner(key, owner_id, flags) local g = GImGui --- @cast g ImGuiContext IM_ASSERT(ImGui.IsNamedKeyOrMod(key) and (owner_id ~= ImGuiKeyOwner_Any or (bit32.band(flags, bit32.bor(ImGuiInputFlags.LockThisFrame, ImGuiInputFlags.LockUntilRelease)) ~= 0)), "Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)") IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetKeyOwner)) == 0, "Passing flags not supported by this function!") + -- IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags) local owner_data = ImGui.GetKeyOwnerData(g, key) owner_data.OwnerCurr = owner_id owner_data.OwnerNext = owner_id + -- We cannot lock by default as it would likely break lots of legacy code. + -- In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data.Down test) owner_data.LockUntilRelease = (bit32.band(flags, ImGuiInputFlags.LockUntilRelease) ~= 0) owner_data.LockThisFrame = (bit32.band(flags, ImGuiInputFlags.LockThisFrame) ~= 0) or owner_data.LockUntilRelease end @@ -7666,6 +9427,12 @@ function ImGui.SetKeyOwnersForKeyChord(key_chord, owner_id, flags) end end +-- This is more or less equivalent to a fancier version of: +-- if (IsItemHovered() || IsItemActive()) +-- SetKeyOwner(key, GetItemID()); +-- Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times. +-- More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition. +-- Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority. --- @param key ImGuiKey --- @param flags? ImGuiInputFlags function ImGui.SetItemKeyOwner(key, flags) @@ -7680,7 +9447,7 @@ function ImGui.SetItemKeyOwner(key, flags) flags = bit32.bor(flags, ImGuiInputFlags.CondDefault_) end if (g.HoveredId == id and bit32.band(flags, ImGuiInputFlags.CondHovered) ~= 0) or (g.ActiveId == id and bit32.band(flags, ImGuiInputFlags.CondActive) ~= 0) then - IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetItemKeyOwner)) == 0) + IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetItemKeyOwner)) == 0) -- Passing flags not supported by this function! if not ImGui.TestKeyOwner(key, id) then return false end @@ -7690,6 +9457,7 @@ function ImGui.SetItemKeyOwner(key, flags) return false end +-- This is equivalent to comparing KeyMods + doing a IsKeyPressed() --- @param key_chord ImGuiKeyChord --- @param flags ImGuiInputFlags --- @param owner_id ImGuiID @@ -7728,7 +9496,7 @@ end --- @param owner_id ImGuiID function ImGui.Shortcut(key_chord, flags, owner_id) local g = GImGui - -- IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)", ImGui.GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id) + -- IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", ImGui.GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id) -- When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any. if bit32.band(flags, ImGuiInputFlags.RouteTypeMask_) == 0 then @@ -7776,6 +9544,9 @@ end --- @param window ImGuiWindow --- @nodiscard local function CalcWindowMinSize(window) + -- We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) + -- FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller. + -- Perhaps should tend further a neater test for this. local g = GImGui local size_min = ImVec2() @@ -7806,6 +9577,7 @@ local function CalcWindowMinSize(window) end end + -- Reduce artifacts with very small windows local window_for_height = window size_min.y = ImMax(size_min.y, window_for_height.TitleBarHeight + window_for_height.MenuBarHeight + ImMax(0, g.Style.WindowRounding - 1)) @@ -7823,6 +9595,7 @@ local function CalcWindowSizeAfterConstraint(window, size_desired) ImVec2_Copy(new_size, size_desired) if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) ~= 0 then + -- See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max. local cr = ImRect() ImRect_Copy(cr, g.NextWindowData.SizeConstraintRect) @@ -7842,6 +9615,7 @@ local function CalcWindowSizeAfterConstraint(window, size_desired) new_size.y = IM_TRUNC(new_size.y) end + -- Minimum size local size_min = CalcWindowMinSize(window) return ImMax(new_size, size_min) end @@ -7884,6 +9658,8 @@ local function CalcWindowAutoFitSize(window, size_contents, axis_mask) size_desired.x = (bit32.band(axis_mask, 1) ~= 0) and (size_contents.x + size_pad.x + decoration_w_without_scrollbars) or window.Size.x size_desired.y = (bit32.band(axis_mask, 2) ~= 0) and (size_contents.y + size_pad.y + decoration_h_without_scrollbars) or window.Size.y + -- Determine maximum window size + -- Child windows are laid within their parent (unless they are also popups/menus) and thus have no restriction local size_max = ImVec2(FLT_MAX, FLT_MAX) if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0 or bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then if not window.ViewportOwned then @@ -7896,13 +9672,16 @@ local function CalcWindowAutoFitSize(window, size_contents, axis_mask) end if bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0 then + -- Tooltip always resize (up to maximum size) return ImMin(size_desired, size_max) else local size_min = CalcWindowMinSize(window) local size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max) + -- When the window cannot fit all contents (either because of constraints, either because screen is too small), + -- we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. local size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit) - local size_contents_for_scrollbar_x = (bit32.band(axis_mask, 1) ~= 0) and size_contents.x or window.ContentSize.x + local size_contents_for_scrollbar_x = (bit32.band(axis_mask, 1) ~= 0) and size_contents.x or window.ContentSize.x -- See #9352. In theory this should use same logic as `window.ScrollbarY = ...` codepath in Begin(). Needs some plumbling. local size_contents_for_scrollbar_y = (bit32.band(axis_mask, 2) ~= 0) and size_contents.y or window.ContentSize.y local will_have_scrollbar_x = (size_auto_fit_after_constraint.x < size_contents_for_scrollbar_x + size_pad.x + decoration_w_without_scrollbars and bit32.band(window.Flags, ImGuiWindowFlags.NoScrollbar) == 0 and bit32.band(window.Flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0) or bit32.band(window.Flags, ImGuiWindowFlags.AlwaysHorizontalScrollbar) ~= 0 local will_have_scrollbar_y = (size_auto_fit_after_constraint.y < size_contents_for_scrollbar_y + size_pad.y + decoration_h_without_scrollbars and bit32.band(window.Flags, ImGuiWindowFlags.NoScrollbar) == 0) or bit32.band(window.Flags, ImGuiWindowFlags.AlwaysVerticalScrollbar) ~= 0 @@ -7948,7 +9727,7 @@ local function CalcResizePosSizeFromAnyCorner(window, corner_target_arg, corner_ local corner_target = ImVec2() ImVec2_Copy(corner_target, corner_target_arg) - if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then + if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then -- Clamp resizing of childs within parent local parent_window = window.ParentWindow local parent_flags = parent_window.Flags @@ -7963,8 +9742,8 @@ local function CalcResizePosSizeFromAnyCorner(window, corner_target_arg, corner_ corner_target.y = ImClamp(corner_target.y, limit_rect.Min.y, limit_rect.Max.y) end end - local pos_min = ImLerp(corner_target, window.Pos, corner_norm) - local pos_max = ImLerp(window.Pos + window.Size, corner_target, corner_norm) + local pos_min = ImLerp(corner_target, window.Pos, corner_norm) -- Expected window upper-left + local pos_max = ImLerp(window.Pos + window.Size, corner_target, corner_norm) -- Expected window lower-right local size_expected = pos_max - pos_min local size_constrained = CalcWindowSizeAfterConstraint(window, size_expected) @@ -7979,6 +9758,9 @@ local function CalcResizePosSizeFromAnyCorner(window, corner_target_arg, corner_ return out_pos, size_constrained end +-- Handle resize for: Resize Grips, Borders, Gamepad +-- Return true when using auto-fit (double-click on resize grip) +-- Returns (ret_auto_fit_mask, border_hovered, border_held) --- @param window ImGuiWindow --- @param resize_grip_count int --- @param resize_grip_col table @@ -7994,7 +9776,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c if (bit32.band(flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0 and bit32.band(window.ChildFlags, bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY)) == 0) then return 0, -1, -1 end - if window.WasActive == false then + if window.WasActive == false then -- Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window. return 0, -1, -1 end @@ -8016,7 +9798,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c -- This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it. -- - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow. -- - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold). - -- We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. + -- We only clip interaction so we overwrite window.ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. local clip_with_viewport_rect = bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasMouseHoveredViewport) == 0 or g.IO.MouseHoveredViewport ~= window.ViewportId or bit32.band(window.Viewport.Flags, ImGuiViewportFlags.NoDecoration) == 0 if (clip_with_viewport_rect) then ImRect_Copy(window.ClipRect, window.Viewport:GetMainRect()) @@ -8037,35 +9819,41 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c local corner = ImVec2(window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y) + -- Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window local resize_rect = ImRect(corner - inner_dir * grip_hover_outer_size, corner + inner_dir * grip_hover_inner_size) if resize_rect.Min.x > resize_rect.Max.x then resize_rect.Min.x, resize_rect.Max.x = resize_rect.Max.x, resize_rect.Min.x end if resize_rect.Min.y > resize_rect.Max.y then resize_rect.Min.y, resize_rect.Max.y = resize_rect.Max.y, resize_rect.Min.y end - local resize_grip_id = window:GetID(resize_grip_n) + local resize_grip_id = window:GetID(resize_grip_n) -- == GetWindowResizeCornerID() ImGui.ItemAdd(resize_rect, resize_grip_id, nil, ImGuiItemFlags.NoNav) local _, hovered, held = ImGui.ButtonBehavior(resize_rect, resize_grip_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus)) + -- GetForegroundDrawList(window):AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)) if hovered or held then ImGui.SetMouseCursor((bit32.band(resize_grip_n, 1) ~= 0) and ImGuiMouseCursor.ResizeNESW or ImGuiMouseCursor.ResizeNWSE) end if held and g.IO.MouseDoubleClicked[0] then + -- Auto-fit when double-clicking local size_auto_fit = CalcWindowAutoFitSize(window, window.ContentSizeIdeal, -1) size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit) - ret_auto_fit_mask = 0x03 + ret_auto_fit_mask = 0x03 -- Both axes ImGui.ClearActiveID() elseif held then + -- Resize from any of the four corners + -- We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position local clamp_min = ImVec2((corner_pos.x == 1.0) and clamp_rect.Min.x or -FLT_MAX, (corner_pos.y == 1.0) and clamp_rect.Min.y or -FLT_MAX) local clamp_max = ImVec2((corner_pos.x == 0.0) and clamp_rect.Max.x or FLT_MAX, (corner_pos.y == 0.0) and clamp_rect.Max.y or FLT_MAX) - local corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN) + local corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN) -- Corner of the window corresponding to our corner grip corner_target = ImClamp(corner_target, clamp_min, clamp_max) pos_target, size_target = CalcResizePosSizeFromAnyCorner(window, corner_target, corner_pos) end + -- Only lower-left grip is visible before hovering/activating local resize_grip_visible = held or hovered or (resize_grip_n == 0 and bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0) if resize_grip_visible then local color @@ -8106,9 +9894,10 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c end local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding) - local border_id = window:GetID(border_n + 4) + local border_id = window:GetID(border_n + 4) -- == GetWindowResizeBorderID() ImGui.ItemAdd(border_rect, border_id, nil, ImGuiItemFlags.NoNav) local _, hovered, held = ImGui.ButtonBehavior(border_rect, border_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus)) + -- GetForegroundDrawList(window):AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)) if hovered and g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER then hovered = false @@ -8128,6 +9917,9 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c end ImGui.ClearActiveID() elseif held then + -- Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop. + -- Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually. + -- FIXME: May want to generalize this idiom at lower-level, so more widgets can use it! local just_scrolled_manually_while_resizing = (g.WheelingWindow ~= nil and g.WheelingWindowScrolledFrame == g.FrameCount and ImGui.IsWindowChildOf(window, g.WheelingWindow, false, true)) if g.ActiveIdIsJustActivated or just_scrolled_manually_while_resizing then g.WindowResizeBorderExpectedRect = border_rect @@ -8142,7 +9934,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c local border_target_rel_mode_for_axis local border_target_abs_mode_for_axis border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis] - border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding -- Match ButtonBehavior() padding above + border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding -- Match ButtonBehavior() padding above. -- Use absolute mode position local border_target = ImVec2() @@ -8152,12 +9944,14 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c -- Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position. local ignore_resize = false if g.WindowResizeRelativeMode then + -- GetForegroundDrawList():AddText(GetMainViewport().WorkPos, IM_COL32_WHITE, "Relative Mode") border_target[axis] = border_target_rel_mode_for_axis if g.IO.MouseDelta[axis] == 0.0 or ((g.IO.MouseDelta[axis] > 0.0) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis)) then ignore_resize = true end end + -- Clamp, apply local clamp_min = ImVec2((border_n == ImGuiDir.Right) and clamp_rect.Min.x or -FLT_MAX, (border_n == ImGuiDir.Down or (border_n == ImGuiDir.Up and window_move_from_title_bar)) and clamp_rect.Min.y or -FLT_MAX) local clamp_max = ImVec2((border_n == ImGuiDir.Left) and clamp_rect.Max.x or FLT_MAX, (border_n == ImGuiDir.Up) and clamp_rect.Max.y or FLT_MAX) border_target = ImClamp(border_target, clamp_min, clamp_max) @@ -8177,8 +9971,10 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c end ImGui.PopID() + -- Restore nav layer window.DC.NavLayerCurrent = ImGuiNavLayer.Main + -- Apply back modified position/size to window if size_target.x ~= FLT_MAX and (window.Size.x ~= size_target.x or window.SizeFull.x ~= size_target.x) then window.Size.x = size_target.x window.SizeFull.x = size_target.x @@ -8197,6 +9993,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c window.Pos.y = ImFloor(pos_target.y) end + -- Recalculate next expected border expected coordinates if border_held ~= -1 then g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, border_held, grip_hover_inner_size, g.WindowsBorderHoverPadding) end @@ -8215,14 +10012,26 @@ function ImGui.CalcWrapWidthForPos(pos, wrap_pos_x) local g = GImGui local window = g.CurrentWindow if wrap_pos_x == 0.0 then + -- We could decide to setup a default wrapping max point for auto-resizing windows, + -- or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function? + -- if (window.Hidden and (window.Flags & ImGuiWindowFlags.AlwaysAutoResize)) + -- wrap_pos_x = ImMax(window.WorkRect.Min.x + g.FontSize * 10.0, window.WorkRect.Max.x) + -- else wrap_pos_x = window.WorkRect.Max.x elseif wrap_pos_x > 0.0 then - wrap_pos_x = wrap_pos_x + window.Pos.x - window.Scroll.x + wrap_pos_x = wrap_pos_x + window.Pos.x - window.Scroll.x -- wrap_pos_x is provided is window local space end return ImMax(wrap_pos_x - pos.x, 1.0) end +------------------------------------------------------------------------------- +-- [SECTION] RENDER HELPERS +-- Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change, +-- we need a nicer separation between low-level functions and high-level functions relying on the ImGui context. +-- Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context. +------------------------------------------------------------------------------- + --- @param text ImString --- @param text_end int? --- @return int # Exclusive upper bound @@ -8240,6 +10049,8 @@ function ImGui.FindRenderedTextEnd(text, text_end) return text_display_end end +-- Internal ImGui functions to render text +-- RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() --- @param pos ImVec2 --- @param text string --- @param text_begin int? @@ -8259,7 +10070,7 @@ function ImGui.RenderText(pos, text, text_begin, text_end, hide_text_after_hash) text_display_end = ImGui.FindRenderedTextEnd(text, text_end) else if text_end == nil then - text_end = #text + 1 + text_end = #text + 1 -- FIXME-OPT (not reached by our internal calls) end text_display_end = text_end end @@ -8281,7 +10092,7 @@ function ImGui.RenderTextWrapped(pos, text, text_end, wrap_width) local window = g.CurrentWindow if text_end == nil then - text_end = #text + 1 + text_end = #text + 1 -- FIXME-OPT (not reached by our internal calls) end if text ~= "" then @@ -8289,6 +10100,12 @@ function ImGui.RenderTextWrapped(pos, text, text_end, wrap_width) end 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, 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. +-- DOES NOT CALL LogRenderedText(), unlike RenderTextClipped!!! --- @param draw_list ImDrawList --- @param pos_min ImVec2 --- @param pos_max ImVec2 @@ -8302,6 +10119,7 @@ end function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin, text_display_end, text_size_if_known, align, clip_rect) if not align then align = ImVec2(0, 0) end + -- Perform CPU side clipping for single clipped element to avoid using scissor state local pos = ImVec2() ImVec2_Copy(pos, pos_min) @@ -8310,13 +10128,15 @@ function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin local clip_min = clip_rect and clip_rect.Min or pos_min local clip_max = clip_rect and clip_rect.Max or pos_max local need_clipping = (pos.x + text_size.x >= clip_max.x) or (pos.y + text_size.y >= clip_max.y) - if (clip_rect) then + if (clip_rect) then -- If we had no explicit clipping rectangle then pos==clip_min need_clipping = need_clipping or ((pos.x < clip_min.x) or (pos.y < clip_min.y)) end + -- Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. if (align.x > 0.0) then pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x) end if (align.y > 0.0) then pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y) end + -- Render local g = GImGui if (need_clipping) then local fine_clip_rect = ImVec4(clip_min.x, clip_min.y, clip_max.x, clip_max.y) @@ -8336,6 +10156,7 @@ end function ImGui.RenderTextClipped(pos_min, pos_max, text, text_end, text_size_if_known, align, clip_rect) if not align then align = ImVec2(0, 0) end + -- Hide anything after a '##' string local text_display_end = ImGui.FindRenderedTextEnd(text, text_end) local text_len = text_display_end - 1 @@ -8370,6 +10191,8 @@ function ImGui.RenderNavCursor(bb, id, flags, rounding) return end + -- We don't early out on 'window.Flags & ImGuiWindowFlags.NoNavInputs' because it would be inconsistent with + -- other code directly checking NavCursorVisible. Instead we aim for NavCursorVisible to always be false. local window = g.CurrentWindow if window.DC.NavHideHighlightOneFrame then return @@ -8382,7 +10205,7 @@ function ImGui.RenderNavCursor(bb, id, flags, rounding) local display_rect = ImRect() ImRect_Copy(display_rect, bb) display_rect:ClipWith(window.ClipRect) - local scale_factor = ImGui.GetScale() + local scale_factor = ImGui.GetScale() -- FIXME-DPI local thickness = ImTrunc(ImMax(2.0, 1.5 * scale_factor)) if bit32.band(flags, ImGuiNavRenderCursorFlags.Compact) ~= 0 then window.DrawList:AddRect(display_rect.Min, display_rect.Max, ImGui.GetColorU32(ImGuiCol.NavCursor), rounding, thickness) @@ -8415,13 +10238,14 @@ local uv_fill = {ImVec2(), ImVec2()} --- @param col_shadow ImU32 function ImGui.RenderMouseCursor(base_pos, base_scale, mouse_cursor, col_fill, col_border, col_shadow) local g = GImGui - if mouse_cursor <= ImGuiMouseCursor.None or mouse_cursor >= ImGuiMouseCursor.COUNT then -- We intentionally accept out of bound values + if mouse_cursor <= ImGuiMouseCursor.None or mouse_cursor >= ImGuiMouseCursor.COUNT then -- We intentionally accept out of bound values. mouse_cursor = ImGuiMouseCursor.Arrow end local font_atlas = g.DrawListSharedData.FontAtlas for _, viewport in g.Viewports:iter() do repeat + -- We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor. if not ImFontAtlasGetMouseCursorTexData(font_atlas, mouse_cursor, offset, size, uv_border, uv_fill) then break end @@ -8453,9 +10277,10 @@ end end ---- Another overly complex function until we reorganize everything into a nice all-in-one helper. ---- This is made more complex because we have dissociated the layout rectangle (pos_min .. pos_max) 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. +-- 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) 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. +-- (BREAKING) On 2025/04/16 we removed the 'float clip_max_x' parameters which was preceding 'float ellipsis_max' and was the same value for 99% of users. --- @param draw_list ImDrawList --- @param pos_min ImVec2 --- @param pos_max ImVec2 @@ -8478,8 +10303,8 @@ function ImGui.RenderTextEllipsis(draw_list, pos_min, pos_max, ellipsis_max_x, t text_size = ImGui.CalcTextSize(text, text_end_full, false, 0.0) end - -- 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)) + -- draw_list:AddLineV(pos_max.x, pos_min.y - 4, pos_max.y + 6, IM_COL32(0, 0, 255, 255)) + -- draw_list:AddLineV(ellipsis_max_x, pos_min.y - 2, 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 then @@ -8515,6 +10340,7 @@ function ImGui.RenderTextEllipsis(draw_list, pos_min, pos_max, ellipsis_max_x, t end end +-- Render a rectangle shaped with optional rounding and borders --- @param p_min ImVec2 --- @param p_max ImVec2 --- @param fill_col ImU32 @@ -8583,7 +10409,7 @@ local function RenderWindowOuterBorders(window) if border_size > 0.0 and (bit32.band(window.Flags, ImGuiWindowFlags.NoBackground) == 0) then window.DrawList:AddRect(window.Pos, window.Pos + window.Size, border_col, window.WindowRounding, window.WindowBorderSize, 0) elseif border_size > 0.0 then - if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 then + if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 then -- Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border. RenderWindowOuterSingleBorder(window, 1, border_col, border_size) end if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0 then @@ -8594,7 +10420,7 @@ local function RenderWindowOuterBorders(window) if window.ResizeBorderHovered ~= -1 or window.ResizeBorderHeld ~= -1 then local border_n = (window.ResizeBorderHeld ~= -1) and window.ResizeBorderHeld or window.ResizeBorderHovered local border_col_resizing = ImGui.GetColorU32((window.ResizeBorderHeld ~= -1) and ImGuiCol.SeparatorActive or ImGuiCol.SeparatorHovered) - RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0, window.WindowBorderSize)) + RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0, window.WindowBorderSize)) -- Thicker than usual end if g.Style.FrameBorderSize > 0 and (bit32.band(window.Flags, ImGuiWindowFlags.NoTitleBar) == 0) and not window.DockIsActive then @@ -8603,6 +10429,8 @@ local function RenderWindowOuterBorders(window) end end +-- Draw background and borders +-- Draw and handle scrollbars --- @param window ImGuiWindow --- @param title_bar_rect ImRect --- @param title_bar_is_highlight bool @@ -8614,10 +10442,13 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high local style = g.Style local flags = window.Flags + -- 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. local window_rounding = window.WindowRounding local window_border_size = window.WindowBorderSize if window.Collapsed then + -- Title bar only local backup_border_size = style.FrameBorderSize g.Style.FrameBorderSize = window.WindowBorderSize @@ -8628,6 +10459,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high -- Window background if bit32.band(flags, ImGuiWindowFlags.NoBackground) == 0 then local bg_col = ImGui.GetColorU32(GetWindowBgColorIdx(window)) + -- Adjust alpha. For docking local override_alpha = false local alpha = 1.0 @@ -8661,6 +10493,8 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high if window.DockIsActive then window.DockNode.IsBgDrawnThisFrame = true end -- Title bar + -- (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag, + -- in order for their pos/size to be matching their undocking state.) if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and not window.DockIsActive then local title_bar_col = ImGui.GetColorU32(title_bar_is_highlight and ImGuiCol.TitleBgActive or ImGuiCol.TitleBg) window.DrawList:AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags.RoundCornersTop) @@ -8669,7 +10503,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high -- Menu bar if bit32.band(flags, ImGuiWindowFlags.MenuBar) ~= 0 then local menu_bar_rect = window:MenuBarRect() - menu_bar_rect:ClipWith(window:Rect()) + menu_bar_rect:ClipWith(window:Rect()) -- Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. window.DrawList:AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, ImGui.GetColorU32(ImGuiCol.MenuBarBg), (bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0) and window_rounding or 0.0, ImDrawFlags.RoundCornersTop) if style.FrameBorderSize > 0.0 and menu_bar_rect.Max.y < window.Pos.y + window.Size.y then window.DrawList:AddLineH(menu_bar_rect.Min.x + window_border_size * 0.5, menu_bar_rect.Max.x - window_border_size * 0.5, menu_bar_rect.Max.y, ImGui.GetColorU32(ImGuiCol.Border), style.FrameBorderSize) @@ -8689,12 +10523,15 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high if pressed then node.WantHiddenTabBarToggle = true elseif held and ImGui.IsMouseDragging(0) then - ImGui.StartMouseMovingWindowOrNode(window, node, true) + ImGui.StartMouseMovingWindowOrNode(window, node, true) -- Undock from tab-bar triangle = same as window/collapse menu button end + + -- FIXME-DOCK: Ideally we'd use ImGuiCol.TitleBgActive/ImGuiCol.TitleBg here, but neither is guaranteed to be visible enough at this sort of size.. local col = ImGui.GetColorU32(((held and hovered) or (node.IsFocused and not hovered)) and ImGuiCol.ButtonActive or (hovered and ImGuiCol.ButtonHovered or ImGuiCol.Button)) window.DrawList:AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0), p + ImVec2(0.0, unhide_sz_draw), col) end + -- Scrollbars if window.ScrollbarX then ImGui.Scrollbar(ImGuiAxis.X) end @@ -8702,7 +10539,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high ImGui.Scrollbar(ImGuiAxis.Y) end - -- Resize grip(s) + -- Render resize grips (after their input handling so we don't have a frame of latency) if handle_borders_and_resize_grips and (bit32.band(flags, ImGuiWindowFlags.NoResize) == 0) then for resize_grip_n = 1, #ImGuiResizeGripDef do repeat @@ -8723,6 +10560,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end end + -- Borders (for dock node host they will be rendered over after the tab bar) if handle_borders_and_resize_grips and not window.DockNodeAsHost then RenderWindowOuterBorders(window) end @@ -8732,6 +10570,9 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders +-- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. +-- Render title text, collapse button, close button +-- Returns the updated 'open' value (nil when there is no close button) --- @param window ImGuiWindow --- @param title_bar_rect ImRect --- @param name string @@ -8745,10 +10586,14 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) local has_close_button = (open ~= nil) local has_collapse_button = bit32.band(flags, ImGuiWindowFlags.NoCollapse) == 0 and (style.WindowMenuButtonPosition ~= ImGuiDir.None) + -- Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) + -- FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags.NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref? local item_flags_backup = g.CurrentItemFlags g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.NoNavDefaultFocus) window.DC.NavLayerCurrent = ImGuiNavLayer.Menu + -- Layout buttons + -- FIXME: Would be nice to generalize the subtleties expressed here into reusable code. local pad_l = g.Style.FramePadding.x local pad_r = g.Style.FramePadding.x local button_sz = g.FontSize @@ -8767,12 +10612,14 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) pad_l = pad_l + button_sz + style.ItemInnerSpacing.x end + -- Collapse button (submitting first so it gets priority when choosing a navigation init fallback) if has_collapse_button then if ImGui.CollapseButton(window:GetID("#COLLAPSE"), collapse_button_pos) then window.WantCollapseToggle = true -- Defer actual collapsing to next frame as we are too far in the Begin() function end end + -- Close button if has_close_button then local backup_item_flags = g.CurrentItemFlags g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.NoFocus) @@ -8785,9 +10632,13 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) window.DC.NavLayerCurrent = ImGuiNavLayer.Main g.CurrentItemFlags = item_flags_backup + -- Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) + -- FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. local marker_size_x = (bit32.band(flags, ImGuiWindowFlags.UnsavedDocument) ~= 0) and (button_sz * 0.80) or 0.0 local text_size = ImGui.CalcTextSize(name, nil, true) + ImVec2(marker_size_x, 0.0) + -- As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, + -- while uncentered title text will still reach edges correctly. if (pad_l > style.FramePadding.x) then pad_l = pad_l + g.Style.ItemInnerSpacing.x end @@ -8795,7 +10646,7 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) pad_r = pad_r + g.Style.ItemInnerSpacing.x end if (style.WindowTitleAlign.x > 0.0 and style.WindowTitleAlign.x < 1.0) then - local centerness = ImSaturate(1.0 - ImFabs(style.WindowTitleAlign.x - 0.5) * 2.0) + local centerness = ImSaturate(1.0 - ImFabs(style.WindowTitleAlign.x - 0.5) * 2.0) -- 0.0 on either edges, 1.0 on center local pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect:GetWidth() - pad_l - pad_r - text_size.x) pad_l = ImMax(pad_l, pad_extend * centerness) pad_r = ImMax(pad_r, pad_extend * centerness) @@ -8813,7 +10664,8 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - math.floor(marker_size_x * 0.5)) end end - + -- if (g.IO.KeyShift) window.DrawList:AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)) -- [DEBUG] + -- if (g.IO.KeyCtrl) window.DrawList:AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)) -- [DEBUG] ImGui.RenderTextClipped(layout_r.Min, layout_r.Max, name, nil, text_size, style.WindowTitleAlign, clip_r) return open @@ -8839,7 +10691,7 @@ function ImGui.UpdateWindowParentAndRootLinks(window, flags, parent_window) if parent_window and (bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0) then window.RootWindowPopupTree = parent_window.RootWindowPopupTree end - if parent_window and (bit32.band(flags, ImGuiWindowFlags.Modal) == 0) and (bit32.band(flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0) then + if parent_window and (bit32.band(flags, ImGuiWindowFlags.Modal) == 0) and (bit32.band(flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0) then -- FIXME: simply use _NoTitleBar ? window.RootWindowForTitleBarHighlight = parent_window.RootWindowForTitleBarHighlight end @@ -8882,10 +10734,10 @@ function ImGui.UpdateWindowSkipRefresh(window) window.SkipItems = true end -- FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused. - if window.Appearing then -- If currently appearing + if window.Appearing then -- If currently appearing return end - if window.Hidden then -- If was hidden (previous frame) + if window.Hidden then -- If was hidden (previous frame) return end if bit32.band(g.NextWindowData.RefreshFlagsVal, ImGuiWindowRefreshFlags.RefreshOnHover) ~= 0 and g.HoveredWindow then @@ -8948,6 +10800,11 @@ function ImGui.GcCompactTransientMiscBuffers() end end +-- Free up/compact internal window buffers, we can use this when a window becomes unused. +-- Not freed: +-- - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data) +-- This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost. +-- FIXME: Consider exposing of elaborating GC policy, e.g. being able to trim excessive ImDrawList gaps. (#9303) --- @param window ImGuiWindow function ImGui.GcCompactTransientWindowBuffers(window) window.MemoryCompacted = true @@ -8962,6 +10819,8 @@ end --- @param window ImGuiWindow function ImGui.GcAwakeTransientWindowBuffers(window) + -- We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening. + -- The other buffers tends to amortize much faster. window.MemoryCompacted = false window.DrawList.IdxBuffer:reserve(window.MemoryDrawListIdxCapacity) window.DrawList.VtxBuffer:reserve(window.MemoryDrawListVtxCapacity) @@ -8987,14 +10846,16 @@ function ImGui.SetWindowPos(window, pos, cond) end if cond == nil then cond = 0 end + -- Test condition (NB: bit 0 is always true) and clear flags for next time if (cond ~= 0) and (bit32.band(window.SetWindowPosAllowFlags, cond) == 0) then return end - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. window.SetWindowPosAllowFlags = bit32.band(window.SetWindowPosAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing))) ImVec2_Copy(window.SetWindowPosVal, ImVec2(FLT_MAX, FLT_MAX)) + -- Set local old_pos = ImVec2() ImVec2_Copy(old_pos, window.Pos) @@ -9007,9 +10868,9 @@ function ImGui.SetWindowPos(window, pos, cond) return end ImGui.MarkIniSettingsDirty(window) - - ImVec2_Copy(window.DC.CursorPos, window.DC.CursorPos + offset) - ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorMaxPos + offset) + -- FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here. + ImVec2_Copy(window.DC.CursorPos, window.DC.CursorPos + offset) -- As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorMaxPos + offset) -- And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected. ImVec2_Copy(window.DC.IdealMaxPos, window.DC.IdealMaxPos + offset) ImVec2_Copy(window.DC.CursorStartPos, window.DC.CursorStartPos + offset) end @@ -9027,13 +10888,15 @@ function ImGui.SetWindowSize(window, size, cond) end if cond == nil then cond = 0 end + -- Test condition (NB: bit 0 is always true) and clear flags for next time if ((cond ~= 0) and bit32.band(window.SetWindowSizeAllowFlags, cond) == 0) then return end - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. window.SetWindowSizeAllowFlags = bit32.band(window.SetWindowSizeAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing))) + -- Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags.AlwaysAutoResize) if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0 or window.Appearing or bit32.band(window.ChildFlags, ImGuiChildFlags.AlwaysAutoResize) ~= 0 then window.AutoFitFramesX = (size.x <= 0.0) and 2 or 0 end @@ -9041,6 +10904,7 @@ function ImGui.SetWindowSize(window, size, cond) window.AutoFitFramesY = (size.y <= 0.0) and 2 or 0 end + -- Set local old_size_x, old_size_y = window.SizeFull.x, window.SizeFull.y if size.x <= 0.0 then @@ -9067,6 +10931,7 @@ function ImGui.SetWindowCollapsed(window, collapsed, cond) window, collapsed, cond = GImGui.CurrentWindow, window, collapsed end if cond == nil then cond = 0 end + -- Test condition (NB: bit 0 is always true) and clear flags for next time if cond ~= 0 and bit32.band(window.SetWindowCollapsedAllowFlags, cond) == 0 then return end @@ -9143,7 +11008,7 @@ function ImGui.SetNextWindowPos(pos, cond, pivot) if pivot == nil then pivot = ImVec2(0, 0) end local g = GImGui - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) ImVec2_Copy(g.NextWindowData.PosVal, pos) @@ -9158,7 +11023,7 @@ function ImGui.SetNextWindowSize(size, cond) if cond == nil then cond = 0 end local g = GImGui - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ImVec2_Copy(g.NextWindowData.SizeVal, size) @@ -9197,6 +11062,9 @@ function ImGui.GetFont() return GImGui.Font end +-- 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) function ImGui.GetFontSize() return GImGui.FontSize end @@ -9245,7 +11113,7 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) child_flags = bit32.band(bit32.bor(child_flags, g.NextWindowData.ChildFlagsSet), bit32.bnot(g.NextWindowData.ChildFlagsClear)) end - -- Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument + -- Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument. local ImGuiChildFlags_SupportedMask_ = bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY, ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AutoResizeY, ImGuiChildFlags.AlwaysAutoResize, ImGuiChildFlags.FrameStyle, ImGuiChildFlags.NavFlattened) -- IM_UNUSED(ImGuiChildFlags_SupportedMask_) IM_ASSERT(bit32.band(child_flags, bit32.bnot(ImGuiChildFlags_SupportedMask_)) == 0, "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?") @@ -9265,7 +11133,7 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoDocking) window_flags = bit32.bor(window_flags, bit32.band(parent_window.Flags, ImGuiWindowFlags.NoMove)) -- Inherit the NoMove flag if bit32.band(child_flags, bit32.bor(ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AutoResizeY, ImGuiChildFlags.AlwaysAutoResize)) ~= 0 then - window_flags = bit32.bor(window_flags, ImGuiWindowFlags.AlwaysAutoResize) + window_flags = bit32.bor(window_flags, ImGuiWindowFlags.AlwaysAutoResize) -- FIXME: Would be sane to not make single-axis flag set this. (#9355) end if bit32.band(child_flags, bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY)) == 0 then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoSavedSettings) @@ -9282,15 +11150,15 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) end -- Forward size - -- Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags.ResizeXXX is set. + -- Important: Begin() has special processing to switch condition to ImGuiCond.FirstUseEver for a given axis when ImGuiChildFlags.ResizeXXX is set. -- (the alternative would to store conditional flags per axis, which is possible but more code) local size_avail = ImGui.GetContentRegionAvail() local size_default = ImVec2((bit32.band(child_flags, ImGuiChildFlags.AutoResizeX) ~= 0) and 0.0 or size_avail.x, (bit32.band(child_flags, ImGuiChildFlags.AutoResizeY) ~= 0) and 0.0 or size_avail.y) local size = ImGui.CalcItemSize(size_arg, size_default.x, size_default.y) -- 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. + -- (since the code in Begin() never supported SizeVal==0.0 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 bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ~= 0 and bit32.band(g.NextWindowData.SizeCond, ImGuiCond.Always) ~= 0 then if g.NextWindowData.SizeVal.x > 0.0 then size.x = g.NextWindowData.SizeVal.x @@ -9308,6 +11176,9 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) -- 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. -- e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it. local temp_window_name + -- if (name and parent_window.IDStack:back() == parent_window.ID) + -- temp_window_name = ImFormatString("%s/%s", parent_window.Name, name) -- May omit ID if in root of ID stack + -- else if name then temp_window_name = ImFormatString("%s/%s_%08X", parent_window.Name, name, id) else @@ -9357,6 +11228,7 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) end -- Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'. +-- ImGuiChildFlags.Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details! -- `true` is accepted as ImGuiChildFlags.Borders for legacy code. --- @param str_id_or_id string|ImGuiID --- @param size_arg? ImVec2 @@ -9404,6 +11276,8 @@ function ImGui.EndChild() end else -- Not navigable into + -- - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs. + -- - We could later decide to not apply this path if ImGuiChildFlags.FrameStyle or ImGuiChildFlags.Borders is set. ImGui.ItemAdd(bb, child_window.ChildId, nil, ImGuiItemFlags.NoNav) -- But when flattened we directly reach items, adjust active layer mask accordingly @@ -9415,6 +11289,7 @@ function ImGui.EndChild() g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end child_window.DC.ChildItemStatusFlags = g.LastItemData.StatusFlags + -- SetLastItemDataForChildWindowItem(child_window, child_window:Rect()) -- Not needed, effectively done by ItemAdd() else ImGui.SetLastItemDataForChildWindowItem(child_window, child_window:Rect()) end @@ -9460,6 +11335,7 @@ function ImGui.SetNextWindowFlags(flags, enabled) end -- Content size = inner scrollable rectangle, padded with WindowPadding. +-- SetNextWindowContentSize(ImVec2(100,100)) + ImGuiWindowFlags.AlwaysAutoResize will always allow submitting a 100x100 item. --- @param size ImVec2 function ImGui.SetNextWindowContentSize(size) local g = GImGui @@ -9479,7 +11355,7 @@ end function ImGui.SetNextWindowCollapsed(collapsed, cond) if cond == nil then cond = 0 end local g = GImGui - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasCollapsed) g.NextWindowData.CollapsedVal = collapsed g.NextWindowData.CollapsedCond = (cond ~= 0) and cond or ImGuiCond.Always @@ -9548,6 +11424,9 @@ end --- @param window ImGuiWindow function ImGui.StartMouseMovingWindow(window) + -- Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows. + -- We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward. + -- This is because we want ActiveId to be set even when the window is not permitted to move. local g = GImGui ImGui.FocusWindow(window) ImGui.SetActiveID(window.MoveId, window) @@ -9571,15 +11450,23 @@ function ImGui.StartMouseMovingWindow(window) end end +-- 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 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. function ImGui.UpdateMouseMovingWindowNewFrame() local g = GImGui if g.MovingWindow then + -- We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window). + -- We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow.MoveId for consistency. ImGui.KeepAliveID(g.ActiveId) IM_ASSERT(g.MovingWindow and g.MovingWindow.RootWindowDockTree) local moving_window = g.MovingWindow.RootWindowDockTree + -- When a window stop being submitted while being dragged, it may will its viewport until next Begin() local window_disappeared = (not moving_window.WasActive and not moving_window.Active) if g.IO.MouseDown[0] and ImGui.IsMousePosValid(g.IO.MousePos) and not window_disappeared then local pos = g.IO.MousePos - g.ActiveIdClickOffset @@ -9596,6 +11483,7 @@ function ImGui.UpdateMouseMovingWindowNewFrame() ImGui.ClearActiveID() end else + -- When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others. if (g.ActiveIdWindow and g.ActiveIdWindow.MoveId == g.ActiveId) then ImGui.KeepAliveID(g.ActiveId) @@ -9610,6 +11498,7 @@ function ImGui.GetDrawListSharedData() return GImGui.DrawListSharedData end +-- Supported flags: ImGuiPopupFlags.AnyPopupId, ImGuiPopupFlags.AnyPopupLevel --- @param id ImGuiID --- @param popup_flags ImGuiPopupFlags function ImGui.IsPopupOpen(id, popup_flags) @@ -9645,6 +11534,7 @@ function ImGui.IsPopupOpen(id, popup_flags) end end +-- Also see FindBlockingModal(nil) --- @return ImGuiWindow? function ImGui.GetTopMostPopupModal() local g = GImGui @@ -9659,6 +11549,9 @@ function ImGui.GetTopMostPopupModal() return nil end +-- Initiate focusing and moving window when clicking on empty space or title bar. +-- Initiate focusing window when clicking on a disabled item. +-- Handle left-click and right-click focus. function ImGui.UpdateMouseMovingWindowEndFrame() local g = GImGui @@ -9666,13 +11559,18 @@ function ImGui.UpdateMouseMovingWindowEndFrame() return end + -- Unless we just made a window/popup appear if g.NavWindow and g.NavWindow.Appearing then return end local hovered_window = g.HoveredWindow + -- Click on empty space to focus window and start moving + -- (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!) if ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) then + -- Handle the edge case of a popup being closed while clicking in its empty space. + -- If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. local hovered_root if hovered_window then hovered_root = hovered_window.RootWindow @@ -9685,8 +11583,11 @@ function ImGui.UpdateMouseMovingWindowEndFrame() if hovered_window ~= nil and not is_closed_popup and not is_queued_focus_request then ImGui.StartMouseMovingWindow(hovered_window) + -- FIXME: In principle we might be able to call StopMouseMovingWindow() below. + -- Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symmetrical, at the later doesn't clear ActiveId. + -- Cancel moving if clicked outside of title bar - if bit32.band(hovered_window.BgClickFlags, ImGuiWindowBgClickFlags.Move) == 0 then -- set by io.ConfigWindowsMoveFromTitleBarOnly + if bit32.band(hovered_window.BgClickFlags, ImGuiWindowBgClickFlags.Move) == 0 then -- set by io.ConfigWindowsMoveFromTitleBarOnly if bit32.band(hovered_root.Flags, ImGuiWindowFlags.NoTitleBar) == 0 then if not hovered_root:TitleBarRect():Contains(g.IO.MouseClickedPos[0]) then g.MovingWindow = nil @@ -9701,6 +11602,7 @@ function ImGui.UpdateMouseMovingWindowEndFrame() g.ActiveIdDisabledId = g.HoveredId end elseif hovered_window == nil and g.NavWindow ~= nil then + -- Clicking on void disable focus ImGui.FocusWindow(nil, ImGuiFocusRequestFlags.UnlessBelowModal) end end @@ -9717,6 +11619,8 @@ function ImGui.UpdateMouseMovingWindowEndFrame() end end +-- This is called during NewFrame()->UpdateViewportsNewFrame() only. +-- Need to keep in sync with SetWindowPos() --- @param window ImGuiWindow --- @param delta ImVec2 function ImGui.TranslateWindow(window, delta) @@ -9747,8 +11651,13 @@ function ImGui.FindWindowByName(name) return ImGui.FindWindowByID(id) end ---- Push a new Dear ImGui window to add widgets to. ---- - Passing a non-nil `open` displays a close button on the upper-right corner of the window +-- Push a new Dear ImGui window to add widgets to. +-- - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. +-- - Begin/End can be called multiple times during the frame with the same window name to append content. +-- - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). +-- You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. +-- - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui.End() even if false is returned. +-- - Passing a non-nil 'open' displays a Close button on the upper-right corner of the window, the returned 'is_open' value will be false when the button is pressed. --- @param name string --- @param open? bool --- @param flags? ImGuiWindowFlags @@ -9760,10 +11669,11 @@ function ImGui.Begin(name, open, flags) local g = GImGui local style = g.Style - IM_ASSERT(name ~= nil and name ~= "") - IM_ASSERT(g.WithinFrameScope) - IM_ASSERT(g.FrameCountEnded ~= g.FrameCount) + IM_ASSERT(name ~= nil and name ~= "") -- Window name required + IM_ASSERT(g.WithinFrameScope) -- Forgot to call ImGui.NewFrame() + IM_ASSERT(g.FrameCountEnded ~= g.FrameCount) -- Called ImGui.Render() or ImGui.EndFrame() and haven't called ImGui.NewFrame() again yet + -- Find or create local window = ImGui.FindWindowByName(name) local window_just_created = (window == nil) if window_just_created then @@ -9783,7 +11693,8 @@ function ImGui.Begin(name, open, flags) local first_begin_of_the_frame = (window.LastFrameActive ~= current_frame) window.IsFallbackWindow = (g.CurrentWindowStack.Size == 0 and g.WithinFrameScopeWithImplicitWindow) - local window_just_activated_by_user = (window.LastFrameActive < (current_frame - 1)) + -- Update the Appearing flag (note: the BeginDocked() path may also set this to true later) + local window_just_activated_by_user = (window.LastFrameActive < (current_frame - 1)) -- Not using !WasActive because the implicit "Debug" window would always toggle off->on if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then local popup_ref = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1] window_just_activated_by_user = window_just_activated_by_user or (window.PopupId ~= popup_ref.PopupId) -- We recycle popups so treat window as activated if popup id changed @@ -9830,7 +11741,7 @@ function ImGui.Begin(name, open, flags) flags = window.Flags if window.DockIsActive then IM_ASSERT(window.DockNode ~= nil) - g.NextWindowData.HasFlags = bit32.band(g.NextWindowData.HasFlags, bit32.bnot(ImGuiNextWindowDataFlags.HasSizeConstraint)) + g.NextWindowData.HasFlags = bit32.band(g.NextWindowData.HasFlags, bit32.bnot(ImGuiNextWindowDataFlags.HasSizeConstraint)) -- Docking currently override constraints end -- Amend the Appearing flag @@ -9841,6 +11752,7 @@ function ImGui.Begin(name, open, flags) end end + -- Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack local parent_window_in_stack if window.DockIsActive and window.DockNode.HostWindow then parent_window_in_stack = window.DockNode.HostWindow @@ -9860,6 +11772,7 @@ function ImGui.Begin(name, open, flags) parent_window = window.ParentWindow end + -- We allow window memory to be compacted so recreate the base stack when needed. if window.IDStack.Size == 0 then window.IDStack:push_back(window.ID) end @@ -9880,10 +11793,14 @@ function ImGui.Begin(name, open, flags) g.BeginMenuDepth = g.BeginMenuDepth + 1 end + -- Update .RootWindow and others pointers (before any possible call to FocusWindow) if first_begin_of_the_frame then ImGui.UpdateWindowParentAndRootLinks(window, flags, parent_window) window.ParentWindowInBeginStack = parent_window_in_stack + -- Focus route + -- There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack, + -- Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798) if window.RootWindow ~= window then window.ParentWindowForFocusRoute = parent_window_in_stack else @@ -9894,10 +11811,12 @@ function ImGui.Begin(name, open, flags) window.ParentWindowForFocusRoute = window.DockNode.HostWindow end end + -- Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute() if window.WindowClass and window.WindowClass.FocusRouteParentWindowId ~= nil and window.WindowClass.FocusRouteParentWindowId ~= 0 then window.ParentWindowForFocusRoute = ImGui.FindWindowByID(window.WindowClass.FocusRouteParentWindowId) end + -- Inherit SetWindowFontScale() from parent until we fix this system... if parent_window then window.FontWindowScaleParents = parent_window.FontWindowScaleParents * parent_window.FontWindowScale else @@ -9905,10 +11824,11 @@ function ImGui.Begin(name, open, flags) end end + -- Add to focus scope stack ImGui.PushFocusScope((bit32.band(window.ChildFlags, ImGuiChildFlags.NavFlattened) ~= 0) and g.CurrentFocusScopeId or window.ID) window.NavRootFocusScopeId = g.CurrentFocusScopeId - -- Add to popup stacks: update OpenPopupStack data, push to BeginPopupStack + -- Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[] if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then local popup_ref = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1] popup_ref.Window = window @@ -9917,12 +11837,15 @@ function ImGui.Begin(name, open, flags) window.PopupId = popup_ref.PopupId end + -- Process SetNextWindow***() calls + -- (FIXME: Consider splitting the HasXXX flags into X/Y components) local window_pos_set_by_api = false local window_size_x_set_by_api = false local window_size_y_set_by_api = false if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) ~= 0 then window_pos_set_by_api = (bit32.band(window.SetWindowPosAllowFlags, g.NextWindowData.PosCond) ~= 0) if window_pos_set_by_api and ImLengthSqr(g.NextWindowData.PosPivotVal) > 1e-5 then + -- May be processed on the next frame if this is our first frame and we are measuring size -- FIXME: Look into removing the branch so everything can go through this same code path for consistency. ImVec2_Copy(window.SetWindowPosVal, g.NextWindowData.PosVal) ImVec2_Copy(window.SetWindowPosPivot, g.NextWindowData.PosPivotVal) @@ -9934,7 +11857,7 @@ function ImGui.Begin(name, open, flags) if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ~= 0 then window_size_x_set_by_api = (bit32.band(window.SetWindowSizeAllowFlags, g.NextWindowData.SizeCond) ~= 0) and (g.NextWindowData.SizeVal.x > 0.0) window_size_y_set_by_api = (bit32.band(window.SetWindowSizeAllowFlags, g.NextWindowData.SizeCond) ~= 0) and (g.NextWindowData.SizeVal.y > 0.0) - if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then + if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then -- Axis-specific conditions for BeginChild() g.NextWindowData.SizeVal.x = window.SizeFull.x end if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then @@ -9973,14 +11896,18 @@ function ImGui.Begin(name, open, flags) -- [EXPERIMENTAL] Skip Refresh mode ImGui.UpdateWindowSkipRefresh(window) + -- Nested root windows (typically tooltips) override disabled state if window_stack_data.DisabledOverrideReenable and window.RootWindow == window then ImGui.BeginDisabledOverrideReenable() end + -- We intentionally set g.CurrentWindow to nil to prevent usage until when the viewport is set, then will call SetCurrentWindow() g.CurrentWindow = nil + -- When reusing window again multiple times a frame, just append content (don't need to setup again) if first_begin_of_the_frame and not window.SkipRefresh then - local window_is_child_tooltip = (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0) + -- Initialize + local window_is_child_tooltip = (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0) -- FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) local window_just_appearing_after_hidden_for_resize = (window.HiddenFramesCannotSkipItems > 0) window.Active = true @@ -9993,16 +11920,22 @@ function ImGui.Begin(name, open, flags) window.DC.CurrentTableIdx = -1 if bit32.band(flags, ImGuiWindowFlags.DockNodeHost) ~= 0 then window.DrawList:ChannelsSplit(2) - window.DrawList:ChannelsSetCurrent(1) -- DOCKING_HOST_DRAW_CHANNEL_FG: render decorations on channel 1, backgrounds rendered manually later + window.DrawList:ChannelsSetCurrent(1) -- DOCKING_HOST_DRAW_CHANNEL_FG: Render decorations on channel 1 as we will render the backgrounds manually later end + -- Restore buffer capacity when woken from a compacted state, to avoid if window.MemoryCompacted then ImGui.GcAwakeTransientWindowBuffers(window) end -- UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS + -- Update contents size from last frame for auto-fitting (or use explicit size) CalcWindowContentSizes(window, window.ContentSize, window.ContentSizeIdeal) + + -- FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors + -- for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because + -- it has a single usage before this code block and may be set below before it is finally checked. if window.HiddenFramesCanSkipItems > 0 then window.HiddenFramesCanSkipItems = window.HiddenFramesCanSkipItems - 1 end @@ -10037,11 +11970,16 @@ function ImGui.Begin(name, open, flags) end -- SELECT VIEWPORT + -- We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes. + ImGui.WindowSelectViewport(window) ImGui.SetCurrentViewport(window, window.Viewport) SetCurrentWindow(window) flags = window.Flags + -- LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies) + -- We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style. + if not window.DockIsActive and bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then window.WindowBorderSize = style.ChildBorderSize else @@ -10074,25 +12012,29 @@ function ImGui.Begin(name, open, flags) window.TitleBarHeight = (bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0) and 0 or g.FontSize + g.Style.FramePadding.y * 2 - window.FontRefSize = g.FontSize -- Lock this to discourage calling window:CalcFontSize() outside of current window. + 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. local use_current_size_for_scrollbar_x = window_just_created local use_current_size_for_scrollbar_y = window_just_created if window_size_x_set_by_api and window.ContentSizeExplicit.x ~= 0.0 then use_current_size_for_scrollbar_x = true end - if window_size_y_set_by_api and window.ContentSizeExplicit.y ~= 0.0 then + if window_size_y_set_by_api and window.ContentSizeExplicit.y ~= 0.0 then -- #7252 use_current_size_for_scrollbar_y = true end -- Collapse window by double-clicking on title bar -- At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and bit32.band(flags, ImGuiWindowFlags.NoCollapse) == 0 and not window.DockIsActive then + -- We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), + -- so verify that we don't have items over the title bar. local title_bar_rect = window:TitleBarRect() if g.HoveredWindow == window and g.HoveredId == 0 and g.HoveredIdPreviousFrame == 0 and g.ActiveId == 0 and ImGui.IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) then if g.IO.MouseClickedCount[0] == 2 and ImGui.GetKeyOwner(ImGuiKey.MouseLeft) == ImGuiKeyOwner_NoOwner then window.WantCollapseToggle = true - ImGui.SetKeyOwner(ImGuiKey.MouseLeft, window.MoveId) + ImGui.SetKeyOwner(ImGuiKey.MouseLeft, window.MoveId) -- Claim input the same way ButtonBehavior() does. Prevent a same-frame move from triggering other items. (#9439) end end if window.WantCollapseToggle then @@ -10107,6 +12049,10 @@ function ImGui.Begin(name, open, flags) end window.WantCollapseToggle = false + -- SIZE + + -- Outer Decoration Sizes + -- (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations). local scrollbar_sizes_from_last_frame = ImVec2() ImVec2_Copy(scrollbar_sizes_from_last_frame, window.ScrollbarSizes) @@ -10167,6 +12113,7 @@ function ImGui.Begin(name, open, flags) end end + -- Apply minimum/maximum window size constraints and final size ImVec2_Copy(window.SizeFull, CalcWindowSizeAfterConstraint(window, window.SizeFull)) ImVec2_Copy(window.Size, (window.Collapsed and bit32.band(flags, ImGuiWindowFlags.ChildWindow) == 0) and window:TitleBarRect():GetSize() or window.SizeFull) @@ -10180,6 +12127,7 @@ function ImGui.Begin(name, open, flags) end end + -- Position child window if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then IM_ASSERT(parent_window and parent_window.Active) window.BeginOrderWithinParent = parent_window.DC.ChildWindows.Size @@ -10218,12 +12166,16 @@ function ImGui.Begin(name, open, flags) ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) end + -- Calculate the range of allowed position for that window (to be movable and visible past safe area padding) + -- When clamping to stay visible, we will enforce that window.Pos stays inside of visibility_rect. local viewport_rect = window.Viewport:GetMainRect() local viewport_work_rect = window.Viewport:GetWorkRect() local visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding) local visibility_rect = ImRect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding) -- Clamp position/size so window stays visible within its viewport or monitor + -- Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + -- FIXME: Similar to code in GetWindowAllowedExtentRect() if not window_pos_set_by_api and bit32.band(flags, ImGuiWindowFlags.ChildWindow) == 0 then if not window.ViewportOwned and viewport_rect:GetWidth() > 0 and viewport_rect:GetHeight() > 0.0 then local size_for_clamping_y = window.Size.y @@ -10236,6 +12188,7 @@ function ImGui.Begin(name, open, flags) end window.Pos.x = ImTrunc(window.Pos.x) window.Pos.y = ImTrunc(window.Pos.y) + -- Apply window focus (new and reactivated windows are moved to front) local want_focus = false if (window_just_activated_by_user and bit32.band(flags, ImGuiWindowFlags.NoFocusOnAppearing) == 0) then if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then @@ -10245,6 +12198,8 @@ function ImGui.Begin(name, open, flags) end end + -- Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) + -- Large values tend to lead to variety of artifacts and are not recommended. if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and not window.DockIsActive then window.WindowRounding = style.ChildRounding elseif window.RootWindowDockTree.ViewportOwned then @@ -10257,11 +12212,16 @@ function ImGui.Begin(name, open, flags) end end + -- Decide if we are going to handle borders and resize grips + -- '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. local handle_borders_and_resize_grips = (window.DockNodeAsHost ~= nil or not window.DockIsActive) if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and window.ParentWindow.SkipItems then handle_borders_and_resize_grips = false end + -- Handle manual resize: Resize Grips, Borders, Gamepad + -- Child windows can only be resized when they have the flags set. The resize grip allows resizing in both directions, so it should appear only if both flags are set. local border_hovered, border_held = -1, -1 local resize_grip_col = {0, 0, 0, 0} @@ -10273,7 +12233,7 @@ function ImGui.Begin(name, open, flags) resize_grip_count = 0 end else - resize_grip_count = g.IO.ConfigWindowsResizeFromEdges and 2 or 1 -- Allow resize from lower-left if we have the mouse cursor feedback for it. + resize_grip_count = g.IO.ConfigWindowsResizeFromEdges and 2 or 1 -- Allow resize from lower-left if we have the mouse cursor feedback for it. end local resize_grip_draw_size = ImTrunc(ImMax(g.FontSize * 1.10, g.Style.WindowRounding + 1.0 + g.FontSize * 0.2)) @@ -10307,12 +12267,13 @@ function ImGui.Begin(name, open, flags) -- Save last known viewport position within the window itself (so it can be saved in .ini file and restored) ImVec2_Copy(window.ViewportPos, window.Viewport.Pos) - --- SCROLLBAR VISIBILITY - -- Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size) + -- SCROLLBAR VISIBILITY + + -- Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). if not window.Collapsed then -- When reading the current size we need to read it after size constraints have been applied. -- Intentionally use previous frame values for InnerRect and ScrollbarSizes. - -- And when we use window.DecoOuterSizeY1 here it doesn't have ScrollbarSizes.y applied yet. + -- And when we use window.DecorationUp here it doesn't have ScrollbarSizes.y applied yet. local avail_size_from_current_frame = ImVec2(window.SizeFull.x, window.SizeFull.y - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2)) local avail_size_from_last_frame = window.InnerRect:GetSize() + scrollbar_sizes_from_last_frame local needed_size_from_last_frame = window_just_created and ImVec2(0, 0) or window.ContentSize + window.WindowPadding * 2.0 @@ -10350,11 +12311,20 @@ function ImGui.Begin(name, open, flags) window.ScrollbarSizes = ImVec2(window.ScrollbarY and style.ScrollbarSize or 0.0, window.ScrollbarX and style.ScrollbarSize or 0.0) - -- Amend the partially filled window.DecoOuterSizeX2 values. + -- Amend the partially filled window.DecorationXXX values. window.DecoOuterSizeX2 = window.DecoOuterSizeX2 + window.ScrollbarSizes.x window.DecoOuterSizeY2 = window.DecoOuterSizeY2 + window.ScrollbarSizes.y end + -- UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING) + -- Update various regions. Variables they depend on should be set above in this function. + -- We set this up after processing the resize grip so that our rectangles doesn't lag by a frame. + + -- Outer rectangle + -- Not affected by window border size. Used by: + -- - FindHoveredWindow() (w/ extra padding when border resize is enabled) + -- - Begin() initial clipping rect for drawing window background and borders. + -- - Begin() clipping whole child local host_rect if (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Popup) == 0 and not window_is_child_tooltip) then host_rect = parent_window.ClipRect @@ -10369,20 +12339,39 @@ function ImGui.Begin(name, open, flags) end window.OuterRectClipped:ClipWith(host_rect) + -- Inner rectangle + -- Not affected by window border size. Used by: + -- - InnerClipRect + -- - ScrollToRectEx() + -- - NavUpdatePageUpPageDown() + -- - Scrollbar() window.InnerRect.Min.x = window.Pos.x + window.DecoOuterSizeX1 window.InnerRect.Min.y = window.Pos.y + window.DecoOuterSizeY1 window.InnerRect.Max.x = window.Pos.x + window.Size.x - window.DecoOuterSizeX2 window.InnerRect.Max.y = window.Pos.y + window.Size.y - window.DecoOuterSizeY2 + -- Inner clipping rectangle. + -- - Extend a outside of normal work region up to borders. + -- - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. + -- - It also makes clipped items be more noticeable. + -- - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5 on left and right edge), see #3312 + -- - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + -- Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. + -- Affected by window/frame border size. Used by: + -- - Begin() initial clip rect local top_border_size = ((bit32.band(flags, ImGuiWindowFlags.MenuBar) ~= 0 or bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0) and style.FrameBorderSize or window.WindowBorderSize) + -- Try to match the fact that our border is drawn centered over the window rectangle, rather than inner. + -- This is why we do a *0.5 here. We don't currently even technically support large values for WindowBorderSize, + -- see e.g #7887 #7888, but may do after we move the window border to become an inner border (and then we can remove the 0.5 here). window.InnerClipRect.Min.x = ImFloor(0.5 + window.InnerRect.Min.x + window.WindowBorderSize * 0.5) window.InnerClipRect.Min.y = ImFloor(0.5 + window.InnerRect.Min.y + top_border_size * 0.5) window.InnerClipRect.Max.x = ImFloor(window.InnerRect.Max.x - window.WindowBorderSize * 0.5) window.InnerClipRect.Max.y = ImFloor(window.InnerRect.Max.y - window.WindowBorderSize * 0.5) window.InnerClipRect:ClipWithFull(host_rect) - --- Scrolling + -- SCROLLING + -- Lock down maximum scrolling -- The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate -- for right/bottom aligned items without creating a scrollbar. @@ -10394,10 +12383,16 @@ function ImGui.Begin(name, open, flags) ImVec2_CopyV(window.ScrollTarget, FLT_MAX, FLT_MAX) window.DecoInnerSizeX1 = 0.0; window.DecoInnerSizeY1 = 0.0 + -- DRAWING + + -- Setup draw list and outer clipping rectangle IM_ASSERT(window.DrawList.CmdBuffer.Size == 1 and window.DrawList.CmdBuffer.Data[1].ElemCount == 0) window.DrawList:PushTexture(g.Font.OwnerAtlas.TexRef) ImGui.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) + -- When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order. + -- FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493) local is_undocked_or_docked_visible = not window.DockIsActive or window.DockTabIsVisible if is_undocked_or_docked_visible then local render_decorations_in_parent = false @@ -10426,6 +12421,7 @@ function ImGui.Begin(name, open, flags) window.DrawList = parent_window.DrawList end + -- Handle title bar, scrollbar, resize grips and resize borders local window_to_highlight = g.NavWindowingTarget or g.NavWindow local title_bar_is_highlight = want_focus or (window_to_highlight ~= nil and (window.RootWindowForTitleBarHighlight == window_to_highlight.RootWindowForTitleBarHighlight or (window.DockNode ~= nil and window.DockNode == window_to_highlight.DockNode))) @@ -10436,6 +12432,13 @@ function ImGui.Begin(name, open, flags) end end + -- UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING) + + -- Work rectangle. + -- Affected by window padding and border size. Used by: + -- - Columns() for right-most edge + -- - TreeNode(), CollapsingHeader() for right-most edge + -- - BeginTabBar() for right-most edge local allow_scrollbar_x = (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) == 0) and (bit32.band(flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0) local allow_scrollbar_y = (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) == 0) @@ -10464,7 +12467,7 @@ function ImGui.Begin(name, open, flags) window.ParentWorkRect = window.WorkRect -- [LEGACY] Content Region - -- FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. + -- FIXME-OBSOLETE: window.ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. -- Unless explicit content size is specified by user, this currently represent the region leading to no scrolling. -- Used by: -- - Mouse wheel scrolling + many other things @@ -10474,7 +12477,7 @@ function ImGui.Begin(name, open, flags) window.ContentRegionRect.Max.y = window.ContentRegionRect.Min.y + (window.ContentSizeExplicit.y ~= 0.0 and window.ContentSizeExplicit.y or (window.Size.y - window.WindowPadding.y * 2.0 - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2))) -- Setup drawing context - -- (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) + -- (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window. and window.DC. is dubious.) window.DC.Indent.x = window.DecoOuterSizeX1 + window.WindowPadding.x - window.Scroll.x window.DC.GroupOffset.x = 0.0 window.DC.ColumnsOffset.x = 0.0 @@ -10530,7 +12533,7 @@ function ImGui.Begin(name, open, flags) end window.DC.ItemWidth = window.DC.ItemWidthDefault window.DC.ItemWidthStack:resize(0) - window.DC.TextWrapPos = -1.0 + window.DC.TextWrapPos = -1.0 -- Disabled window.DC.TextWrapPosStack:resize(0) if bit32.band(flags, ImGuiWindowFlags.Modal) ~= 0 then window.DC.ModalDimBgColor = ImGui.ColorConvertFloat4ToU32(ImGui.GetStyleColorVec4(ImGuiCol.ModalWindowDimBg)) @@ -10543,22 +12546,30 @@ function ImGui.Begin(name, open, flags) window.AutoFitFramesY = window.AutoFitFramesY - 1 end + -- Clear SetNextWindowXXX data (can aim to move this higher in the function) g.NextWindowData:ClearFlags() + -- Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) + -- We ImGuiFocusRequestFlags.UnlessBelowModal to: + -- - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed. + -- - Position window behind the modal that is not a begin-parent of this window. if want_focus then ImGui.FocusWindow(window, ImGuiFocusRequestFlags.UnlessBelowModal) end if want_focus and window == g.NavWindow then - ImGui.NavInitWindow(window, false) + ImGui.NavInitWindow(window, false) -- <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls end -- 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 then if g.NavWindow and g.NavWindow.RootWindow == window and g.ActiveId == 0 and ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.C)) then ImGui.LogToClipboard(0) end end + -- Title bar if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and not window.DockIsActive then open = 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, open) elseif bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and window.DockIsActive then @@ -10574,7 +12585,7 @@ function ImGui.Begin(name, open, flags) if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) ~= 0 then -- Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source. - -- We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it. + -- We need to do this _before_ we overwrite window.DC.LastItemId below because BeginDockableDragDropSource() also overwrites it. if g.MovingWindow == window and bit32.band(window.RootWindowDockTree.Flags, ImGuiWindowFlags.NoDocking) == 0 then ImGui.BeginDockableDragDropSource(window) end @@ -10589,12 +12600,17 @@ function ImGui.Begin(name, open, flags) end end + -- Set default BgClickFlags + -- This is set at the end of this function, so UpdateWindowManualResize()/ClampWindowPos() may use last-frame value if overridden by user code. + -- FIXME: The general intent is that we will later expose config options to default to enable scrolling + select scrolling mouse button. if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then window.BgClickFlags = parent_window.BgClickFlags else window.BgClickFlags = g.IO.ConfigWindowsMoveFromTitleBarOnly and ImGuiWindowBgClickFlags.None or ImGuiWindowBgClickFlags.Move end + -- 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 if ImGui.IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) then @@ -10602,10 +12618,12 @@ function ImGui.Begin(name, open, flags) end ImGui.SetLastItemDataForWindow(window, title_bar_rect) else + -- Skip refresh always mark active if (window.SkipRefresh) then SetWindowActiveForSkipRefresh(window) end + -- Append ImGui.SetCurrentViewport(window, window.Viewport) SetCurrentWindow(window) g.NextWindowData:ClearFlags() @@ -10620,12 +12638,17 @@ function ImGui.Begin(name, open, flags) dl._ScrollOriginX, dl._ScrollOriginY = window.Pos.x - window.Scroll.x, window.Pos.y - window.Scroll.y end + -- Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) window.WriteAccessed = false window.BeginCount = window.BeginCount + 1 g.NextWindowData:ClearFlags() + -- Update visibility if first_begin_of_the_frame and not window.SkipRefresh then -- When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. + -- This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. + -- This is analogous to regular windows being hidden from one frame. + -- It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed. if window.DockIsActive and not window.DockTabIsVisible then if window.LastFrameJustFocused == g.FrameCount then window.HiddenFramesCannotSkipItems = 1 @@ -10660,10 +12683,12 @@ function ImGui.Begin(name, open, flags) end end + -- Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) if style.Alpha <= 0.0 then window.HiddenFramesCanSkipItems = 1 end + -- Update the Hidden flag local hidden_regular = (window.HiddenFramesCanSkipItems > 0) or (window.HiddenFramesCannotSkipItems > 0) window.Hidden = hidden_regular or (window.HiddenFramesForRenderOnly > 0) @@ -10687,6 +12712,7 @@ function ImGui.Begin(name, open, flags) window.DC.NavLayersActiveMaskNext = window.DC.NavLayersActiveMask end elseif first_begin_of_the_frame then + -- Skip refresh mode window.SkipItems = true end @@ -10698,6 +12724,7 @@ function ImGui.End() local g = GImGui local window = g.CurrentWindow + -- Error checking: verify that user hasn't called End() too many times! if (g.CurrentWindowStack.Size <= 1 and g.WithinFrameScopeWithImplicitWindow) then IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!") @@ -10705,6 +12732,7 @@ function ImGui.End() end local window_stack_data = g.CurrentWindowStack:back() + -- Error checking: verify that user doesn't directly call End() on a child window. if bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then IM_ASSERT_USER_ERROR(g.WithinEndPopupID == window.ID, "Must call EndPopup() and not End()!") end @@ -10712,10 +12740,11 @@ function ImGui.End() IM_ASSERT_USER_ERROR(g.WithinEndChildID == window.ID, "Must call EndChild() and not End()!") end + -- Close anything that is open if window.DC.CurrentColumns then ImGui.EndColumns() end - if bit32.band(window.Flags, ImGuiWindowFlags.DockNodeHost) == 0 and not window.SkipRefresh then + if bit32.band(window.Flags, ImGuiWindowFlags.DockNodeHost) == 0 and not window.SkipRefresh then -- Pop inner window clip rectangle ImGui.PopClipRect() end ImGui.PopFocusScope() @@ -10744,7 +12773,7 @@ function ImGui.End() -- Docking: report contents sizes to parent to allow for auto-resize if window.DockNode and window.DockTabIsVisible then - local host_window = window.DockNode.HostWindow + local host_window = window.DockNode.HostWindow -- FIXME-DOCK if host_window then ImVec2_Copy(host_window.DC.CursorMaxPos, window.DC.CursorMaxPos + window.WindowPadding - host_window.WindowPadding) end @@ -10802,6 +12831,13 @@ function ImGui.PopItemFlag() g.CurrentItemFlags = g.ItemFlagsStack:back() end +-- BeginDisabled()/EndDisabled() +-- - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) +-- - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently. +-- - Feedback welcome at https://github.com/ocornut/imgui/issues/211 +-- - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions. +-- (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls) +-- - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags.Disabled) is currently NOT SUPPORTED. --- @param disabled? bool function ImGui.BeginDisabled(disabled) if disabled == nil then disabled = true end @@ -10810,12 +12846,12 @@ function ImGui.BeginDisabled(disabled) local was_disabled = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0 if not was_disabled and disabled then g.DisabledAlphaBackup = g.Style.Alpha - g.Style.Alpha = g.Style.Alpha * g.Style.DisabledAlpha + g.Style.Alpha = g.Style.Alpha * g.Style.DisabledAlpha -- PushStyleVar(ImGuiStyleVar.Alpha, g.Style.Alpha * g.Style.DisabledAlpha) end if was_disabled or disabled then g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.Disabled) end - g.ItemFlagsStack:push_back(g.CurrentItemFlags) + g.ItemFlagsStack:push_back(g.CurrentItemFlags) -- FIXME-OPT: can we simply skip this and use DisabledStackSize? g.DisabledStackSize = g.DisabledStackSize + 1 end @@ -10824,13 +12860,17 @@ function ImGui.EndDisabled() IM_ASSERT_USER_ERROR_RET(g.DisabledStackSize > 0, "Calling EndDisabled() too many times!") g.DisabledStackSize = g.DisabledStackSize - 1 local was_disabled = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0 + -- PopItemFlag() g.ItemFlagsStack:pop_back() g.CurrentItemFlags = g.ItemFlagsStack:back() if was_disabled and bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) == 0 then - g.Style.Alpha = g.DisabledAlphaBackup + g.Style.Alpha = g.DisabledAlphaBackup -- PopStyleVar() end end +-- Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name. +-- Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal. +-- The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled(). function ImGui.BeginDisabledOverrideReenable() local g = GImGui IM_ASSERT(bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0) @@ -10851,6 +12891,12 @@ function ImGui.EndDisabledOverrideReenable() g.Style.Alpha = g.CurrentWindowStack:back().DisabledOverrideReenableAlphaBackup end +-- Find window given position, search front-to-back +-- - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow. +-- - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically +-- with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is +-- called, aka before the next Begin(). Moving window isn't affected. +-- - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here. --- @param pos ImVec2 --- @param find_first_and_in_any_viewport bool --- @return ImGuiWindow, ImGuiWindow? @@ -10889,6 +12935,8 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) if (window.Viewport ~= g.MouseViewport) then break end + + -- Using the clipped AABB, a child window will typically be clipped by its parent (not always) local hit_padding if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.NoResize, ImGuiWindowFlags.AlwaysAutoResize)) ~= 0 then hit_padding = padding_regular @@ -10899,6 +12947,8 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) break end + -- Support for one rectangular hole in any given window + -- FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512) if window.HitTestHoleSize.x ~= 0 then local hx, hy = window.Pos.x + window.HitTestHoleOffset.x, window.Pos.y + window.HitTestHoleOffset.y if pos.x >= hx and pos.y >= hy and pos.x < hx + window.HitTestHoleSize.x and pos.y < hy + window.HitTestHoleSize.y then @@ -10935,26 +12985,37 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) end -- TODO: +-- 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) function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) local g = GImGui local 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.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. local clear_hovered_windows = false g.HoveredWindow, g.HoveredWindowUnderMovingWindow = FindHoveredWindowEx(mouse_pos, false) IM_ASSERT(g.HoveredWindow == nil or g.HoveredWindow == g.MovingWindow or g.HoveredWindow.Viewport == g.MouseViewport) g.HoveredWindowBeforeClear = g.HoveredWindow + -- Modal windows prevents mouse from hovering behind them. local modal_window = ImGui.GetTopMostPopupModal() - if modal_window and g.HoveredWindow and not ImGui.IsWindowWithinBeginStackOf(g.HoveredWindow.RootWindow, modal_window) then + if modal_window and g.HoveredWindow and not ImGui.IsWindowWithinBeginStackOf(g.HoveredWindow.RootWindow, modal_window) then -- FIXME-MERGE: RootWindowDockTree ? clear_hovered_windows = true end + -- Disabled mouse hovering (we don't currently clear MousePos, we could) if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoMouse) ~= 0 then clear_hovered_windows = true end + -- We track click ownership. When clicked outside of a window the click is owned by the application and + -- won't report hovering nor request capture even while dragging over our windows afterward. local has_open_popup = (g.OpenPopupStack.Size > 0) local has_open_modal = (modal_window ~= nil) local mouse_earliest_down = -1 @@ -10967,7 +13028,7 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) end mouse_any_down = mouse_any_down or io.MouseDown[i] - if (io.MouseDown[i] or io.MouseReleased[i]) then + if (io.MouseDown[i] or io.MouseReleased[i]) then -- Increase release frame for our evaluation of earliest button (#1392) if (mouse_earliest_down == -1 or (io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])) then mouse_earliest_down = i end @@ -10977,6 +13038,8 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) local mouse_avail = (mouse_earliest_down == -1) or io.MouseDownOwned[mouse_earliest_down] local mouse_avail_unless_popup_close = (mouse_earliest_down == -1) or io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down] + -- If mouse was first clicked outside of ImGui bounds we also cancel out hovering. + -- FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) local mouse_dragging_extern_payload = g.DragDropActive and bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceExtern) ~= 0 if not mouse_avail and not mouse_dragging_extern_payload then clear_hovered_windows = true @@ -10987,6 +13050,8 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) g.HoveredWindowUnderMovingWindow = nil end + -- Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app) + -- Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag if (g.WantCaptureMouseNextFrame ~= -1) then io.WantCaptureMouse = (g.WantCaptureMouseNextFrame ~= 0) io.WantCaptureMouseUnlessPopupClose = io.WantCaptureMouse @@ -10995,6 +13060,7 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close and (g.HoveredWindow ~= nil or mouse_any_down)) or has_open_modal end + -- Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app) io.WantCaptureKeyboard = false if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoKeyboard) == 0 then if (g.ActiveId ~= 0) or (modal_window ~= nil) then @@ -11003,10 +13069,11 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) io.WantCaptureKeyboard = true end end - if g.WantCaptureKeyboardNextFrame ~= -1 then + if g.WantCaptureKeyboardNextFrame ~= -1 then -- Manual override io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame ~= 0) end + -- Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible io.WantTextInput = (g.WantTextInputNextFrame ~= -1) and (g.WantTextInputNextFrame ~= 0) or false end @@ -11020,8 +13087,10 @@ function ImGui.UpdateAliasKey(key, v, analog_value) key_data.AnalogValue = analog_value end +-- [Internal] Do not use directly function ImGui.GetMergedModsFromKeys() local g = GImGui + -- Bypass IsKeyDown() for the unlikely case where user used a ImGuiInputFlags.LockXXXX on those. local mods = 0 if ImGui.GetKeyData(g, ImGuiMod_Ctrl).Down then mods = bit32.bor(mods, ImGuiMod_Ctrl) end @@ -11040,13 +13109,17 @@ function ImGui.UpdateKeyboardInputs() io:ClearInputKeys() end + -- Update aliases for n = 0, 2 do -- TODO: ImGuiMouseButton.COUNT - 1 ImGui.UpdateAliasKey(ImGui.MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] and 1.0 or 0.0) end ImGui.UpdateAliasKey(ImGuiKey.MouseWheelX, io.MouseWheelH ~= 0.0, io.MouseWheelH) ImGui.UpdateAliasKey(ImGuiKey.MouseWheelY, io.MouseWheel ~= 0.0, io.MouseWheel) - -- Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values + -- Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values. + -- - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array. + -- - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array. + -- So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing. local prev_key_mods = io.KeyMods io.KeyMods = ImGui.GetMergedModsFromKeys() io.KeyCtrl = bit32.band(io.KeyMods, ImGuiMod_Ctrl) ~= 0 @@ -11102,6 +13175,7 @@ function ImGui.UpdateKeyboardInputs() owner_data.LockUntilRelease = owner_data.LockUntilRelease and key_data.Down -- Clear LockUntilRelease when key is not Down anymore end + -- Update key routing (for e.g. shortcuts) ImGui.UpdateKeyRoutingTable(g.KeysRoutingTable) end @@ -11111,7 +13185,9 @@ function ImGui.UpdateMouseInputs() -- Mouse Wheel swapping flag -- As a standard behavior holding Shift while using Vertical Mouse Wheel triggers Horizontal scroll instead - -- - We avoid doing it on OSX as it the OS input layer handles this already + -- - We avoid doing it on OSX as it the OS input layer handles this already. + -- - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature. + -- - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source. io.MouseWheelRequestAxisSwap = io.KeyShift and not io.ConfigMacOSXBehaviors -- Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well) @@ -11130,13 +13206,14 @@ function ImGui.UpdateMouseInputs() io.MouseDelta = ImVec2(0.0, 0.0) end - -- Update stationary timer - -- FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates - local mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource.Mouse) and 2.0 or 3.0 + -- Update stationary timer. + -- FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates. + local mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource.Mouse) and 2.0 or 3.0 -- Slightly higher threshold for ImGuiMouseSource.TouchScreen/ImGuiMouseSource.Pen, may need rework. local mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold) g.MouseStationaryTimer = mouse_stationary and (g.MouseStationaryTimer + io.DeltaTime) or 0.0 + -- IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer) - -- If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0 threshold but would need to reset in everywhere we set this to true. + -- If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true. if io.MouseDelta.x ~= 0.0 or io.MouseDelta.y ~= 0.0 then g.NavHighlightItemUnderNav = false end @@ -11198,8 +13275,10 @@ function ImGui.UpdateMouseInputs() io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, (delta_from_click_pos.y < 0.0) and -delta_from_click_pos.y or delta_from_click_pos.y) end + -- We provide io.MouseDoubleClicked[] as a legacy service io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2) + -- Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation if (io.MouseClicked[i]) then g.NavHighlightItemUnderNav = false end @@ -11230,6 +13309,7 @@ end --- @param wheel ImVec2 --- @return ImGuiWindow? local function FindBestWheelingWindow(wheel) + -- For each axis, find window in the hierarchy that may want to use scrolling local g = GImGui local windows = {nil, nil} for axis = ImGuiAxis.X, ImGuiAxis.Y do @@ -11237,10 +13317,15 @@ local function FindBestWheelingWindow(wheel) windows[axis] = g.HoveredWindow local window = g.HoveredWindow while bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 do + -- Bubble up into parent window if: + -- - a child window doesn't allow any scrolling. + -- - a child window has the ImGuiWindowFlags.NoScrollWithMouse flag. + -- -- - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP) local has_scrolling = (window.ScrollMax[axis] ~= 0.0) local inputs_disabled = (bit32.band(window.Flags, ImGuiWindowFlags.NoScrollWithMouse) ~= 0) and not (bit32.band(window.Flags, ImGuiWindowFlags.NoMouseInputs) ~= 0) + -- local scrolling_past_limits = (wheel_v < 0.0) and (window.Scroll[axis] <= 0.0) or (window.Scroll[axis] >= window.ScrollMax[axis]) - if has_scrolling and not inputs_disabled then + if has_scrolling and not inputs_disabled then -- and not scrolling_past_limits break -- select this window end @@ -11253,10 +13338,14 @@ local function FindBestWheelingWindow(wheel) return nil end + -- If there's only one window or only one axis then there's no ambiguity if (windows[1] == windows[2] or windows[1] == nil or windows[2] == nil) then return windows[2] and windows[2] or windows[1] end + -- If candidate are different windows we need to decide which one to prioritize + -- - First frame: only find a winner if one axis is zero. + -- - Subsequent frames: only find a winner when one is more than the other. if (g.WheelingWindowStartFrame == -1) then g.WheelingWindowStartFrame = g.FrameCount end @@ -11268,7 +13357,10 @@ local function FindBestWheelingWindow(wheel) return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) and windows[1] or windows[2] end +-- Called by NewFrame() function ImGui.UpdateMouseWheel() + -- Reset the locked window if we move the mouse or after the timer elapses. + -- FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795) local g = GImGui if g.WheelingWindow ~= nil then g.WheelingWindowReleaseTimer = g.WheelingWindowReleaseTimer - g.IO.DeltaTime @@ -11290,13 +13382,14 @@ function ImGui.UpdateMouseWheel() local wheel = ImVec2() wheel.x = ImGui.TestKeyOwner(ImGuiKey.MouseWheelX, owner_id) and g.IO.MouseWheelH or 0.0 wheel.y = ImGui.TestKeyOwner(ImGuiKey.MouseWheelY, owner_id) and g.IO.MouseWheel or 0.0 + -- IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y) if g.WheelingWindow ~= nil then ImGui.SetKeyOwner(ImGuiKey.MouseWheelX, owner_id) ImGui.SetKeyOwner(ImGuiKey.MouseWheelY, owner_id) end -- Zoom / Scale window - -- FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned + -- FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. if wheel.y ~= 0.0 and g.IO.KeyCtrl and g.IO.FontAllowUserScaling then LockWheelingWindow(mouse_window, wheel.y) local window = mouse_window @@ -11315,6 +13408,7 @@ function ImGui.UpdateMouseWheel() end -- Mouse wheel scrolling + -- Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs() if (g.IO.MouseWheelRequestAxisSwap) then wheel = ImVec2(wheel.y, 0.0) end @@ -11324,7 +13418,7 @@ function ImGui.UpdateMouseWheel() g.WheelingAxisAvg.x = ImStd.ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30) g.WheelingAxisAvg.y = ImStd.ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30) - -- In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now + -- In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now. wheel = wheel + g.WheelingWindowWheelRemainder g.WheelingWindowWheelRemainder = ImVec2(0.0, 0.0) if (wheel.x == 0.0 and wheel.y == 0.0) then @@ -11367,6 +13461,8 @@ function ImGui.UpdateMouseWheel() end end +-- Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. +-- FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! local function SetupDrawListSharedData() local g = GImGui local virtual_space = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX) @@ -11397,7 +13493,7 @@ local function InitViewportDrawData(viewport) local g = GImGui local draw_data = viewport.DrawDataP - viewport.DrawData = draw_data + viewport.DrawData = draw_data -- Make publicly accessible viewport.DrawDataBuilder.Layers[1] = draw_data.CmdLists viewport.DrawDataBuilder.Layers[2] = viewport.DrawDataBuilder.LayerData1 viewport.DrawDataBuilder.Layers[1]:resize(0) @@ -11430,7 +13526,7 @@ local function InitViewportDrawData(viewport) draw_data.Textures = g.PlatformIO.Textures end --- FIXME-DPI: +-- FIXME-DPI: PLEASE DO NOT USE. I don't want to formalize this just yet. Because reasons. function ImGui.GetScale() local g = GImGui return g.Style._MainScale @@ -11450,6 +13546,14 @@ function ImGui.GetCurrentWindow() return g.CurrentWindow end +-- Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. +-- - When using this function it is sane to ensure that float are perfectly rounded to integer values, +-- so that e.g. (int)(max.x-min.x) in user's render produce correct result. +-- - 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 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. --- @param clip_rect_min ImVec2 --- @param clip_rect_max ImVec2 --- @param intersect_with_current_clip_rect? bool @@ -11471,6 +13575,7 @@ end --- @param drawlist_name string --- @return ImDrawList local function GetViewportBgFgDrawList(viewport, drawlist_no, drawlist_name) + -- Create the draw list on demand, because they are not frequently used for all viewports local g = GImGui IM_ASSERT(drawlist_no <= 2) -- IM_COUNTOF(viewport->BgFgDrawLists) local draw_list = viewport.BgFgDrawLists[drawlist_no] @@ -11480,6 +13585,7 @@ local function GetViewportBgFgDrawList(viewport, drawlist_no, drawlist_name) viewport.BgFgDrawLists[drawlist_no] = draw_list end + -- Our ImDrawList system requires that there is always a command if viewport.BgFgDrawListsLastTimeActive[drawlist_no] ~= g.Time then draw_list:_ResetForNewFrame() draw_list:PushTexture(g.IO.Fonts.TexRef) @@ -11514,7 +13620,7 @@ function ImGui.GetForegroundDrawList(viewport) return GetViewportBgFgDrawList(viewport, 2, "##Foreground") end --- FIXME: Add a more explicit sort order in the window structure +-- FIXME: Add a more explicit sort order in the window structure. --- @param lhs ImGuiWindow --- @param rhs ImGuiWindow local function ChildWindowComparer(lhs, rhs) @@ -11551,7 +13657,7 @@ local function AddWindowToDrawData(window, layer) local viewport = window.Viewport g.IO.MetricsRenderWindows = g.IO.MetricsRenderWindows + 1 if window.DrawList._Splitter._Count > 1 then - window.DrawList:ChannelsMerge() -- Merge if user forgot to merge back. Also required for DockNodeHost windows. + window.DrawList:ChannelsMerge() -- Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags.DockNodeHost windows. end ImGui.AddDrawListToDrawDataEx(viewport.DrawDataP, viewport.DrawDataBuilder.Layers[layer], window.DrawList) for _, child in window.DC.ChildWindows:iter() do @@ -11566,6 +13672,7 @@ local function GetWindowDisplayLayer(window) return (bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0) and 2 or 1 end +-- Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu) --- @param window ImGuiWindow local function AddRootWindowToDrawData(window) AddWindowToDrawData(window, GetWindowDisplayLayer(window)) @@ -11613,6 +13720,7 @@ function ImGui.NewFrame() g.WindowsActiveCount = 0 g.MenusIdSubmittedThisFrame:resize(0) + -- Calculate frame-rate for the user, as a purely luxurious feature -- FIXME: are lines below correct and necessary g.FramerateSecPerFrameAccum = g.FramerateSecPerFrameAccum + (g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]) g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime @@ -11624,12 +13732,16 @@ function ImGui.NewFrame() g.IO.Framerate = FLT_MAX end + -- Process input queue (trickle as many events as possible), turn events into writes to IO structure ImGui.UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue) + -- Update viewports (after processing input queue, so io.MouseHoveredViewport is set) ImGui.UpdateViewportsNewFrame() + -- Update texture list (collect destroyed textures, etc.) ImGui.UpdateTexturesNewFrame() + -- Setup current font and draw list shared data SetupDrawListSharedData() ImGui.UpdateFontsNewFrame() @@ -11641,11 +13753,13 @@ function ImGui.NewFrame() viewport.DrawDataP.Valid = false end + -- Drag and drop keep the source ID alive so even if the source disappear our state is consistent if g.DragDropActive and g.DragDropPayload.SourceId == g.ActiveId then ImGui.KeepAliveID(g.DragDropPayload.SourceId) end - if not g.IO.ConfigDebugHighlightIdConflicts or not g.IO.KeyCtrl then + -- [DEBUG] + if not g.IO.ConfigDebugHighlightIdConflicts or not g.IO.KeyCtrl then -- Count is locked while holding Ctrl g.DebugDrawIdConflictsId = 0 end if g.IO.ConfigDebugHighlightIdConflicts and g.HoveredIdPreviousFrameItemCount > 1 then @@ -11671,6 +13785,9 @@ function ImGui.NewFrame() g.HoveredIdAllowOverlap = false g.HoveredIdIsDisabled = false + -- Clear ActiveID if the item is not alive anymore. + -- In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd(). + -- As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves. if (g.ActiveId ~= 0 and g.ActiveIdIsAlive ~= g.ActiveId and g.ActiveIdPreviousFrame == g.ActiveId) then IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() 0x%08X because it isn't marked alive anymore!", g.ActiveId) @@ -11740,8 +13857,18 @@ function ImGui.NewFrame() end end + -- Close popups on focus lost (currently wip/opt-in) + -- if (g.IO.AppFocusLost) + -- ClosePopupsExceptModals(); + + -- Update keyboard input state ImGui.UpdateKeyboardInputs() + -- IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl)); + -- IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift)); + -- IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt)); + -- IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper)); + -- Drag and drop g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr g.DragDropAcceptIdCurr = 0 @@ -11752,6 +13879,10 @@ function ImGui.NewFrame() g.DragDropWithinTarget = false g.DragDropHoldJustPressedId = 0 if g.DragDropActive then + -- Also works when g.ActiveId==0 (aka leftover payload in progress, no active id) + -- You may disable this externally by hijacking the input route: + -- 'if (GetDragDropPayload() ~= nil) then Shortcut(ImGuiKey.Escape, ImGuiInputFlags.RouteGlobal | ImGuiInputFlags.RouteOverActive) end + -- but you will not get a return value from Shortcut() due to ActiveIdUsingAllKeyboardKeys logic. You can however poll IsKeyPressed(ImGuiKey.Escape) afterwards. local owner_id = (g.ActiveId ~= 0) and g.ActiveId or ImHashStr("##DragDropCancelHandler") if ImGui.Shortcut(ImGuiKey.Escape, ImGuiInputFlags.RouteGlobal, owner_id) then ImGui.ClearActiveID() @@ -11760,14 +13891,17 @@ function ImGui.NewFrame() end g.TooltipPreviousWindow = nil + -- Update keyboard/gamepad navigation ImGui.NavUpdate() + -- Update mouse input state ImGui.UpdateMouseInputs() -- Undocking -- (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame) ImGui.DockContextNewFrameUpdateUndocking(g) + -- Mark all windows as not visible and compact unused memory. IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size) local gc_all = g.GcCompactAll or g.IO.ConfigMemoryCompactTimer < 0.0 local memory_compact_start_time = gc_all and FLT_MAX or (g.Time - g.IO.ConfigMemoryCompactTimer) @@ -11779,13 +13913,18 @@ function ImGui.NewFrame() window.BeginCountPreviousFrame = window.BeginCount window.BeginCount = 0 + -- Garbage collect transient buffers of recently unused windows if (not window.WasActive or gc_all) and not window.MemoryCompacted and window.LastTimeActive < memory_compact_start_time then ImGui.GcCompactTransientWindowBuffers(window) end end + -- 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) ImGui.UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos) + -- Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) ImGui.UpdateMouseMovingWindowNewFrame() -- Background darkening/whitening @@ -11805,6 +13944,7 @@ function ImGui.NewFrame() g.PlatformImeData.WantVisible = false g.PlatformImeData.WantTextInput = false + -- Mouse wheel scrolling, scale ImGui.UpdateMouseWheel() -- Garbage collect transient buffers of recently unused tables @@ -11824,14 +13964,17 @@ function ImGui.NewFrame() end g.GcCompactAll = false + -- Closing the focused window restore focus to the first active root window in descending z-order if (g.NavWindow and not g.NavWindow.WasActive) then ImGui.FocusTopMostWindowUnderOne(nil, nil, nil, ImGuiFocusRequestFlags.RestoreFocusedChild) end + -- No window should be open at the beginning of the frame. + -- But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack:resize(0) g.BeginPopupStack:resize(0) g.ItemFlagsStack:resize(0) - g.ItemFlagsStack:push_back(ImGuiItemFlags.Default_) + g.ItemFlagsStack:push_back(ImGuiItemFlags.Default_) -- Default flags g.CurrentItemFlags = g.ItemFlagsStack:back() g.GroupStack:resize(0) @@ -11841,6 +13984,9 @@ function ImGui.NewFrame() -- Docking ImGui.DockContextNewFrameUpdateDocking(g) + -- Create implicit/fallback window - which we will only render it if the user has added something to it. + -- We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. + -- This fallback is particularly important as it prevents ImGui:: calls from crashing. g.WithinFrameScopeWithImplicitWindow = true ImGui.SetNextWindowSize(ImVec2(400, 400), ImGuiCond.FirstUseEver) ImGui.Begin("Debug##Default") @@ -11852,10 +13998,12 @@ function ImGui.NewFrame() ImGui.ErrorRecoveryStoreState(g.StackSizesInNewFrame) end +-- This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. function ImGui.EndFrame() local g = GImGui IM_ASSERT(g.Initialized) + -- Don't process EndFrame() multiple times. if g.FrameCountEnded == g.FrameCount then return end @@ -11867,7 +14015,7 @@ function ImGui.EndFrame() end ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() - -- Notify Platform when our Input Method Editor cursor has moved + -- Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) local ime_data = g.PlatformImeData if g.PlatformIO.Platform_SetImeDataFn ~= nil and not ImGuiPlatformImeData_Compare(ime_data, g.PlatformImeDataPrev) then local viewport = ImGui.FindViewportByID(ime_data.ViewportId) @@ -11879,6 +14027,7 @@ function ImGui.EndFrame() end g.WantTextInputNextFrame = ime_data.WantTextInput + -- Hide implicit/fallback "Debug" window if it hasn't been used g.WithinFrameScopeWithImplicitWindow = false if (g.CurrentWindow and g.CurrentWindow.IsFallbackWindow and g.CurrentWindow.WriteAccessed == false) then g.CurrentWindow.Active = false @@ -11911,14 +14060,19 @@ function ImGui.EndFrame() g.DragDropWithinSource = false end + -- End frame g.WithinFrameScope = false g.FrameCountEnded = g.FrameCount ImGui.UpdateFontsEndFrame() + -- Initiate moving window + handle left-click and right-click focus ImGui.UpdateMouseMovingWindowEndFrame() + -- Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) ImGui.UpdateViewportsEndFrame() + -- Sort the window list so that all child windows are after their parent + -- We cannot do that on FocusWindow() because children may not exist yet g.WindowsTempSortBuffer:resize(0) g.WindowsTempSortBuffer:reserve(g.Windows.Size) for _, window in g.Windows:iter() do @@ -11932,16 +14086,19 @@ function ImGui.EndFrame() until true end + -- This usually assert if there is a mismatch between the ImGuiWindowFlags.ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong. IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size) g.Windows:swap(g.WindowsTempSortBuffer) g.IO.MetricsActiveWindows = g.WindowsActiveCount ImGui.UpdateTexturesEndFrame() + -- Unlock font atlas for _, atlas in g.FontAtlases:iter() do atlas.Locked = false end + -- Clear Input data for next frame ImVec2_Copy(g.IO.MousePosPrev, g.IO.MousePos) g.IO.AppFocusLost = false g.IO.MouseWheel = 0.0 @@ -11950,6 +14107,9 @@ function ImGui.EndFrame() end -- TODO: +-- Prepare the data for rendering so you can call GetDrawData() +-- (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) function ImGui.Render() local g = GImGui IM_ASSERT(g.Initialized) @@ -11962,6 +14122,7 @@ function ImGui.Render() g.IO.MetricsRenderWindows = 0 + -- Add background ImDrawList (for each active viewport) for _, viewport in g.Viewports:iter() do InitViewportDrawData(viewport) if viewport.BgFgDrawLists[1] ~= nil and viewport.BgFgDrawListsLastTimeActive[1] == g.Time then @@ -11969,8 +14130,10 @@ function ImGui.Render() end end + -- Draw modal/window whitening backgrounds ImGui.RenderDimmedBackgrounds() + -- Add ImDrawList to render local windows_to_render_top_most = {nil, nil} windows_to_render_top_most[1] = (g.NavWindowingTarget and (bit32.band(g.NavWindowingTarget.Flags, ImGuiWindowFlags.NoBringToFrontOnFocus) == 0)) and g.NavWindowingTarget.RootWindowDockTree or nil windows_to_render_top_most[2] = g.NavWindowingTarget and g.NavWindowingListWindow or nil @@ -11990,15 +14153,18 @@ function ImGui.Render() ImGui.RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48)) end + -- Setup ImDrawData structures for end-user g.IO.MetricsRenderVertices = 0 g.IO.MetricsRenderIndices = 0 for _, viewport in g.Viewports:iter() do FlattenDrawDataIntoSingleLayer(viewport.DrawDataBuilder) + -- Add foreground ImDrawList (for each active viewport) if viewport.BgFgDrawLists[2] ~= nil and viewport.BgFgDrawListsLastTimeActive[2] == g.Time then ImGui.AddDrawListToDrawDataEx(viewport.DrawDataP, viewport.DrawDataBuilder.Layers[1], ImGui.GetForegroundDrawList(viewport)) end + -- We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch). local draw_data = viewport.DrawDataP for _, draw_list in draw_data.CmdLists:iter() do draw_list:_PopUnusedDrawCmd() @@ -12009,6 +14175,8 @@ function ImGui.Render() end end +-- Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. +-- CalcTextSize("") should return ImVec2(0.0, g.FontSize) --- @param text ImString --- @param text_end? int # Exclusive upper bound --- @param hide_text_after_double_hash? bool @@ -12034,7 +14202,7 @@ function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double local text_display_end if hide_text_after_double_hash then - text_display_end = ImGui.FindRenderedTextEnd(text, text_end) + text_display_end = ImGui.FindRenderedTextEnd(text, text_end) -- Hide anything after a '##' string else text_display_end = text_end end @@ -12046,11 +14214,15 @@ function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double end local text_size = font:CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_begin, text_display_end, nil) + -- Round + -- (see 7b0bf230, 4622fa4b6, #791 for details about this.) + -- FIXME: Add a way to disable this. text_size.x = ImCeilFast(text_size.x) return text_size end +-- Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() function ImGui.GetDrawData() local g = GImGui local viewport = g.Viewports[1] @@ -12061,6 +14233,7 @@ function ImGui.GetTime() return GImGui.Time end +-- This function is merely here to free heap allocations. function ImGui.Shutdown() local g = GImGui IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == nil, "Forgot to shutdown Platform backend?") @@ -12070,6 +14243,7 @@ function ImGui.Shutdown() IM_ASSERT_USER_ERROR(viewport.RendererUserData == nil and viewport.PlatformUserData == nil and viewport.PlatformHandle == nil, "Backend or app forgot to call DestroyPlatformWindows()?") end + -- 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) for _, atlas in g.FontAtlases:iter() do ImGui.UnregisterFontAtlas(atlas) if atlas.OwnerContext == g then @@ -12081,16 +14255,20 @@ function ImGui.Shutdown() end g.DrawListSharedData.TempBuffer:clear() + -- Shutdown extensions ImGui.DockContextShutdown(g) + -- Cleanup of other data are conditional on actually having initialized Dear ImGui. if not g.Initialized then return end -- TODO: + -- Clear everything else g.MenusIdSubmittedThisFrame:clear() end +-- A conformant backend should return nil on failure (e.g. clipboard data is not text). --- @return string? function ImGui.GetClipboardText() local g = GImGui @@ -12113,17 +14291,29 @@ function ImGui.GetPlatformIO() return GImGui.PlatformIO end +-- Get desired mouse cursor shape. +-- Important: this is meant to be used by a platform backend, it is reset in ImGui.NewFrame(), +-- updated during the frame, and locked in EndFrame()/Render(). +-- If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you function ImGui.GetMouseCursor() local g = GImGui return g.MouseCursor end +-- We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value. +-- Custom cursors may be handled by custom backends. If you are using a standard backend and want to hack in a custom cursor, you may +-- handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags.NoMouseCursorChange during the backend _NewFrame() call. --- @param cursor_type ImGuiMouseCursor function ImGui.SetMouseCursor(cursor_type) local g = GImGui g.MouseCursor = cursor_type end +------------------------------------------------------------------------------- +-- [SECTION] MISC HELPERS/UTILITIES (Color functions) +-- Note: The Convert functions are early design which are not consistent with other API. +------------------------------------------------------------------------------- + --- @param col_a ImU32 --- @param col_b ImU32 --- @return ImU32 @@ -12161,6 +14351,8 @@ function ImGui.ColorConvertFloat4ToU32(in_col) return bit32.bor(F32ToU8Sat(in_col.x), bit32.lshift(F32ToU8Sat(in_col.y), 8), bit32.lshift(F32ToU8Sat(in_col.z), 16), bit32.lshift(F32ToU8Sat(in_col.w), 24)) end +-- Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 +-- Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv --- @param r float --- @param g float --- @param b float @@ -12184,6 +14376,8 @@ function ImGui.ColorConvertRGBtoHSV(r, g, b) return out_h, out_s, out_v end +-- Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 +-- also http://en.wikipedia.org/wiki/HSL_and_HSV --- @param h float --- @param s float --- @param v float @@ -12217,6 +14411,7 @@ function ImGui.ColorConvertHSVtoRGB(h, s, v) end end +-- Generic helper, equivalent to old ImGui.CalcListClipping() but stateless --- @param clip_rect ImRect --- @param pos ImVec2 --- @param items_height float @@ -12226,9 +14421,9 @@ function ImGui.CalcClipRectVisibleItemsY(clip_rect, pos, items_height) return visible_start + 1, visible_end + 1 end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] STYLING ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.GetStyle() IM_ASSERT(GImGui ~= nil, "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?") @@ -12273,6 +14468,7 @@ end end +-- FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32 --- @param idx ImGuiCol --- @param col ImU32|ImVec4 function ImGui.PushStyleColor(idx, col) @@ -12307,57 +14503,57 @@ function ImGui.PopStyleColor(count) end local GStyleVarsInfo = { - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "Alpha"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DisabledAlpha"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowPadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowMinSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowTitleAlign"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "FramePadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemSpacing"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemInnerSpacing"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "IndentSpacing"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "CellPadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarPadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabMinSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthBase"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthShrink"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarOverlineSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TableAngledHeadersAngle"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "TableAngledHeadersTextAlign"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "MenuItemRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SelectableRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DragDropTargetRounding"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ButtonTextAlign"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SelectableTextAlign"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorTextBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextAlign"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextPadding") + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "Alpha"), -- ImGuiStyleVar.Alpha + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DisabledAlpha"), -- ImGuiStyleVar.DisabledAlpha + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowPadding"), -- ImGuiStyleVar.WindowPadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowRounding"), -- ImGuiStyleVar.WindowRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowBorderSize"), -- ImGuiStyleVar.WindowBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowMinSize"), -- ImGuiStyleVar.WindowMinSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowTitleAlign"), -- ImGuiStyleVar.WindowTitleAlign + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildRounding"), -- ImGuiStyleVar.ChildRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildBorderSize"), -- ImGuiStyleVar.ChildBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupRounding"), -- ImGuiStyleVar.PopupRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupBorderSize"), -- ImGuiStyleVar.PopupBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "FramePadding"), -- ImGuiStyleVar.FramePadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameRounding"), -- ImGuiStyleVar.FrameRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameBorderSize"), -- ImGuiStyleVar.FrameBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemSpacing"), -- ImGuiStyleVar.ItemSpacing + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemInnerSpacing"), -- ImGuiStyleVar.ItemInnerSpacing + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "IndentSpacing"), -- ImGuiStyleVar.IndentSpacing + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "CellPadding"), -- ImGuiStyleVar.CellPadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarSize"), -- ImGuiStyleVar.ScrollbarSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarRounding"), -- ImGuiStyleVar.ScrollbarRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarPadding"), -- ImGuiStyleVar.ScrollbarPadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabMinSize"), -- ImGuiStyleVar.GrabMinSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabRounding"), -- ImGuiStyleVar.GrabRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageRounding"), -- ImGuiStyleVar.ImageRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageBorderSize"), -- ImGuiStyleVar.ImageBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabRounding"), -- ImGuiStyleVar.TabRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBorderSize"), -- ImGuiStyleVar.TabBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthBase"), -- ImGuiStyleVar.TabMinWidthBase + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthShrink"), -- ImGuiStyleVar.TabMinWidthShrink + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarBorderSize"), -- ImGuiStyleVar.TabBarBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarOverlineSize"), -- ImGuiStyleVar.TabBarOverlineSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TableAngledHeadersAngle"), -- ImGuiStyleVar.TableAngledHeadersAngle + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "TableAngledHeadersTextAlign"), -- ImGuiStyleVar.TableAngledHeadersTextAlign + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesSize"), -- ImGuiStyleVar.TreeLinesSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesRounding"), -- ImGuiStyleVar.TreeLinesRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "MenuItemRounding"), -- ImGuiStyleVar.MenuItemRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SelectableRounding"), -- ImGuiStyleVar.SelectableRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DragDropTargetRounding"), -- ImGuiStyleVar.DragDropTargetRounding + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ButtonTextAlign"), -- ImGuiStyleVar.ButtonTextAlign + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SelectableTextAlign"), -- ImGuiStyleVar.SelectableTextAlign + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorSize"), -- ImGuiStyleVar.SeparatorSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorTextBorderSize"), -- ImGuiStyleVar.SeparatorTextBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextAlign"), -- ImGuiStyleVar.SeparatorTextAlign + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextPadding") -- ImGuiStyleVar.SeparatorTextPadding } --- @param idx ImGuiStyleVar --- @return ImGuiStyleVarInfo function ImGui.GetStyleVarInfo(idx) IM_ASSERT(idx >= 0 and idx < ImGuiStyleVar.COUNT) - -- IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT) + -- IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar.COUNT) return GStyleVarsInfo[idx + 1] end @@ -12425,8 +14621,9 @@ function ImGui.PopStyleVar(count) end end +-- ATTENTION THIS IS IN LEGACY LOCAL SPACE. --- @param wrap_local_pos_x float -function ImGui.PushTextWrapPos(wrap_local_pos_x) -- ATTENTION: THIS IS IN LEGACY LOCAL SPACE. +function ImGui.PushTextWrapPos(wrap_local_pos_x) local g = GImGui local window = g.CurrentWindow window.DC.TextWrapPosStack:push_back(window.DC.TextWrapPos) @@ -12516,7 +14713,7 @@ end function ImGui.IsWindowAbove(potential_above, potential_below) local g = GImGui - -- It would be saner to ensure that display layer is always reflected in the g.Windows order, which would likely requires altering all manipulations of that array + -- It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array local display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below) if display_layer_delta ~= 0 then return display_layer_delta > 0 @@ -12535,6 +14732,9 @@ function ImGui.IsWindowAbove(potential_above, potential_below) end -- Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags for options. +-- IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, +-- you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! +-- Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. --- @param flags? ImGuiHoveredFlags function ImGui.IsWindowHovered(flags) if flags == nil then flags = 0 end @@ -12575,6 +14775,11 @@ function ImGui.IsWindowHovered(flags) end end + -- When changing hovered window we requires a bit of stationary delay before activating hover timer. + -- FIXME: We don't support delay other than stationary one for now, other delay would need a way + -- to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true + -- for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache. + -- We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow. if bit32.band(flags, ImGuiHoveredFlags.ForTooltip) ~= 0 then flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse) end @@ -12624,11 +14829,12 @@ local function ScaleWindow(window, scale) ImVec2_Copy(window.ContentSize, ImTrunc(window.ContentSize * scale)) end +-- Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) --- @param viewport ImGuiViewportP --- @param scale float function ImGui.ScaleWindowsInViewport(viewport, scale) local g = GImGui - -- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X", viewport.ID) + -- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X\n", viewport.ID) if viewport.Window then ScaleWindow(viewport.Window, scale) @@ -12641,10 +14847,14 @@ function ImGui.ScaleWindowsInViewport(viewport, scale) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] SCROLLING ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Helper to snap on edges when aiming at an item very close to the edge, +-- So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling. +-- When we refactor the scrolling API this may be configurable with a flag? +-- Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default. --- @param target float --- @param snap_min float --- @param snap_max float @@ -12688,6 +14898,7 @@ function CalcNextScrollFromScrollTargetAndClamp(window) return scroll end +-- Scroll to keep newly navigated item fully into view --- @param window ImGuiWindow --- @param item_rect ImRect --- @param flags? ImGuiScrollFlags @@ -12698,10 +14909,14 @@ function ImGui.ScrollToRectEx(window, item_rect, flags) local scroll_rect = ImRect(window.InnerRect.Min - ImVec2(1, 1), window.InnerRect.Max + ImVec2(1, 1)) scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window.DecoInnerSizeX1, scroll_rect.Max.x) scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window.DecoInnerSizeY1, scroll_rect.Max.y) + -- GetForegroundDrawList(window):AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0, 0, 5.0) -- [DEBUG] + -- GetForegroundDrawList(window):AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE) -- [DEBUG] + -- Check that only one behavior is selected per axis IM_ASSERT(bit32.band(flags, ImGuiScrollFlags.MaskX_) == 0 or ImIsPowerOfTwo(bit32.band(flags, ImGuiScrollFlags.MaskX_))) IM_ASSERT(bit32.band(flags, ImGuiScrollFlags.MaskY_) == 0 or ImIsPowerOfTwo(bit32.band(flags, ImGuiScrollFlags.MaskY_))) + -- Defaults local in_flags = flags if bit32.band(flags, ImGuiScrollFlags.MaskX_) == 0 and window.ScrollbarX then flags = bit32.bor(flags, ImGuiScrollFlags.KeepVisibleEdgeX) @@ -12746,7 +14961,9 @@ function ImGui.ScrollToRectEx(window, item_rect, flags) local next_scroll = CalcNextScrollFromScrollTargetAndClamp(window) local delta_scroll = next_scroll - window.Scroll + -- Also scroll parent window to keep us into view if necessary if bit32.band(flags, ImGuiScrollFlags.NoScrollParent) == 0 and bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then + -- FIXME-SCROLL: May be an option? if bit32.band(in_flags, bit32.bor(ImGuiScrollFlags.AlwaysCenterX, ImGuiScrollFlags.KeepVisibleCenterX)) ~= 0 then in_flags = bit32.bor(bit32.band(in_flags, bit32.bnot(ImGuiScrollFlags.MaskX_)), ImGuiScrollFlags.KeepVisibleEdgeX) end @@ -12791,6 +15008,7 @@ function ImGui.ScrollToRect(window, item_rect, flags) ImGui.ScrollToRectEx(window, item_rect, flags or 0) end +-- center_x_ratio: 0.0 left of last item, 0.5 horizontal center of last item, 1.0 right of last item. --- @param center_x_ratio? float function ImGui.SetScrollHereX(center_x_ratio) if center_x_ratio == nil then center_x_ratio = 0.5 end @@ -12798,10 +15016,13 @@ function ImGui.SetScrollHereX(center_x_ratio) local window = g.CurrentWindow local spacing_x = ImMax(window.WindowPadding.x, g.Style.ItemSpacing.x) local target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio) - ImGui.SetScrollFromPosX(window, target_pos_x - window.Pos.x, center_x_ratio) + ImGui.SetScrollFromPosX(window, target_pos_x - window.Pos.x, center_x_ratio) -- Convert from absolute to local pos + + -- Tweak: snap on edges when aiming at an item very close to the edge window.ScrollTargetEdgeSnapDist.x = ImMax(0.0, window.WindowPadding.x - spacing_x) end +-- center_y_ratio: 0.0 top of last item, 0.5 vertical center of last item, 1.0 bottom of last item. --- @param center_y_ratio? float function ImGui.SetScrollHereY(center_y_ratio) if center_y_ratio == nil then center_y_ratio = 0.5 end @@ -12809,7 +15030,9 @@ function ImGui.SetScrollHereY(center_y_ratio) local window = g.CurrentWindow local spacing_y = ImMax(window.WindowPadding.y, g.Style.ItemSpacing.y) local target_pos_y = ImLerp(window.DC.CursorPosPrevLine.y - spacing_y, window.DC.CursorPosPrevLine.y + window.DC.PrevLineSize.y + spacing_y, center_y_ratio) - ImGui.SetScrollFromPosY(window, target_pos_y - window.Pos.y, center_y_ratio) + ImGui.SetScrollFromPosY(window, target_pos_y - window.Pos.y, center_y_ratio) -- Convert from absolute to local pos + + -- Tweak: snap on edges when aiming at an item very close to the edge window.ScrollTargetEdgeSnapDist.y = ImMax(0.0, window.WindowPadding.y - spacing_y) end @@ -12832,6 +15055,16 @@ function ImGui.SetScrollY(window, scroll_y) window.ScrollTargetEdgeSnapDist.y = 0.0 end +-- Note that a local position will vary depending on initial scroll value, +-- This is a little bit confusing so bear with us: +-- - local_pos = (absolution_pos - window.Pos) +-- - So local_x/local_y are 0.0 for a position at the upper-left corner of a window, +-- and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area. +-- - They mostly exist because of legacy API. +-- Following the rules above, when trying to work with scrolling code, consider that: +-- - SetScrollFromPosY(0.0) == SetScrollY(0.0 + scroll.y) == has no effect! +-- - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0) == reset scroll. Of course writing SetScrollY(0.0) directly then makes more sense +-- We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size --- @param window ImGuiWindow --- @param local_x float --- @param center_x_ratio float @@ -12839,7 +15072,7 @@ function ImGui.SetScrollFromPosX(window, local_x, center_x_ratio) if type(window) == "number" then window, local_x, center_x_ratio = GImGui.CurrentWindow, window, local_x end if center_x_ratio == nil then center_x_ratio = 0.5 end IM_ASSERT(center_x_ratio >= 0.0 and center_x_ratio <= 1.0) - window.ScrollTarget.x = IM_TRUNC(local_x - window.DecoOuterSizeX1 - window.DecoInnerSizeX1 + window.Scroll.x) + window.ScrollTarget.x = IM_TRUNC(local_x - window.DecoOuterSizeX1 - window.DecoInnerSizeX1 + window.Scroll.x) -- Convert local position to scroll offset window.ScrollTargetCenterRatio.x = center_x_ratio window.ScrollTargetEdgeSnapDist.x = 0.0 end @@ -12851,14 +15084,14 @@ function ImGui.SetScrollFromPosY(window, local_y, center_y_ratio) if type(window) == "number" then window, local_y, center_y_ratio = GImGui.CurrentWindow, window, local_y end if center_y_ratio == nil then center_y_ratio = 0.5 end IM_ASSERT(center_y_ratio >= 0.0 and center_y_ratio <= 1.0) - window.ScrollTarget.y = IM_TRUNC(local_y - window.DecoOuterSizeY1 - window.DecoInnerSizeY1 + window.Scroll.y) + window.ScrollTarget.y = IM_TRUNC(local_y - window.DecoOuterSizeY1 - window.DecoInnerSizeY1 + window.Scroll.y) -- Convert local position to scroll offset window.ScrollTargetCenterRatio.y = center_y_ratio window.ScrollTargetEdgeSnapDist.y = 0.0 end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] TOOLTIPS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- @param tooltip_flags ImGuiTooltipFlags --- @param extra_window_flags ImGuiWindowFlags @@ -12867,6 +15100,12 @@ function ImGui.BeginTooltipEx(tooltip_flags, extra_window_flags) local is_dragdrop_tooltip = g.DragDropWithinSource or g.DragDropWithinTarget if is_dragdrop_tooltip then + -- Drag and Drop tooltips are positioning differently than other tooltips: + -- - 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 positioning logic of other tooltips (not drag and drop ones). + -- local tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding local is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource.TouchScreen) if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) == 0 then @@ -12883,10 +15122,12 @@ function ImGui.BeginTooltipEx(tooltip_flags, extra_window_flags) local bg_alpha = g.Style.Colors[ImGuiCol.PopupBg].w * 0.60 ImGui.SetNextWindowBgAlpha(bg_alpha) + -- PushStyleVar(ImGuiStyleVar.Alpha, g.Style.Alpha * 0.60) -- This would be nice but e.g ColorButton with checkerboard has issue with transparent colors :( tooltip_flags = bit32.bor(tooltip_flags, ImGuiTooltipFlags.OverridePrevious) end + -- Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. if (bit32.band(tooltip_flags, ImGuiTooltipFlags.OverridePrevious) ~= 0) and g.TooltipPreviousWindow ~= nil and g.TooltipPreviousWindow.Active and not ImGui.IsWindowInBeginStack(g.TooltipPreviousWindow) then -- IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name) ImGui.SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow) @@ -12899,7 +15140,11 @@ function ImGui.BeginTooltipEx(tooltip_flags, extra_window_flags) local flags = bit32.bor(ImGuiWindowFlags.Tooltip, ImGuiWindowFlags.NoInputs, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.AlwaysAutoResize) ImGui.Begin(window_name, nil, bit32.bor(flags, extra_window_flags)) - + -- 2023-03-09: Added bool return value to the API, but currently always returning true. + -- If this ever returns false we need to update BeginDragDropSource() accordingly. + -- if (!ret) + -- End(); + -- return ret; return true end @@ -12929,6 +15174,8 @@ function ImGui.SetTooltip(fmt, ...) ImGui.EndTooltip() end +-- Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'. +-- Defaults to == ImGuiHoveredFlags.Stationary | ImGuiHoveredFlags.DelayShort when using the mouse. --- @param fmt string --- @param ... any function ImGui.SetItemTooltip(fmt, ...) @@ -12937,10 +15184,23 @@ function ImGui.SetItemTooltip(fmt, ...) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] POPUPS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- 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 nil +-- Notes: +-- - FindBlockingModal(nil) == nil is generally equivalent to GetTopMostPopupModal() == nil. +-- Only difference is here we check for .Active/WasActive but it may be unnecessary. --- @param window? ImGuiWindow function ImGui.FindBlockingModal(window) local g = GImGui @@ -12948,6 +15208,7 @@ function ImGui.FindBlockingModal(window) return nil end + -- Find a modal that has common parent with specified window. Specified window should be positioned behind that modal. for i = 1, g.OpenPopupStack.Size do repeat local popup_data = g.OpenPopupStack.Data[i] @@ -12955,17 +15216,17 @@ function ImGui.FindBlockingModal(window) if popup_window == nil or bit32.band(popup_window.Flags, ImGuiWindowFlags.Modal) == 0 then break end - if not popup_window.Active and not popup_window.WasActive then + if not popup_window.Active and not popup_window.WasActive then -- Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows. break end - if window == nil then + if window == nil then -- FindBlockingModal(nil) test for if FocusWindow(nil) is naturally possible via a mouse click. return popup_window end - if ImGui.IsWindowWithinBeginStackOf(window, popup_window) then + if ImGui.IsWindowWithinBeginStackOf(window, popup_window) then -- Window may be over modal break end - do return popup_window end + do return popup_window end -- Place window right below first block modal until true end @@ -12987,6 +15248,12 @@ function ImGui.OpenPopup(id, popup_flags) end end +-- Mark popup as open (toggle toward open state). +-- - Return true when the popup is toggled open, which allows you to capture local state if needed. +-- You may also call IsWindowAppearing() inside the later BeginPopup() scope if you need to prepare/compute data for the popup. +-- - Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. +-- - Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). +-- - One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to nil). --- @param id ImGuiID --- @param popup_flags ImGuiPopupFlags function ImGui.OpenPopupEx(id, popup_flags) @@ -13000,7 +15267,7 @@ function ImGui.OpenPopupEx(id, popup_flags) end end - local popup_ref = ImGuiPopupData() + local popup_ref = ImGuiPopupData() -- Tagged as new ref as Window will be set back to nil if we write this into OpenPopupStack. popup_ref.PopupId = id popup_ref.Window = nil popup_ref.RestoreNavWindow = g.NavWindow -- When popup closes focus may be restored to NavWindow (depend on window type). @@ -13013,7 +15280,7 @@ function ImGui.OpenPopupEx(id, popup_flags) ImVec2_Copy(popup_ref.OpenMousePos, popup_ref.OpenPopupPos) end - -- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)", id) + -- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id) if g.OpenPopupStack.Size < current_stack_size + 1 then g.OpenPopupStack:push_back(popup_ref) return true @@ -13059,7 +15326,7 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p end -- Don't close our own child popup windows. - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d", ref_window and ref_window.Name or "", restore_focus_to_window_under_popup) + -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window and ref_window.Name or "", restore_focus_to_window_under_popup) local popup_count_to_keep = 0 if ref_window then -- Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow) @@ -13079,12 +15346,13 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p -- Window -> Popup1 -> Window2(Ref) -- - Clicking/focusing Popup1 will close Popup2 and Popup3: -- Window -> Popup1(Ref) -> Popup2 -> Popup3 - -- - Each popups may contain child windows, which is why we compare ->RootWindow! + -- - Each popups may contain child windows, which is why we compare .RootWindowDockTree! -- Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child -- We step through every popup from bottom to top to validate their position relative to reference window. ref_window_is_descendent_of_popup = false for n = popup_count_to_keep, g.OpenPopupStack.Size - 1 do local popup_window = g.OpenPopupStack.Data[n + 1].Window + -- if (popup_window.RootWindowDockTree == ref_window.RootWindowDockTree) -- FIXME-MERGE if popup_window and ImGui.IsWindowWithinBeginStackOf(ref_window, popup_window) then ref_window_is_descendent_of_popup = true break @@ -13102,7 +15370,7 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p end end if popup_count_to_keep < g.OpenPopupStack.Size then -- This test is not required but it allows to set a convenient breakpoint on the statement below - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")", ref_window and ref_window.Name or "") + -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window and ref_window.Name or "") ImGui.ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup) end end @@ -13111,7 +15379,7 @@ end --- @param restore_focus_to_window_under_popup bool function ImGui.ClosePopupToLevel(remaining, restore_focus_to_window_under_popup) local g = GImGui - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d", remaining, restore_focus_to_window_under_popup) + -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup) IM_ASSERT(remaining >= 0 and remaining < g.OpenPopupStack.Size) -- if bit32.band(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then -- for n = remaining + 1, g.OpenPopupStack.Size do @@ -13144,7 +15412,7 @@ function ImGui.ClosePopupToLevel(remaining, restore_focus_to_window_under_popup) end end --- Close the popup we have Begin-ed into +-- Close the popup we have begin-ed into. function ImGui.CloseCurrentPopup() local g = GImGui local popup_idx = g.BeginPopupStack.Size @@ -13182,12 +15450,13 @@ function ImGui.CloseCurrentPopup() end end +-- Attention! BeginPopup() adds default flags when calling BeginPopupEx()! --- @param id ImGuiID --- @param extra_window_flags ImGuiWindowFlags function ImGui.BeginPopupEx(id, extra_window_flags) local g = GImGui if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values return false end @@ -13210,21 +15479,24 @@ end function ImGui.BeginPopupMenuEx(id, label, extra_window_flags) local g = GImGui if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values return false end + -- As we bypass BeginChild(), set ImGuiChildFlags.AlwaysAutoResize as it is checked independently from ImGuiWindowFlags.AlwaysAutoResize for now (see #9355) + -- Ideally we should remove setting ImGuiWindowFlags.AlwaysAutoResize in BeginChild(). if bit32.band(extra_window_flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(extra_window_flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0 then ImGui.SetNextWindowChildFlags(ImGuiChildFlags.AlwaysAutoResize, true) end IM_ASSERT(bit32.band(extra_window_flags, ImGuiWindowFlags.ChildMenu) ~= 0) - local name = ImFormatString("%s###Menu_%02d", label, g.BeginMenuDepth) + local name = ImFormatString("%s###Menu_%02d", label, g.BeginMenuDepth) -- Recycle windows based on depth local is_open _, is_open = ImGui.Begin(name, nil, bit32.bor(extra_window_flags, ImGuiWindowFlags.Popup)) - if not is_open then + if not is_open then -- NB: Begin can return false when the popup is completely clipped (e.g. zero size display) ImGui.EndPopup() end + -- g.CurrentWindow.FocusRouteParentWindow = g.CurrentWindow.ParentWindowInBeginStack return is_open end @@ -13266,6 +15538,11 @@ function ImGui.EndPopup() g.WithinEndChildID = backup_within_end_child_id end +-- r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) +-- r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it. +-- (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor +-- information are available, it may represent the entire platform monitor from the frame of reference of the current viewport. +-- this allows us to have tooltips/popups displayed out of the parent viewport.) --- @param ref_pos ImVec2 --- @param size ImVec2 --- @param last_dir ImGuiDir @@ -13317,7 +15594,7 @@ function ImGui.FindBestWindowPosForPopupEx(ref_pos, size, last_dir, r_outer, r_a repeat local dir = (n == 0) and last_dir or dir_preferred_order[n] - if n ~= 0 and dir == last_dir then + if n ~= 0 and dir == last_dir then -- Already tried this direction? break end @@ -13364,6 +15641,7 @@ function ImGui.FindBestWindowPosForPopupEx(ref_pos, size, last_dir, r_outer, r_a return pos, last_dir end +-- Note that this is used for popups, which can overlap the non work-area of individual viewports. --- @param window ImGuiWindow --- @return ImRect --- @nodiscard @@ -13444,6 +15722,7 @@ function ImGui.FindBestWindowPosForPopup(window) 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. end + -- ImGui.GetForegroundDrawList():AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255)) local pos pos, window.AutoPosLastDirection = ImGui.FindBestWindowPosForPopupEx(tooltip_pos, window.Size, window.AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy.Tooltip) @@ -13459,7 +15738,6 @@ end --- @return ImGuiMouseButton function ImGui.GetMouseButtonFromPopupFlags(flags) IM_ASSERT(bit32.band(flags, ImGuiPopupFlags.InvalidMask_) == 0) - if bit32.band(flags, ImGuiPopupFlags.MouseButtonMask_) ~= 0 then return bit32.rshift(bit32.band(flags, ImGuiPopupFlags.MouseButtonMask_), ImGuiPopupFlags.MouseButtonShift_) - 1 end @@ -13482,6 +15760,8 @@ function ImGui.IsPopupOpenRequestForItem(popup_flags, id) return false end +-- Helper to open a popup if mouse button is released over the item +-- - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup() --- @param str_id? string --- @param popup_flags? ImGuiPopupFlags @native @@ -13492,14 +15772,30 @@ function ImGui.OpenPopupOnItemClick(str_id, popup_flags) if ImGui.IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID) then local window = g.CurrentWindow local id - if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end - IM_ASSERT(id ~= 0) + if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end -- If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + IM_ASSERT(id ~= 0) -- You cannot pass a nil str_id if the last item has no identifier (e.g. a Text() item) return ImGui.OpenPopupEx(id, popup_flags) end return false end +-- This is a helper to handle the simplest case of associating one named popup to one given widget. +-- - To create a popup associated to the last item, you generally want to pass a nil value to str_id. +-- - To create a popup with a specific identifier, pass it in str_id. +-- - This is useful when using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call. +-- - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id. +-- - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). +-- This is essentially the same as: +-- id = str_id ? GetID(str_id) : GetItemID(); +-- OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight); +-- return BeginPopup(id); +-- Which is essentially the same as: +-- id = str_id ? GetID(str_id) : GetItemID(); +-- if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) +-- OpenPopup(id); +-- return BeginPopup(id); +-- The main difference being that this is tweaked to avoid computing the ID twice. --- @param str_id? string --- @param popup_flags? ImGuiPopupFlags --- @return bool @@ -13512,17 +15808,21 @@ function ImGui.BeginPopupContextItem(str_id, popup_flags) return false end local id - if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end - IM_ASSERT(id ~= 0) + if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end -- If user hasn't passed an ID, we can use the LastItem ID. Using LastItem ID as a Popup ID won't conflict! + IM_ASSERT(id ~= 0) -- You cannot pass a nil str_id if the last item has no identifier (e.g. a Text() item) if ImGui.IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID) then ImGui.OpenPopupEx(id, popup_flags) end return ImGui.BeginPopupEx(id, bit32.bor(ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoSavedSettings)) end ---------------------------------------------------------------------------------------- --- [SECTION] NAVIGATION ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] KEYBOARD/GAMEPAD NAVIGATION +------------------------------------------------------------------------------- + +-- FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked. +-- In our terminology those should be interchangeable, yet right now this is super confusing. +-- Those two functions are merely a legacy artifact, so at minimum naming should be clarified. --- @param id ImGuiID function ImGui.PushFocusScope(id) @@ -13563,13 +15863,15 @@ end function ImGui.SetNavFocusScope(focus_scope_id) local g = GImGui g.NavFocusScopeId = focus_scope_id - g.NavFocusRoute:resize(0) + g.NavFocusRoute:resize(0) -- Invalidate if focus_scope_id == 0 then return end IM_ASSERT(g.NavWindow ~= nil) + -- Store current path (in reverse order) if focus_scope_id == g.CurrentFocusScopeId then + -- Top of focus stack contains local focus scopes inside current window for n = g.FocusScopeStack.Size, 1, -1 do local data = g.FocusScopeStack.Data[n] if data.WindowID ~= g.CurrentWindow.ID then @@ -13586,6 +15888,7 @@ function ImGui.SetNavFocusScope(focus_scope_id) return end + -- Then follow on manually set ParentWindowForFocusRoute field (#6798) local window = g.NavWindow.ParentWindowForFocusRoute while window ~= nil do local data = ImGuiFocusScopeData() @@ -13594,7 +15897,7 @@ function ImGui.SetNavFocusScope(focus_scope_id) g.NavFocusRoute:push_back(data) window = window.ParentWindowForFocusRoute end - IM_ASSERT(g.NavFocusRoute.Size < 100) + IM_ASSERT(g.NavFocusRoute.Size < 100) -- Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3 end function ImGui.SetItemDefaultFocus() @@ -13611,11 +15914,13 @@ function ImGui.SetItemDefaultFocus() ImGui.NavApplyItemToResult(g.NavInitResult) ImGui.NavUpdateAnyRequestFlag() + -- Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll) if not window.ClipRect:Contains(g.LastItemData.Rect) then ImGui.ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags.None) end end +-- (was called NavRestoreHighlightAfterMove() before 1.91.4) function ImGui.SetNavCursorVisibleAfterMove() local g = GImGui if g.NavWindow and (bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) ~= 0) then @@ -13665,10 +15970,13 @@ function ImGui.SetNavID(id, nav_layer, focus_scope_id, rect_rel) g.NavWindow.NavLastIds[nav_layer] = id ImRect_Copy(g.NavWindow.NavRectRel[nav_layer], rect_rel) + -- Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y) end +-- FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0). +-- This way we could find the last focused window among our children. It would be much less confusing this way? --- @param nav_window ImGuiWindow function ImGui.NavSaveLastChildNavWindowIntoParent(nav_window) local parent = nav_window @@ -13680,6 +15988,8 @@ function ImGui.NavSaveLastChildNavWindowIntoParent(nav_window) end end +-- Restore the last focused child. +-- Call when we are expected to land on the Main Layer (0) after FocusWindow() --- @param window ImGuiWindow function ImGui.NavRestoreLastChildNavWindow(window) if window.NavLastChildNavWindow and window.NavLastChildNavWindow.WasActive then @@ -13693,8 +16003,9 @@ function ImGui.NavRestoreLayer(layer) local g = GImGui if layer == ImGuiNavLayer.Main then local prev_nav_window = g.NavWindow - g.NavWindow = ImGui.NavRestoreLastChildNavWindow(g.NavWindow) + g.NavWindow = ImGui.NavRestoreLastChildNavWindow(g.NavWindow) -- FIXME-NAV: Should clear ongoing nav requests? g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid + -- if (prev_nav_window) IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name) end local window = g.NavWindow if window.NavLastIds[layer] ~= 0 then @@ -13720,9 +16031,11 @@ function ImGui.NavUpdateAnyRequestFlag() end end +-- This needs to be called before we submit any widget (aka in or before Begin) --- @param window ImGuiWindow --- @param force_reinit bool function ImGui.NavInitWindow(window, force_reinit) + -- FIXME: ChildWindow test here is wrong for docking local g = GImGui IM_ASSERT(window == g.NavWindow) @@ -13749,6 +16062,8 @@ function ImGui.NavInitWindow(window, force_reinit) end end +-- Positioning logic altered slightly for remote activation: for Popup we want to use item rect, for Tooltip we leave things alone. (#9138) +-- When calling for ImGuiWindowFlags.Popup we use LastItemData. --- @param window_type ImGuiWindowFlags --- @return ImGuiInputSource function ImGui.NavCalcPreferredRefPosSource(window_type) @@ -13852,7 +16167,7 @@ function ImGui.NavUpdateWindowingTarget(focus_change_dir) if window_target == nil then window_target = ImGui.FindWindowNavFocusable((focus_change_dir < 0) and g.WindowsFocusOrder.Size or 1, i_current, focus_change_dir) end - if window_target then + if window_target then -- Don't reset windowing target if there's a single window in the list g.NavWindowingTarget = window_target g.NavWindowingTargetAnim = window_target ImVec2_CopyV(g.NavWindowingAccumDeltaPos, 0.0, 0.0) @@ -13861,8 +16176,11 @@ function ImGui.NavUpdateWindowingTarget(focus_change_dir) g.NavWindowingToggleLayer = false end +-- Apply focus and close overlay --- @param apply_focus_window ImGuiWindow function ImGui.NavUpdateWindowingApplyFocus(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() local g = GImGui if g.NavWindow == nil or apply_focus_window ~= g.NavWindow.RootWindow then local previous_viewport = g.NavWindow and g.NavWindow.Viewport or nil @@ -13872,14 +16190,22 @@ function ImGui.NavUpdateWindowingApplyFocus(apply_focus_window) ImGui.FocusWindow(apply_focus_window, ImGuiFocusRequestFlags.RestoreFocusedChild) IM_ASSERT(g.NavWindow ~= nil) apply_focus_window = g.NavWindow - if apply_focus_window.NavLastIds[ImGuiNavLayer.Main] == 0 then + if apply_focus_window.NavLastIds[ImGuiNavLayer.Main] == 0 then -- FIXME: This is the equivalent of the 'if (g.NavId == 0) { NavInitWindow() }' in DockNodeUpdateTabBar(). ImGui.NavInitWindow(apply_focus_window, false) end + -- 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 == bit32.lshift(1, ImGuiNavLayer.Menu) then g.NavLayer = ImGuiNavLayer.Menu end + -- Request OS level focus if apply_focus_window.Viewport ~= previous_viewport and g.PlatformIO.Platform_SetWindowFocus then g.PlatformIO.Platform_SetWindowFocus(apply_focus_window.Viewport) end @@ -13887,6 +16213,9 @@ function ImGui.NavUpdateWindowingApplyFocus(apply_focus_window) g.NavWindowingTarget = nil end +-- 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) function ImGui.NavUpdateWindowing() local g = GImGui local io = g.IO @@ -13895,11 +16224,12 @@ function ImGui.NavUpdateWindowing() local apply_toggle_layer = false local modal_window = ImGui.GetTopMostPopupModal() - local allow_windowing = (modal_window == nil) + local allow_windowing = (modal_window == nil) -- FIXME: This prevent Ctrl+Tab from being usable with windows that are inside the Begin-stack of that modal. if not allow_windowing then g.NavWindowingTarget = nil end + -- Fade out if g.NavWindowingTargetAnim and g.NavWindowingTarget == nil then g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0, 0.0) if g.DimBgRatio <= 0.0 and g.NavWindowingHighlightAlpha <= 0.0 then @@ -13907,6 +16237,8 @@ function ImGui.NavUpdateWindowing() end end + -- 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) local owner_id = ImHashStr("##NavUpdateWindowing") local nav_gamepad_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0 local nav_keyboard_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 @@ -13914,10 +16246,10 @@ function ImGui.NavUpdateWindowing() local keyboard_prev_window = allow_windowing and g.ConfigNavWindowingKeyPrev ~= 0 and ImGui.Shortcut(g.ConfigNavWindowingKeyPrev, bit32.bor(ImGuiInputFlags.Repeat, ImGuiInputFlags.RouteAlways), owner_id) local start_toggling_with_gamepad = nav_gamepad_active and g.NavWindowingTarget == nil and ImGui.Shortcut(ImGuiKey.NavGamepadMenu, ImGuiInputFlags.RouteAlways, owner_id) local start_windowing_with_gamepad = allow_windowing and start_toggling_with_gamepad - local start_windowing_with_keyboard = allow_windowing and g.NavWindowingTarget == nil and (keyboard_next_window or keyboard_prev_window) + local start_windowing_with_keyboard = allow_windowing and g.NavWindowingTarget == nil and (keyboard_next_window or keyboard_prev_window) -- Note: enabled even without NavEnableKeyboard! local just_started_windowing_from_null_focus = false if start_toggling_with_gamepad then - g.NavWindowingToggleLayer = true + g.NavWindowingToggleLayer = true -- Gamepad starts toggling layer g.NavWindowingToggleKey = ImGuiKey.NavGamepadMenu g.NavWindowingInputSource = ImGuiInputSource.Gamepad g.NavInputSource = ImGuiInputSource.Gamepad @@ -13927,7 +16259,7 @@ function ImGui.NavUpdateWindowing() if window then if start_windowing_with_keyboard or g.ConfigNavWindowingWithGamepad then g.NavWindowingTarget = window.RootWindow - g.NavWindowingTargetAnim = window.RootWindow + g.NavWindowingTargetAnim = window.RootWindow -- Current location end g.NavWindowingTimer = 0.0 g.NavWindowingHighlightAlpha = 0.0 @@ -13939,17 +16271,22 @@ function ImGui.NavUpdateWindowing() just_started_windowing_from_null_focus = true end + -- Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects. if keyboard_next_window or keyboard_prev_window then ImGui.SetKeyOwnersForKeyChord(bit32.band(bit32.bor(g.ConfigNavWindowingKeyNext, g.ConfigNavWindowingKeyPrev), ImGuiMod_Mask_), owner_id) end end end + -- Gamepad update if (g.NavWindowingTarget or g.NavWindowingToggleLayer) and g.NavWindowingInputSource == ImGuiInputSource.Gamepad then if g.NavWindowingTarget ~= nil then + -- 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 = g.NavWindowingTimer + io.DeltaTime g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05)) + -- Select window to focus local focus_change_dir = (ImGui.IsKeyPressedEx(ImGuiKey.GamepadL1, ImGuiInputFlags.None, ImGuiKeyOwner_Any) and 1 or 0) - (ImGui.IsKeyPressedEx(ImGuiKey.GamepadR1, ImGuiInputFlags.None, ImGuiKeyOwner_Any) and 1 or 0) if focus_change_dir ~= 0 and not just_started_windowing_from_null_focus then ImGui.NavUpdateWindowingTarget(focus_change_dir) @@ -13957,8 +16294,9 @@ function ImGui.NavUpdateWindowing() end end + -- Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most) if not ImGui.IsKeyDown(ImGuiKey.NavGamepadMenu) then - g.NavWindowingToggleLayer = g.NavWindowingToggleLayer and (g.NavWindowingHighlightAlpha < 1.0) + g.NavWindowingToggleLayer = g.NavWindowingToggleLayer and (g.NavWindowingHighlightAlpha < 1.0) -- Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. if g.NavWindowingToggleLayer and g.NavWindow then apply_toggle_layer = true elseif not g.NavWindowingToggleLayer then @@ -13969,13 +16307,15 @@ function ImGui.NavUpdateWindowing() end end + -- Keyboard: Focus if g.NavWindowingTarget and g.NavWindowingInputSource == ImGuiInputSource.Keyboard then + -- Visuals only appears after a brief time after pressing TAB the first time, so that a fast Ctrl+Tab doesn't add visual noise local shared_mods = bit32.band( bit32.band((g.ConfigNavWindowingKeyNext ~= 0) and g.ConfigNavWindowingKeyNext or ImGuiMod_Mask_, (g.ConfigNavWindowingKeyPrev ~= 0) and g.ConfigNavWindowingKeyPrev or ImGuiMod_Mask_), ImGuiMod_Mask_) - IM_ASSERT(shared_mods ~= 0) + 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 = g.NavWindowingTimer + io.DeltaTime - g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05)) + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05)) -- 1.0f if (keyboard_next_window or keyboard_prev_window) and not just_started_windowing_from_null_focus then ImGui.NavUpdateWindowingTarget(keyboard_next_window and -1 or 1) elseif bit32.band(io.KeyMods, shared_mods) ~= shared_mods then @@ -13983,6 +16323,7 @@ function ImGui.NavUpdateWindowing() end end + -- Keyboard: Press and Release Alt to toggle menu layer local windowing_toggle_keys = { ImGuiKey.LeftAlt, ImGuiKey.RightAlt } local windowing_toggle_layer_start = false if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 then @@ -13998,6 +16339,10 @@ function ImGui.NavUpdateWindowing() end end if g.NavWindowingToggleLayer and g.NavWindowingInputSource == ImGuiInputSource.Keyboard then + -- 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) + -- - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). + -- We cancel toggling nav layer if an owner has claimed the key. if io.InputQueueCharacters.Size > 0 or io.KeyCtrl or io.KeyShift or io.KeySuper then g.NavWindowingToggleLayer = false elseif windowing_toggle_layer_start == false and g.LastKeyboardKeyPressTime == g.Time then @@ -14006,6 +16351,8 @@ function ImGui.NavUpdateWindowing() g.NavWindowingToggleLayer = false end + -- Apply layer toggle on Alt release + -- Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss. if ImGui.IsKeyReleased(g.NavWindowingToggleKey) and g.NavWindowingToggleLayer then if g.ActiveId == 0 or g.ActiveIdAllowOverlap then if ImGui.IsMousePosValid(io.MousePos) == ImGui.IsMousePosValid(io.MousePosPrev) then @@ -14018,6 +16365,7 @@ function ImGui.NavUpdateWindowing() end end + -- Move window if g.NavWindowingTarget and bit32.band(g.NavWindowingTarget.Flags, ImGuiWindowFlags.NoMove) == 0 then local nav_move_dir if g.NavInputSource == ImGuiInputSource.Keyboard and not io.KeyShift then @@ -14040,13 +16388,16 @@ function ImGui.NavUpdateWindowing() end end + -- Apply final focus if apply_focus_window then ImGui.NavUpdateWindowingApplyFocus(apply_focus_window) end + -- Apply menu/layer toggle if apply_toggle_layer and g.NavWindow then ImGui.ClearActiveID() + -- Move to parent menu if necessary local new_nav_window = g.NavWindow while new_nav_window.ParentWindow and bit32.band(new_nav_window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) == 0 @@ -14060,8 +16411,10 @@ function ImGui.NavUpdateWindowing() new_nav_window.NavLastChildNavWindow = old_nav_window end + -- Toggle layer local new_nav_layer = (bit32.band(g.NavWindow.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) ~= 0) and bit32.bxor(g.NavLayer, 1) or ImGuiNavLayer.Main if new_nav_layer ~= g.NavLayer then + -- Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?) local preserve_layer_1_nav_id = (new_nav_window.DockNodeAsHost ~= nil) if new_nav_layer == ImGuiNavLayer.Menu and not preserve_layer_1_nav_id then g.NavWindow.NavLastIds[new_nav_layer] = 0 @@ -14093,6 +16446,7 @@ function ImGui.NavUpdateContextMenuRequest() g.NavOpenContextMenuItemId = g.NavId g.NavOpenContextMenuWindowId = g.NavWindow.ID + -- Allow triggering for Begin()..BeginPopupContextItem(). A possible alternative would be to use g.NavLayer == ImGuiNavLayer.Menu. if g.NavId == g.NavWindow:GetID("#CLOSE") or g.NavId == g.NavWindow:GetID("#COLLAPSE") then g.NavOpenContextMenuItemId = g.NavWindow.MoveId end @@ -14101,6 +16455,7 @@ function ImGui.NavUpdateContextMenuRequest() ImGui.SetNavCursorVisibleAfterMove() end +-- FIXME: ScoringRect is not set --- @param move_dir ImGuiDir --- @param clip_dir ImGuiDir --- @param move_flags ImGuiNavMoveFlags @@ -14108,6 +16463,8 @@ end function ImGui.NavMoveRequestSubmit(move_dir, clip_dir, move_flags, scroll_flags) local g = GImGui IM_ASSERT(g.NavWindow ~= nil) + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name) + if bit32.band(move_flags, ImGuiNavMoveFlags.IsTabbing) ~= 0 then move_flags = bit32.bor(move_flags, ImGuiNavMoveFlags.AllowCurrentNavId) end @@ -14127,13 +16484,19 @@ function ImGui.NavMoveRequestSubmit(move_dir, clip_dir, move_flags, scroll_flags ImGui.NavUpdateAnyRequestFlag() end +-- Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position --- @param r ImRect --- @param preferred_pos_rel ImVec2 --- @param move_dir ImGuiDir --- @param move_flags ImGuiNavMoveFlags function ImGui.NavBiasScoringRect(r, preferred_pos_rel, move_dir, move_flags) + -- Bias initial rect local g = GImGui local rel_to_abs_offset = g.NavWindow.DC.CursorStartPos + + -- Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias. + -- - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column. + -- - But each successful move sets new bias on one axis, only cleared when using mouse. if bit32.band(move_flags, ImGuiNavMoveFlags.Forwarded) == 0 then if preferred_pos_rel.x == FLT_MAX then preferred_pos_rel.x = ImMin(r.Min.x + 1.0, r.Max.x) - rel_to_abs_offset.x @@ -14142,6 +16505,8 @@ function ImGui.NavBiasScoringRect(r, preferred_pos_rel, move_dir, move_flags) preferred_pos_rel.y = r:GetCenter().y - rel_to_abs_offset.y end end + + -- Apply general bias on the other axis if (move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and preferred_pos_rel.x ~= FLT_MAX then local new_x = preferred_pos_rel.x + rel_to_abs_offset.x r.Min.x = new_x; r.Max.x = new_x @@ -14151,6 +16516,10 @@ function ImGui.NavBiasScoringRect(r, preferred_pos_rel, move_dir, move_flags) end end +-- Handle PageUp/PageDown/Home/End keys +-- Called from NavUpdateCreateMoveRequest() which will use our output to create a move request +-- FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference +-- FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid? --- @return float function ImGui.NavUpdatePageUpPageDown() local g = GImGui @@ -14163,7 +16532,7 @@ function ImGui.NavUpdatePageUpPageDown() local page_down_held = ImGui.IsKeyDown(ImGuiKey.PageDown, ImGuiKeyOwner_NoOwner) local home_pressed = ImGui.IsKeyPressedEx(ImGuiKey.Home, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) local end_pressed = ImGui.IsKeyPressedEx(ImGuiKey.End, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) - if page_up_held == page_down_held and home_pressed == end_pressed then + if page_up_held == page_down_held and home_pressed == end_pressed then -- Proceed if either (not both) are pressed, otherwise early out return 0.0 end @@ -14172,6 +16541,7 @@ function ImGui.NavUpdatePageUpPageDown() end if bit32.band(window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Main)) == 0 and window.DC.NavWindowHasScrollY then + -- Fallback manual-scroll when window has no navigable item if ImGui.IsKeyPressedEx(ImGuiKey.PageUp, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then ImGui.SetScrollY(window, window.Scroll.y - window.InnerRect:GetHeight()) elseif ImGui.IsKeyPressedEx(ImGuiKey.PageDown, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then @@ -14187,21 +16557,25 @@ function ImGui.NavUpdatePageUpPageDown() local nav_scoring_rect_offset_y = 0.0 if ImGui.IsKeyPressedEx(ImGuiKey.PageUp, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then nav_scoring_rect_offset_y = -page_offset_y - g.NavMoveDir = ImGuiDir.Down + g.NavMoveDir = ImGuiDir.Down -- Because our scoring rect is offset up, we request the down direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir.Up - g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) + g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) -- ImGuiNavMoveFlags.AlsoScoreVisibleSet may be added later elseif ImGui.IsKeyPressedEx(ImGuiKey.PageDown, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then nav_scoring_rect_offset_y = page_offset_y - g.NavMoveDir = ImGuiDir.Up + g.NavMoveDir = ImGuiDir.Up -- Because our scoring rect is offset down, we request the up direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir.Down - g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) + g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) -- ImGuiNavMoveFlags.AlsoScoreVisibleSet may be added later elseif home_pressed then + -- FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y + -- Scrolling will be handled via the ImGuiNavMoveFlags.ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result. + -- Preserve current horizontal position if we have any. nav_rect_rel.Min.y = 0.0; nav_rect_rel.Max.y = 0.0 if nav_rect_rel:IsInverted() then nav_rect_rel.Min.x = 0.0; nav_rect_rel.Max.x = 0.0 end g.NavMoveDir = ImGuiDir.Down g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.ScrollToEdgeY) + -- FIXME-NAV: MoveClipDir left to _None, intentional? elseif end_pressed then nav_rect_rel.Min.y = window.ContentSize.y; nav_rect_rel.Max.y = window.ContentSize.y if nav_rect_rel:IsInverted() then @@ -14209,6 +16583,7 @@ function ImGui.NavUpdatePageUpPageDown() end g.NavMoveDir = ImGuiDir.Up g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.ScrollToEdgeY) + -- FIXME-NAV: MoveClipDir left to _None, intentional? end return nav_scoring_rect_offset_y end @@ -14223,9 +16598,13 @@ function ImGui.NavUpdateCreateMoveRequest() local nav_keyboard_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 if g.NavMoveForwardToNextFrame and window ~= nil then + -- Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window) + -- (preserve most state, which were already set by the NavMoveRequestForward() function) IM_ASSERT(g.NavMoveDir ~= ImGuiDir.None and g.NavMoveClipDir ~= ImGuiDir.None) IM_ASSERT(bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) ~= 0) + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir) else + -- Initiate directional inputs request g.NavMoveDir = ImGuiDir.None g.NavMoveFlags = ImGuiNavMoveFlags.None g.NavMoveScrollFlags = ImGuiScrollFlags.None @@ -14240,33 +16619,46 @@ function ImGui.NavUpdateCreateMoveRequest() ImRect_Copy(g.NavScoringNoClipRect, ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX)) end + -- Update PageUp/PageDown/Home/End scroll + -- FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags.NavEnableKeyboard flag? local scoring_page_offset_y = 0.0 if window and g.NavMoveDir == ImGuiDir.None and nav_keyboard_active then scoring_page_offset_y = ImGui.NavUpdatePageUpPageDown() end + -- Submit g.NavMoveForwardToNextFrame = false if g.NavMoveDir ~= ImGuiDir.None then ImGui.NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags) end + -- Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match) if g.NavMoveSubmitted and g.NavId == 0 then + -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer) g.NavInitRequest = true; g.NavInitRequestFromMove = true g.NavInitResult.ID = 0 - if g.IO.ConfigNavCursorVisibleAuto then + if g.IO.ConfigNavCursorVisibleAuto then -- NO check for _NoNavInputs here as we assume MoveRequests cannot be created. g.NavCursorVisible = true end end - if g.NavMoveSubmitted and g.NavInputSource == ImGuiInputSource.Gamepad and g.NavLayer == ImGuiNavLayer.Main and window ~= nil then + -- When using gamepad, we project the reference nav bounding box into window visible area. + -- This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, + -- since with gamepad all movements are relative (can't focus a visible object like we can with the mouse). + if g.NavMoveSubmitted and g.NavInputSource == ImGuiInputSource.Gamepad and g.NavLayer == ImGuiNavLayer.Main and window ~= nil then -- and (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded)) local clamp_x = bit32.band(g.NavMoveFlags, bit32.bor(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.WrapX)) == 0 local clamp_y = bit32.band(g.NavMoveFlags, bit32.bor(ImGuiNavMoveFlags.LoopY, ImGuiNavMoveFlags.WrapY)) == 0 local inner_rect_rel = ImGui.WindowRectAbsToRel(window, ImRect(ImVec2(window.InnerRect.Min.x - 1, window.InnerRect.Min.y - 1), ImVec2(window.InnerRect.Max.x + 1, window.InnerRect.Max.y + 1))) + + -- Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171) + -- Otherwise 'inner_rect_rel' would be off on the move result frame. local next_scroll = CalcNextScrollFromScrollTargetAndClamp(window) inner_rect_rel:Translate(ImVec2(next_scroll.x - window.Scroll.x, next_scroll.y - window.Scroll.y)) + if (clamp_x or clamp_y) and not inner_rect_rel:Contains(window.NavRectRel[g.NavLayer]) then + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n") local pad_x = ImMin(inner_rect_rel:GetWidth(), window.FontRefSize * 0.5) - local pad_y = ImMin(inner_rect_rel:GetHeight(), window.FontRefSize * 0.5) + local pad_y = ImMin(inner_rect_rel:GetHeight(), window.FontRefSize * 0.5) -- Terrible approximation for the intent of starting navigation from first fully visible item inner_rect_rel.Min.x = clamp_x and (inner_rect_rel.Min.x + pad_x) or -FLT_MAX inner_rect_rel.Max.x = clamp_x and (inner_rect_rel.Max.x - pad_x) or FLT_MAX inner_rect_rel.Min.y = clamp_y and (inner_rect_rel.Min.y + pad_y) or -FLT_MAX @@ -14276,6 +16668,8 @@ function ImGui.NavUpdateCreateMoveRequest() end end + -- 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) local scoring_rect = ImRect() if window ~= nil then local nav_rect_rel = ImRect() @@ -14285,6 +16679,7 @@ function ImGui.NavUpdateCreateMoveRequest() scoring_rect = ImGui.WindowRectRelToAbs(window, nav_rect_rel) if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsPageMove) ~= 0 then + -- When we start from a visible location, score visible items and prioritize this result. if window.InnerRect:Contains(scoring_rect) then g.NavMoveFlags = bit32.bor(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) end @@ -14293,12 +16688,16 @@ function ImGui.NavUpdateCreateMoveRequest() g.NavScoringNoClipRect:Add(scoring_rect) end + -- ImGui.GetForegroundDrawList():AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)) -- [DEBUG] Pre-bias if g.NavMoveSubmitted then ImGui.NavBiasScoringRect(scoring_rect, window.RootWindowForNav.NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags) end - IM_ASSERT(not scoring_rect:IsInverted()) + IM_ASSERT(not scoring_rect:IsInverted()) -- Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem(). + -- ImGui.GetForegroundDrawList():AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)) -- [DEBUG] Post-bias + -- if not g.NavScoringNoClipRect:IsInverted() then ImGui.GetForegroundDrawList():AddRectFilled(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(100, 255, 0, 80)) end -- [DEBUG] end ImRect_Copy(g.NavScoringRect, scoring_rect) + -- g.NavScoringNoClipRect:Add(scoring_rect) end function ImGui.NavUpdateCreateTabbingRequest() @@ -14314,6 +16713,9 @@ function ImGui.NavUpdateCreateTabbingRequest() return end + -- Initiate tabbing request + -- (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags.NavEnableKeyboard flag!) + -- See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping. local nav_keyboard_active = bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 if nav_keyboard_active then g.NavTabbingDir = g.IO.KeyShift and -1 or ((g.NavCursorVisible == false and g.ActiveId == 0) and 0 or 1) @@ -14323,7 +16725,7 @@ function ImGui.NavUpdateCreateTabbingRequest() local move_flags = bit32.bor(ImGuiNavMoveFlags.IsTabbing, ImGuiNavMoveFlags.Activate) local scroll_flags = window.Appearing and bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.AlwaysCenterY) or bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleEdgeY) local clip_dir = (g.NavTabbingDir < 0) and ImGuiDir.Up or ImGuiDir.Down - ImGui.NavMoveRequestSubmit(ImGuiDir.None, clip_dir, move_flags, scroll_flags) + ImGui.NavMoveRequestSubmit(ImGuiDir.None, clip_dir, move_flags, scroll_flags) -- FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable. g.NavTabbingCounter = -1 end @@ -14332,7 +16734,10 @@ function ImGui.NavUpdate() local io = g.IO io.WantSetMousePos = false + -- if g.NavScoringDebugCount > 0 then IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest) end + -- Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard) + -- FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource? local nav_gamepad_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0 if nav_gamepad_active and g.NavInputSource ~= ImGuiInputSource.Gamepad then for _, key in ipairs(nav_gamepad_keys_to_change_source) do @@ -14351,6 +16756,7 @@ function ImGui.NavUpdate() end end + -- Process navigation init request (select first/default focus) g.NavJustMovedToId = 0 g.NavJustMovedToFocusScopeId = 0 g.NavJustMovedFromFocusScopeId = 0 @@ -14361,6 +16767,7 @@ function ImGui.NavUpdate() g.NavInitRequestFromMove = false g.NavInitResult.ID = 0 + -- Process navigation move request if g.NavMoveSubmitted then ImGui.NavMoveRequestApplyResult() end @@ -14374,6 +16781,7 @@ function ImGui.NavUpdate() end end + -- Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling) local set_mouse_pos = false if g.NavMousePosDirty and g.NavIdIsAlive then if g.NavCursorVisible and g.NavHighlightItemUnderNav and g.NavWindow then @@ -14383,6 +16791,7 @@ function ImGui.NavUpdate() g.NavMousePosDirty = false IM_ASSERT(g.NavLayer == ImGuiNavLayer.Main or g.NavLayer == ImGuiNavLayer.Menu) + -- Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0 if g.NavWindow then ImGui.NavSaveLastChildNavWindowIntoParent(g.NavWindow) end @@ -14390,14 +16799,18 @@ function ImGui.NavUpdate() g.NavWindow.NavLastChildNavWindow = nil end + -- Update Ctrl+Tab and Windowing features (hold Square to move/resize/etc.) ImGui.NavUpdateWindowing() + -- Set output flags for user application io.NavActive = (nav_keyboard_active or nav_gamepad_active) and g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 io.NavVisible = (io.NavActive and g.NavId ~= 0 and g.NavCursorVisible) or (g.NavWindowingTarget ~= nil) + -- Process NavCancel input (to close a popup, get back to parent, clear focus) ImGui.NavUpdateCancelRequest() ImGui.NavUpdateContextMenuRequest() + -- Process manual activation request g.NavActivateId = 0 g.NavActivateDownId = 0 g.NavActivatePressedId = 0 @@ -14408,7 +16821,7 @@ function ImGui.NavUpdate() local activate_pressed = activate_down and ((nav_keyboard_active and ImGui.IsKeyPressedEx(ImGuiKey.Space, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner)) or (nav_gamepad_active and ImGui.IsKeyPressedEx(ImGuiKey.NavGamepadActivate, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner))) local input_pressed_keyboard = nav_keyboard_active and (ImGui.IsKeyPressedEx(ImGuiKey.Enter, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) or ImGui.IsKeyPressedEx(ImGuiKey.KeypadEnter, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner)) local input_pressed_gamepad = false - if activate_down and nav_gamepad_active and ImGui.IsKeyDown(ImGuiKey.NavGamepadActivate, ImGuiKeyOwner_NoOwner) and bit32.band(g.NavIdItemFlags, ImGuiItemFlags.Inputable) ~= 0 then + if activate_down and nav_gamepad_active and ImGui.IsKeyDown(ImGuiKey.NavGamepadActivate, ImGuiKeyOwner_NoOwner) and bit32.band(g.NavIdItemFlags, ImGuiItemFlags.Inputable) ~= 0 then -- requires ImGuiItemFlags.Inputable to avoid retriggering regular buttons. if ImGui.GetKeyData(g, ImGuiKey.NavGamepadActivate).DownDurationPrev < NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY and ImGui.GetKeyData(g, ImGuiKey.NavGamepadActivate).DownDuration >= NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY then input_pressed_gamepad = true end @@ -14422,7 +16835,7 @@ function ImGui.NavUpdate() g.NavActivateId = g.NavId g.NavActivateFlags = ImGuiActivateFlags.PreferInput end - if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_down or input_pressed_keyboard or input_pressed_gamepad) then + if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_down or input_pressed_keyboard or input_pressed_gamepad) then -- FIXME-NAV: Unsure why input_pressed_xxx (migrated from input_down which was already dubious) g.NavActivateDownId = g.NavId end if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_pressed or input_pressed_keyboard or input_pressed_gamepad) then @@ -14439,6 +16852,7 @@ function ImGui.NavUpdate() IM_ASSERT(g.NavActivateDownId == g.NavActivateId) end + -- Highlight if g.NavHighlightActivatedTimer > 0.0 then g.NavHighlightActivatedTimer = ImMax(0.0, g.NavHighlightActivatedTimer - io.DeltaTime) end @@ -14446,6 +16860,8 @@ function ImGui.NavUpdate() g.NavHighlightActivatedId = 0 end + -- Process programmatic activation request + -- FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others) if g.NavNextActivateId ~= 0 then g.NavActivateId = g.NavNextActivateId g.NavActivateDownId = g.NavNextActivateId @@ -14454,6 +16870,7 @@ function ImGui.NavUpdate() end g.NavNextActivateId = 0 + -- Process move requests ImGui.NavUpdateCreateMoveRequest() if g.NavMoveDir == ImGuiDir.None then ImGui.NavUpdateCreateTabbingRequest() @@ -14461,9 +16878,11 @@ function ImGui.NavUpdate() ImGui.NavUpdateAnyRequestFlag() g.NavIdIsAlive = false + -- Scrolling if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 and not g.NavWindowingTarget then + -- *Fallback* manual-scroll with Nav directional keys when window has no navigable item local window = g.NavWindow - local scroll_speed = IM_ROUND(window.FontRefSize * 100 * io.DeltaTime) + local scroll_speed = IM_ROUND(window.FontRefSize * 100 * io.DeltaTime) -- We need round the scrolling speed because sub-pixel scroll isn't reliably supported. local move_dir = g.NavMoveDir if window.DC.NavLayersActiveMask == 0x00 and window.DC.NavWindowHasScrollY and move_dir ~= ImGuiDir.None then if move_dir == ImGuiDir.Left or move_dir == ImGuiDir.Right then @@ -14476,6 +16895,8 @@ function ImGui.NavUpdate() end end + -- *Normal* Manual scroll with LStick + -- Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. if nav_gamepad_active then local scroll_dir = ImGui.GetKeyMagnitude2d(ImGuiKey.GamepadLStickLeft, ImGuiKey.GamepadLStickRight, ImGuiKey.GamepadLStickUp, ImGuiKey.GamepadLStickDown) local tweak_factor = 1.0 @@ -14493,21 +16914,29 @@ function ImGui.NavUpdate() end end + -- Always prioritize mouse highlight if navigation is disabled if not nav_keyboard_active and not nav_gamepad_active then g.NavCursorVisible = false g.NavHighlightItemUnderNav = false set_mouse_pos = false end + -- Update mouse position if requested + -- (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied) if set_mouse_pos and io.ConfigNavMoveSetMousePos and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasSetMousePos) ~= 0 then ImGui.TeleportMousePos(ImGui.NavCalcPreferredRefPos(ImGuiWindowFlags.Popup)) end + -- [DEBUG] g.NavScoringDebugCount = 0 end end +-- Process Escape/NavCancel input (to close a popup, get back to parent, clear focus) +-- FIXME: In order to support e.g. Escape to clear a selection we'll need: +-- - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it. +-- - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept function ImGui.NavUpdateCancelRequest() local g = GImGui local nav_gamepad_active = bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0 @@ -14520,9 +16949,11 @@ function ImGui.NavUpdateCancelRequest() if g.ActiveId ~= 0 then ImGui.ClearActiveID() elseif g.NavLayer ~= ImGuiNavLayer.Main then + -- Leave the "menu" layer ImGui.NavRestoreLayer(ImGuiNavLayer.Main) ImGui.SetNavCursorVisibleAfterMove() elseif g.NavWindow and g.NavWindow ~= g.NavWindow.RootWindow and bit32.band(g.NavWindow.RootWindowForNav.Flags, ImGuiWindowFlags.Popup) == 0 and g.NavWindow.RootWindowForNav.ParentWindow then + -- Exit child window local child_window = g.NavWindow.RootWindowForNav local parent_window = child_window.ParentWindow IM_ASSERT(child_window.ChildId ~= 0) @@ -14530,13 +16961,18 @@ function ImGui.NavUpdateCancelRequest() ImGui.SetNavID(child_window.ChildId, ImGuiNavLayer.Main, 0, ImGui.WindowRectAbsToRel(parent_window, child_window:Rect())) ImGui.SetNavCursorVisibleAfterMove() elseif g.OpenPopupStack.Size > 0 and g.OpenPopupStack:back().Window ~= nil and bit32.band(g.OpenPopupStack:back().Window.Flags, ImGuiWindowFlags.Modal) == 0 then + -- Close open popup/menu ImGui.ClosePopupToLevel(g.OpenPopupStack.Size - 1, true) else + -- Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were + -- FIXME-NAV: This should happen on window appearing. if g.IO.ConfigNavEscapeClearFocusItem or g.IO.ConfigNavEscapeClearFocusWindow then - if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.Popup) ~= 0 then + if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.Popup) ~= 0 then -- or not (g.NavWindow.Flags & ImGuiWindowFlags.ChildWindow) g.NavWindow.NavLastIds[0] = 0 end end + + -- Clear nav focus if g.IO.ConfigNavEscapeClearFocusItem or g.IO.ConfigNavEscapeClearFocusWindow then g.NavId = 0 end @@ -14568,6 +17004,7 @@ local function NavScoreItemDistInterval(cand_min, cand_max, curr_min, curr_max) return 0.0 end +-- Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057 --- @param result ImGuiNavItemData --- @param nav_bb ImRect --- @return bool @@ -14578,70 +17015,93 @@ function ImGui.NavScoreItem(result, nav_bb) return false end + -- FIXME: Those are not good variables names local cand = ImRect() - ImRect_Copy(cand, nav_bb) - local curr = g.NavScoringRect + ImRect_Copy(cand, nav_bb) -- Current item nav rectangle + local 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 = g.NavScoringDebugCount + 1 + -- When entering through a NavFlattened border, we consider child window items as fully clipped for scoring if window.ParentWindow == g.NavWindow then IM_ASSERT(bit32.band(bit32.bor(window.ChildFlags, g.NavWindow.ChildFlags), ImGuiChildFlags.NavFlattened) ~= 0) if not window.ClipRect:Overlaps(cand) then return false end - cand:ClipWithFull(window.ClipRect) + cand:ClipWithFull(window.ClipRect) -- This allows the scored item to not overlap other candidates in the parent window end + -- Compute distance between boxes + -- FIXME-NAV: Introducing biases for vertical navigation, needs to be removed. local dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x) - local dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2), ImLerp(cand.Min.y, cand.Max.y, 0.8), ImLerp(curr.Min.y, curr.Max.y, 0.2), ImLerp(curr.Min.y, curr.Max.y, 0.8)) + local dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2), ImLerp(cand.Min.y, cand.Max.y, 0.8), ImLerp(curr.Min.y, curr.Max.y, 0.2), ImLerp(curr.Min.y, curr.Max.y, 0.8)) -- Scale down on Y to keep using box-distance for vertically touching items if dby ~= 0.0 and dbx ~= 0.0 then dbx = (dbx / 1000.0) + ((dbx > 0.0) and 1.0 or -1.0) end local dist_box = ImFabs(dbx) + ImFabs(dby) + -- Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) local dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x) local dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y) - local dist_center = ImFabs(dcx) + ImFabs(dcy) + local dist_center = ImFabs(dcx) + ImFabs(dcy) -- L1 metric (need this for our connectedness guarantee) + -- Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance local quadrant local dax = 0.0 local day = 0.0 local dist_axial = 0.0 if dbx ~= 0.0 or dby ~= 0.0 then + -- For non-overlapping boxes, use distance between boxes + -- FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y + -- One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir.Right, pressing Left to navigate from Close to Collapse tends to fail. + -- Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty. dax = dbx day = dby dist_axial = dist_box quadrant = ImGetDirQuadrantFromDelta(dbx, dby) elseif dcx ~= 0.0 or dcy ~= 0.0 then + -- For overlapping boxes with different centers, use distance between centers dax = dcx day = dcy dist_axial = dist_center quadrant = ImGetDirQuadrantFromDelta(dcx, dcy) else + -- Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter) quadrant = (g.LastItemData.ID < g.NavId) and ImGuiDir.Left or ImGuiDir.Right end local move_dir = g.NavMoveDir + -- Is it in the quadrant we're interested in moving to? local new_best = false if quadrant == move_dir then + -- Does it beat the current best candidate? if dist_box < result.DistBox then result.DistBox = dist_box result.DistCenter = dist_center return true end if dist_box == result.DistBox then + -- Try using distance between center points to break ties if dist_center < result.DistCenter then result.DistCenter = dist_center new_best = true elseif dist_center == result.DistCenter then - if (((move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and dby) or dbx) < 0.0 then + -- Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items + -- (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index), + -- this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis. + if (((move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and dby) or dbx) < 0.0 then -- moving bj to the right/down decreases distance new_best = true end end end end - if result.DistBox == FLT_MAX and dist_axial < result.DistAxial then + -- Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches + -- are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness) + -- This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too. + -- 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward. + -- Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option? + if result.DistBox == FLT_MAX and dist_axial < result.DistAxial then -- Check axial match if g.NavLayer == ImGuiNavLayer.Menu and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.ChildMenu) == 0 then if (move_dir == ImGuiDir.Left and dax < 0.0) or (move_dir == ImGuiDir.Right and dax > 0.0) or (move_dir == ImGuiDir.Up and day < 0.0) or (move_dir == ImGuiDir.Down and day > 0.0) then result.DistAxial = dist_axial @@ -14664,18 +17124,25 @@ function ImGui.NavApplyItemToResult(result) ImRect_Copy(result.RectRel, ImGui.WindowRectAbsToRel(window, g.LastItemData.NavRect)) if bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 then IM_ASSERT(g.NextItemData.SelectionUserData ~= ImGuiSelectionUserData_Invalid) - result.SelectionUserData = g.NextItemData.SelectionUserData + result.SelectionUserData = g.NextItemData.SelectionUserData -- INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData. end end --- @param result ImGuiNavItemData function ImGui.NavMoveRequestResolveWithLastItem(result) local g = GImGui - g.NavMoveScoringItems = false + g.NavMoveScoringItems = false -- Ensure request doesn't need more processing ImGui.NavApplyItemToResult(result) ImGui.NavUpdateAnyRequestFlag() end +-- Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest(). +-- Note that SetKeyboardFocusHere() API calls are considered tabbing requests! +-- - Case 1: no nav/active id: set result to first eligible item, stop storing. +-- - Case 2: tab forward: on ref id set counter, on counter elapse store result +-- - Case 3: tab forward wrap: set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. -- FIXME-TABBING: Could be done as a next-frame forwarded request +-- - Case 4: tab backward: store all results, on ref id pick prev, stop storing +-- - Case 5: tab backward wrap: store all results, on ref id if no result keep storing until last -- FIXME-TABBING: Could be done as next-frame forwarded requested --- @param id ImGuiID --- @param item_flags ImGuiItemFlags --- @param move_flags ImGuiNavMoveFlags @@ -14691,6 +17158,9 @@ function ImGui.NavProcessItemForTabbingRequest(id, item_flags, move_flags) end end + -- - Can always land on an item when using API call. + -- - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item. + -- - Tabbing without _NavEnableKeyboard: goes through inputable items only. local can_stop if bit32.band(move_flags, ImGuiNavMoveFlags.FocusApi) ~= 0 then can_stop = true @@ -14698,8 +17168,10 @@ function ImGui.NavProcessItemForTabbingRequest(id, item_flags, move_flags) can_stop = bit32.band(item_flags, ImGuiItemFlags.NoTabStop) == 0 and (bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 or bit32.band(item_flags, ImGuiItemFlags.Inputable) ~= 0) end + -- Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows) local result = g.NavMoveResultLocal if g.NavTabbingDir == 1 then + -- Tab Forward or SetKeyboardFocusHere() with >= 0 if can_stop and g.NavTabbingResultFirst.ID == 0 then ImGui.NavApplyItemToResult(g.NavTabbingResultFirst) end @@ -14712,30 +17184,35 @@ function ImGui.NavProcessItemForTabbingRequest(id, item_flags, move_flags) g.NavTabbingCounter = 1 end elseif g.NavTabbingDir == -1 then + -- Tab Backward if g.NavId == id then if result.ID ~= 0 then g.NavMoveScoringItems = false ImGui.NavUpdateAnyRequestFlag() end elseif can_stop then + -- Keep applying until reaching NavId ImGui.NavApplyItemToResult(result) end elseif g.NavTabbingDir == 0 then if can_stop and g.NavId == id then ImGui.NavMoveRequestResolveWithLastItem(result) end - if can_stop and g.NavTabbingResultFirst.ID == 0 then + if can_stop and g.NavTabbingResultFirst.ID == 0 then -- Tab init ImGui.NavApplyItemToResult(g.NavTabbingResultFirst) end end end +-- We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above) +-- This is called after LastItemData is set, but NextItemData is also still valid. function ImGui.NavProcessItem() local g = GImGui local window = g.CurrentWindow local id = g.LastItemData.ID local item_flags = g.LastItemData.ItemFlags + -- When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816, #7994) local nav_bb = ImRect() ImRect_Copy(nav_bb, g.LastItemData.NavRect) if window.DC.NavIsScrollPushableX == false then @@ -14743,17 +17220,21 @@ function ImGui.NavProcessItem() nav_bb.Max.x = ImClamp(nav_bb.Max.x, window.ClipRect.Min.x, window.ClipRect.Max.x) end + -- Process Init Request if g.NavInitRequest and g.NavLayer == window.DC.NavLayerCurrent and bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then + -- Even if 'ImGuiItemFlags.NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback local candidate_for_nav_default_focus = bit32.band(item_flags, ImGuiItemFlags.NoNavDefaultFocus) == 0 if candidate_for_nav_default_focus or g.NavInitResult.ID == 0 then ImGui.NavApplyItemToResult(g.NavInitResult) end if candidate_for_nav_default_focus then - g.NavInitRequest = false + g.NavInitRequest = false -- Found a match, clear request ImGui.NavUpdateAnyRequestFlag() end end + -- Process Move Request (scoring for navigation) + -- FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy) if g.NavMoveScoringItems and bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.FocusApi) ~= 0 or bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) == 0 then local is_tabbing = bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 @@ -14765,9 +17246,10 @@ function ImGui.NavProcessItem() ImGui.NavApplyItemToResult(result) end + -- Features like PageUp/PageDown need to maintain a separate score for the visible set of items. local VISIBLE_RATIO = 0.70 if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) ~= 0 then - local r = window.InnerRect + local r = window.InnerRect -- window.ClipRect if r:Overlaps(nav_bb) then if ImClamp(nav_bb.Max.y, r.Min.y, r.Max.y) - ImClamp(nav_bb.Min.y, r.Min.y, r.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO then if ImGui.NavScoreItem(g.NavMoveResultLocalVisible, nav_bb) then @@ -14780,24 +17262,26 @@ function ImGui.NavProcessItem() end end + -- Update information for currently focused/navigated item if g.NavId == id then if g.NavWindow ~= window then - ImGui.SetNavWindow(window) + ImGui.SetNavWindow(window) -- Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window. end g.NavLayer = window.DC.NavLayerCurrent - ImGui.SetNavFocusScope(g.CurrentFocusScopeId) + ImGui.SetNavFocusScope(g.CurrentFocusScopeId) -- Will set g.NavFocusScopeId AND store g.NavFocusScopePath g.NavFocusScopeId = g.CurrentFocusScopeId g.NavIdIsAlive = true g.NavIdItemFlags = item_flags if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 then IM_ASSERT(g.NextItemData.SelectionUserData ~= ImGuiSelectionUserData_Invalid) - g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData + g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData -- INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData. end - window.NavRectRel[window.DC.NavLayerCurrent] = ImGui.WindowRectAbsToRel(window, nav_bb) + window.NavRectRel[window.DC.NavLayerCurrent] = ImGui.WindowRectAbsToRel(window, nav_bb) -- Store item bounding box (relative to window position) end end function ImGui.NavInitRequestApplyResult() + -- In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void) local g = GImGui if not g.NavWindow then return @@ -14813,8 +17297,11 @@ function ImGui.NavInitRequestApplyResult() g.NavJustMovedToHasSelectionData = bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 end + -- Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) + -- FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently. + -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) ImGui.SetNavID(result.ID, g.NavLayer, result.FocusScopeId, result.RectRel) - g.NavIdIsAlive = true + g.NavIdIsAlive = true -- Mark as alive from previous frame as we got a result if result.SelectionUserData ~= ImGuiSelectionUserData_Invalid then g.NavLastValidSelectionUserData = result.SelectionUserData end @@ -14823,9 +17310,11 @@ function ImGui.NavInitRequestApplyResult() end end +-- Apply result from previous frame navigation directional move request. Always called from NavUpdate() function ImGui.NavMoveRequestApplyResult() local g = GImGui + -- Select which result to use local result if g.NavMoveResultLocal.ID ~= 0 then result = g.NavMoveResultLocal @@ -14835,12 +17324,14 @@ function ImGui.NavMoveRequestApplyResult() result = nil end + -- Tabbing forward wrap if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 and result == nil then if (g.NavTabbingCounter == 1 or g.NavTabbingDir == 0) and g.NavTabbingResultFirst.ID ~= 0 then result = g.NavTabbingResultFirst end end + -- In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result) local axis = (g.NavMoveDir == ImGuiDir.Up or g.NavMoveDir == ImGuiDir.Down) and ImGuiAxis.Y or ImGuiAxis.X if result == nil then if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 then @@ -14849,15 +17340,18 @@ function ImGui.NavMoveRequestApplyResult() if g.NavId ~= 0 and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSetNavCursorVisible) == 0 then ImGui.SetNavCursorVisibleAfterMove() end - ImGui.NavClearPreferredPosForAxis(axis) + ImGui.NavClearPreferredPosForAxis(axis) -- On a failed move, clear preferred pos for this axis. + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n") return end + -- PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page. if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) ~= 0 and g.NavMoveResultLocalVisible.ID ~= 0 and g.NavMoveResultLocalVisible.ID ~= g.NavId then result = g.NavMoveResultLocalVisible end + -- Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules. if result ~= g.NavMoveResultOther and g.NavMoveResultOther.ID ~= 0 and g.NavMoveResultOther.Window.ParentWindow == g.NavWindow then if g.NavMoveResultOther.DistBox < result.DistBox or (g.NavMoveResultOther.DistBox == result.DistBox and g.NavMoveResultOther.DistCenter < result.DistCenter) then @@ -14866,24 +17360,33 @@ function ImGui.NavMoveRequestApplyResult() end IM_ASSERT(g.NavWindow and result.Window) + -- Scroll to keep newly navigated item fully into view. if g.NavLayer == ImGuiNavLayer.Main then local rect_abs = ImGui.WindowRectRelToAbs(result.Window, result.RectRel) ImGui.ScrollToRectEx(result.Window, rect_abs, g.NavMoveScrollFlags) + if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.ScrollToEdgeY) ~= 0 then + -- FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge? local scroll_target = (g.NavMoveDir == ImGuiDir.Up) and result.Window.ScrollMax.y or 0.0 ImGui.SetScrollY(result.Window, scroll_target) end end if g.NavWindow ~= result.Window then + -- IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name) g.NavWindow = result.Window g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid end + -- Clear active id unless requested not to + -- FIXME: ImGuiNavMoveFlags.NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction, + -- so this is mostly provided as a gateway for further experiments (see #1418, #2890) if g.ActiveId ~= result.ID and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoClearActiveId) == 0 then ImGui.ClearActiveID() end + -- Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags.AllowCurrentNavId) + -- PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior. if (g.NavId ~= result.ID or bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsPageMove) ~= 0) and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSelect) == 0 then g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId @@ -14892,8 +17395,11 @@ function ImGui.NavMoveRequestApplyResult() g.NavJustMovedToKeyMods = g.NavMoveKeyMods g.NavJustMovedToIsTabbing = bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 g.NavJustMovedToHasSelectionData = bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 + -- IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId) end + -- Apply new NavID/Focus + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) local root_for_nav = g.NavWindow.RootWindowForNav local preferred_scoring_pos_rel = ImVec2() ImVec2_Copy(preferred_scoring_pos_rel, root_for_nav.NavPreferredScoringPosRel[g.NavLayer]) @@ -14902,16 +17408,20 @@ function ImGui.NavMoveRequestApplyResult() g.NavLastValidSelectionUserData = result.SelectionUserData end + -- Restore last preferred position for current axis + -- (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..) if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) == 0 then preferred_scoring_pos_rel[axis] = result.RectRel:GetCenter()[axis] ImVec2_Copy(root_for_nav.NavPreferredScoringPosRel[g.NavLayer], preferred_scoring_pos_rel) end + -- Tabbing: Activates Inputable, otherwise only Focus if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 and bit32.band(result.ItemFlags, ImGuiItemFlags.Inputable) == 0 then g.NavMoveFlags = bit32.band(g.NavMoveFlags, bit32.bnot(ImGuiNavMoveFlags.Activate)) end + -- Activate if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Activate) ~= 0 then g.NavNextActivateId = result.ID g.NavNextActivateFlags = ImGuiActivateFlags.None @@ -14923,26 +17433,30 @@ function ImGui.NavMoveRequestApplyResult() end end + -- Make nav cursor visible if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSetNavCursorVisible) == 0 then ImGui.SetNavCursorVisibleAfterMove() end end +-- True when current work location may be scrolled horizontally when moving left / right. +-- This is generally always true UNLESS within a column. We don't have a vertical equivalent. function ImGui.NavUpdateCurrentWindowIsScrollPushableX() local g = GImGui local window = g.CurrentWindow window.DC.NavIsScrollPushableX = (g.CurrentTable == nil and window.DC.CurrentColumns == nil) end +-- Called by TreePop() to implement ImGuiTreeNodeFlags.NavLeftJumpsToParent --- @param result ImGuiNavItemData --- @param tree_node_data ImGuiTreeNodeStackData function ImGui.NavMoveRequestResolveWithPastTreeNode(result, tree_node_data) local g = GImGui g.NavMoveScoringItems = false g.LastItemData.ID = tree_node_data.ID - g.LastItemData.ItemFlags = bit32.band(tree_node_data.ItemFlags, bit32.bnot(ImGuiItemFlags.HasSelectionUserData)) + g.LastItemData.ItemFlags = bit32.band(tree_node_data.ItemFlags, bit32.bnot(ImGuiItemFlags.HasSelectionUserData)) -- Losing SelectionUserData, recovered next-frame (cheaper). ImRect_Copy(g.LastItemData.NavRect, tree_node_data.NavRect) - ImGui.NavApplyItemToResult(result) + ImGui.NavApplyItemToResult(result) -- Result this instead of implementing a NavApplyPastTreeNodeToResult() ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y) ImGui.NavUpdateAnyRequestFlag() end @@ -14954,6 +17468,7 @@ function ImGui.NavMoveRequestCancel() ImGui.NavUpdateAnyRequestFlag() end +-- Forward will reuse the move request again on the next frame (generally with modifications done to it) --- @param move_dir ImGuiDir --- @param clip_dir ImGuiDir --- @param move_flags ImGuiNavMoveFlags @@ -14969,29 +17484,33 @@ function ImGui.NavMoveRequestForward(move_dir, clip_dir, move_flags, scroll_flag g.NavMoveScrollFlags = scroll_flags end +-- Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire +-- popup is assembled and in case of appended popups it is not clear which EndPopup() call is final. --- @param window ImGuiWindow --- @param wrap_flags ImGuiNavMoveFlags function ImGui.NavMoveRequestTryWrapping(window, wrap_flags) local g = GImGui - IM_ASSERT(bit32.band(wrap_flags, ImGuiNavMoveFlags.WrapMask_) ~= 0 and bit32.band(wrap_flags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)) == 0) + IM_ASSERT(bit32.band(wrap_flags, ImGuiNavMoveFlags.WrapMask_) ~= 0 and bit32.band(wrap_flags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)) == 0) -- Call with _WrapX, _WrapY, _LoopX, _LoopY + -- In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it: + -- as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest(). if g.NavWindow == window and g.NavMoveScoringItems and g.NavLayer == window.DC.NavLayerCurrent then g.NavMoveFlags = bit32.bor(bit32.band(g.NavMoveFlags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)), wrap_flags) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] DRAG AND DROP ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.IsDragDropPayloadBeingAccepted() local g = GImGui return g.DragDropActive and g.DragDropAcceptIdPrev ~= 0 end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] LOCALIZATION ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- @param entries ImGuiLocEntry[] --- @param count int @@ -15002,9 +17521,32 @@ function ImGui.LocalizeRegisterEntries(entries, count) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] VIEWPORTS, PLATFORM WINDOWS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - GetMainViewport() +-- - FindViewportByID() +-- - SetCurrentViewport() [Internal] +-- - SetWindowViewport() [Internal] +-- - GetWindowAlwaysWantOwnViewport() [Internal] +-- - UpdateTryMergeWindowIntoHostViewport() [Internal] +-- - UpdateTryMergeWindowIntoHostViewports() [Internal] +-- - TranslateWindowsInViewport() [Internal] +-- - ScaleWindowsInViewport() [Internal] +-- - FindHoveredViewportFromPlatformWindowStack() [Internal] +-- - UpdateViewportsNewFrame() [Internal] +-- - UpdateViewportsEndFrame() [Internal] +-- - AddUpdateViewport() [Internal] +-- - WindowSelectViewport() [Internal] +-- - WindowSyncOwnedViewport() [Internal] +-- - UpdatePlatformWindows() +-- - RenderPlatformWindowsDefault() +-- - FindPlatformMonitorForPos() [Internal] +-- - FindPlatformMonitorForRect() [Internal] +-- - UpdateViewportPlatformMonitor() [Internal] +-- - DestroyPlatformWindow() [Internal] +-- - DestroyPlatformWindows() +------------------------------------------------------------------------------- function MT.ImGuiViewport:GetDebugName() local viewport = self @@ -15040,6 +17582,7 @@ function ImGui.GetMainViewport() return g.Viewports[1] end +-- FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236) --- @param viewport_id ImGuiID --- @return ImGuiViewport? function ImGui.FindViewportByID(viewport_id) @@ -15112,8 +17655,8 @@ function ImGui.GetWindowAlwaysWantOwnViewport(window) return false end ---- Heuristic, see #8948: depends on how backends handle OS-level parenting. ---- Due to how parent viewport stack is layed out, note that IsViewportAbove(a,b) isn't always the same as !IsViewportAbove(b,a). +-- Heuristic, see #8948: depends on how backends handle OS-level parenting. +-- Due to how parent viewport stack is layed out, note that IsViewportAbove(a,b) isn't always the same as !IsViewportAbove(b,a). --- @param potential_above ImGuiViewportP --- @param potential_below ImGuiViewportP --- @return bool @@ -15207,8 +17750,8 @@ function ImGui.UpdateTryMergeWindowIntoHostViewports(window) return ImGui.UpdateTryMergeWindowIntoHostViewport(window, g.Viewports.Data[1]) end ---- Translate Dear ImGui windows when a Host Viewport has been moved ---- (This additionally keeps windows at the same place when ImGuiConfigFlags.ViewportsEnable is toggled!) +-- Translate Dear ImGui windows when a Host Viewport has been moved +-- (This additionally keeps windows at the same place when ImGuiConfigFlags.ViewportsEnable is toggled!) --- @param viewport ImGuiViewportP --- @param old_pos ImVec2 --- @param new_pos ImVec2 @@ -15235,7 +17778,7 @@ function ImGui.TranslateWindowsInViewport(viewport, old_pos, new_pos, old_size, end end --- If the backend doesn't support ImGuiBackendFlags_HasMouseHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs for it, we do a search ourselves. +-- If the backend doesn't support ImGuiBackendFlags.HasMouseHoveredViewport or doesn't honor ImGuiViewportFlags.NoInputs for it, we do a search ourselves. -- A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. -- B) It requires Platform_GetWindowFocus to be implemented by backend. --- @param mouse_platform_pos ImVec2 @@ -15255,6 +17798,8 @@ function ImGui.FindHoveredViewportFromPlatformWindowStack(mouse_platform_pos) return best_candidate end +-- Update viewports and monitor infos +-- Note that this is running even if 'ImGuiConfigFlags.ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info. function ImGui.UpdateViewportsNewFrame() local g = GImGui IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size) @@ -15411,6 +17956,7 @@ function ImGui.UpdateViewportsNewFrame() viewport:UpdateWorkRect() + -- Garbage collect transient buffers of recently BG/FG drawlists for dl_n = 1, 2 do -- IM_COUNTOF(viewport->BgFgDrawLists) if viewport.BgFgDrawListsLastTimeActive[dl_n] < memory_compact_start_time and viewport.BgFgDrawLists[dl_n] ~= nil then IM_DELETE(viewport.BgFgDrawLists, dl_n) @@ -15540,6 +18086,7 @@ function ImGui.UpdateViewportsNewFrame() IM_ASSERT(g.MouseViewport ~= nil) end +-- Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) function ImGui.UpdateViewportsEndFrame() local g = GImGui g.PlatformIO.Viewports:resize(0) @@ -15550,7 +18097,7 @@ function ImGui.UpdateViewportsEndFrame() ImVec2_Copy(viewport.LastPos, ImVec2(viewport.Pos.x, viewport.Pos.y)) ImVec2_Copy(viewport.LastSize, ImVec2(viewport.Size.x, viewport.Size.y)) - if (viewport.LastFrameActive < g.FrameCount or viewport.Size.x <= 0.0 or viewport.Size.y <= 0.0) and (i > 1) then + if (viewport.LastFrameActive < g.FrameCount or viewport.Size.x <= 0.0 or viewport.Size.y <= 0.0) and (i > 1) then -- Always include main viewport in the list break end if viewport.Window and not ImGui.IsWindowActiveAndVisible(viewport.Window) then @@ -15567,6 +18114,7 @@ function ImGui.UpdateViewportsEndFrame() g.Viewports.Data[1]:ClearRequestFlags() -- Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called end +-- FIXME: We should ideally refactor the system to call this every frame (we currently don't) --- @param window? ImGuiWindow --- @param id ImGuiID --- @param pos ImVec2 @@ -15604,8 +18152,7 @@ function ImGui.AddUpdateViewport(window, id, pos, size, flags) if not viewport.PlatformRequestResize or viewport.ID == IMGUI_VIEWPORT_DEFAULT_ID then ImVec2_Copy(viewport.Size, size) end - -- Preserve existing flags - viewport.Flags = bit32.bor(flags, bit32.band(viewport.Flags, bit32.bor(ImGuiViewportFlags.IsMinimized, ImGuiViewportFlags.IsFocused))) + viewport.Flags = bit32.bor(flags, bit32.band(viewport.Flags, bit32.bor(ImGuiViewportFlags.IsMinimized, ImGuiViewportFlags.IsFocused))) -- Preserve existing flags if prev_pos.x ~= viewport.Pos.x or prev_pos.y ~= viewport.Pos.y or prev_size.x ~= viewport.Size.x or prev_size.y ~= viewport.Size.y then ImGui.UpdateViewportPlatformMonitor(viewport) end @@ -15678,6 +18225,7 @@ function ImGui.DestroyViewport(viewport) -- IM_DELETE(viewport) end +-- FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. --- @param window ImGuiWindow function ImGui.WindowSelectViewport(window) local g = GImGui @@ -15856,7 +18404,7 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) -- Not correct to set modal as topmost because: -- - Because other popups can be stacked above a modal (e.g. combo box in a modal) - -- - ImGuiViewportFlags.TopMost is currently handled different in backends + -- - ImGuiViewportFlags.TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost" -- if bit32.band(window_flags, ImGuiWindowFlags.Modal) ~= 0 then -- viewport_flags = bit32.bor(viewport_flags, ImGuiViewportFlags.TopMost) -- end @@ -15907,6 +18455,8 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) end end +-- Called by user at the end of the main loop, after EndFrame() +-- This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api. function ImGui.UpdatePlatformWindows() local g = GImGui IM_ASSERT(g.FrameCountEnded == g.FrameCount, "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?") @@ -16068,6 +18618,9 @@ function ImGui.FindPlatformMonitorForPos(pos) return -1 end +-- Search for the monitor with the largest intersection area with the given rectangle +-- We generally try to avoid searching loops but the monitor count should be very small here +-- FIXME-OPT: We could test the last monitor used for that viewport first, and early --- @param rect ImRect --- @return int function ImGui.FindPlatformMonitorForRect(rect) @@ -16109,11 +18662,13 @@ function ImGui.FindPlatformMonitorForRect(rect) return best_monitor_n end +-- Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor) --- @param viewport ImGuiViewportP function ImGui.UpdateViewportPlatformMonitor(viewport) viewport.PlatformMonitor = ImGui.FindPlatformMonitorForRect(viewport:GetMainRect()) end +-- Return value is always ~= nil, but don't hold on it across frames. --- @param viewport_p ImGuiViewport --- @return ImGuiPlatformMonitor function ImGui.GetViewportPlatformMonitor(viewport_p) @@ -16155,15 +18710,24 @@ function ImGui.DestroyPlatformWindow(viewport) end function ImGui.DestroyPlatformWindows() + -- We call the destroy window on every viewport (including the main viewport, index 1) to give a chance to the backend + -- to clear any data they may have stored in e.g. PlatformUserData, RendererUserData. + -- It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling + -- code to operator a consistent manner. + -- It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without + -- crashing if it doesn't have data stored. local g = GImGui for _, viewport in g.Viewports:iter() do ImGui.DestroyPlatformWindow(viewport) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] METRICS/DEBUGGER WINDOW ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DebugRenderViewportThumbnail() [Internal] +-- - RenderViewportsThumbnails() [Internal] +------------------------------------------------------------------------------- --- @param draw_list ImDrawList --- @param viewport ImGuiViewport @@ -16189,7 +18753,7 @@ function ImGui.DebugRenderViewportThumbnail(draw_list, viewport, bb) local thumb_r = thumb_window:Rect() local title_r = thumb_window:TitleBarRect() thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off + thumb_r.Max * scale)) - title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r:GetHeight() * 3.0) * scale)) + title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r:GetHeight() * 3.0) * scale)) -- Exaggerate title bar height thumb_r:ClipWithFull(bb) title_r:ClipWithFull(bb) local window_is_focused = g.NavWindow and thumb_window.RootWindowForTitleBarHighlight == g.NavWindow.RootWindowForTitleBarHighlight @@ -16211,6 +18775,7 @@ function ImGui.RenderViewportsThumbnails() local g = GImGui local window = g.CurrentWindow + -- Draw monitor and calculate their boundaries local SCALE = 1.0 / 8.0 local bb_full = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX) for _, monitor in g.PlatformIO.Monitors:iter() do @@ -16225,6 +18790,7 @@ function ImGui.RenderViewportsThumbnails() window.DrawList:AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui.GetColorU32(ImGuiCol.Border, 0.10), 4.0) end + -- Draw viewports for _, viewport in g.Viewports:iter() do local viewport_draw_bb = ImRect(off + viewport.Pos * SCALE, off + (viewport.Pos + viewport.Size) * SCALE) ImGui.DebugRenderViewportThumbnail(window.DrawList, viewport, viewport_draw_bb) @@ -16241,6 +18807,19 @@ function ImGui.GetStyleColorVec4(idx) return GImGui.Style.Colors[idx] end +-- 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. +-- +-- 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. function ImGui.ErrorCheckUsingSetCursorPosToExtendParentBoundaries() local g = GImGui local window = g.CurrentWindow @@ -16253,9 +18832,9 @@ function ImGui.ErrorCheckUsingSetCursorPosToExtendParentBoundaries() window.DC.CursorMaxPos = ImMax(window.DC.CursorMaxPos, window.DC.CursorPos) end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] POPUPS: modals, context popups, dimming ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- local function GetWindowDisplayLayer(window) return (bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0) and 1 or 0 @@ -16293,6 +18872,7 @@ function ImGui.FindBottomMostVisibleWindowWithinBeginStack(parent_window) return bottom_most_visible_window end +-- See Demo->Stacked Modal to confirm what this is for. function ImGui.GetTopMostAndVisiblePopupModal() local g = GImGui for n = g.OpenPopupStack.Size, 1, -1 do @@ -16309,18 +18889,22 @@ function ImGui.RenderDimmedBackgroundBehindWindow(window, col) local viewport = window.Viewport local viewport_rect = viewport:GetMainRect() -- Draw behind window by moving the draw command at the FRONT of the draw list + -- Draw list have been trimmed already, hence the explicit recreation of a draw command if missing. + -- FIXME: This is a little bit complicated, solely to avoid creating/injecting an extra drawlist in drawdata. local draw_list = (window.RootWindowDockTree or window.RootWindow).DrawList draw_list:ChannelsMerge() if draw_list.CmdBuffer.Size == 0 then draw_list:AddDrawCmd() end - draw_list:PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false) + draw_list:PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false) -- FIXME: Need to strictly ensure ImDrawCmd are not merged draw_list:AddRectFilled(viewport_rect.Min, viewport_rect.Max, col) local cmd = draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size] draw_list.CmdBuffer:pop_back() draw_list.CmdBuffer:push_front(cmd) - draw_list:AddDrawCmd() + draw_list:AddDrawCmd() -- We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command. draw_list:PopClipRect() end +-- Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList:ChannelsMerge() before usage. +-- We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds(). function ImGui.RenderDimmedBackgrounds() local g = GImGui local modal_window = ImGui.GetTopMostAndVisiblePopupModal() @@ -16330,24 +18914,27 @@ function ImGui.RenderDimmedBackgrounds() if not dim_bg_for_modal and not dim_bg_for_window_list then return end if dim_bg_for_modal then + -- Draw dimming behind modal or a begin stack child, whichever comes first in draw order. local dim_behind_window = ImGui.FindBottomMostVisibleWindowWithinBeginStack(modal_window) ImGui.RenderDimmedBackgroundBehindWindow(dim_behind_window, ImGui.GetColorU32(modal_window.DC.ModalDimBgColor, g.DimBgRatio, true)) elseif dim_bg_for_window_list then + -- Draw dimming behind Ctrl+Tab target window and behind Ctrl+Tab UI window ImGui.RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, ImGui.GetColorU32(ImGuiCol.NavWindowingDimBg, g.DimBgRatio)) if g.NavWindowingListWindow ~= nil and g.NavWindowingListWindow.Active and g.NavWindowingListWindow.Viewport and g.NavWindowingListWindow.Viewport ~= g.NavWindowingTargetAnim.Viewport then ImGui.RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, ImGui.GetColorU32(ImGuiCol.NavWindowingDimBg, g.DimBgRatio)) end + -- Draw border around Ctrl+Tab target window local window = g.NavWindowingTargetAnim local viewport = window.Viewport local distance = g.FontSize local bb = window:Rect() bb:Expand(distance) - if bb:GetWidth() >= viewport.Size.x and bb:GetHeight() >= viewport.Size.y then bb:Expand(-distance - 1.0) end + if bb:GetWidth() >= viewport.Size.x and bb:GetHeight() >= viewport.Size.y then bb:Expand(-distance - 1.0) end -- If a window fits the entire viewport, adjust its highlight inward window.DrawList:ChannelsMerge() if window.DrawList.CmdBuffer.Size == 0 then window.DrawList:AddDrawCmd() end window.DrawList:PushClipRect(viewport.Pos, viewport.Pos + viewport.Size) - window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.NavWindowingHighlight, g.NavWindowingHighlightAlpha), window.WindowRounding, 0, 3.0) + window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.NavWindowingHighlight, g.NavWindowingHighlightAlpha), window.WindowRounding, 0, 3.0) -- FIXME-DPI window.DrawList:PopClipRect() end end @@ -16360,11 +18947,15 @@ function ImGui.ClosePopupsExceptModals() if not window or bit32.band(window.Flags, ImGuiWindowFlags.Modal) ~= 0 then break end popup_count_to_keep = popup_count_to_keep - 1 end - if popup_count_to_keep < g.OpenPopupStack.Size then + if popup_count_to_keep < g.OpenPopupStack.Size then -- This test is not required but it allows to set a convenient breakpoint on the statement below ImGui.ClosePopupToLevel(popup_count_to_keep, true) end end +-- If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup. +-- Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup). +-- - p_open is returned set back to false by BeginPopupModal() when popup is not open. +-- - if you set p_open to false before calling BeginPopupModal(), it will close the popup. --- @return bool visible, bool? p_open # p_open is the updated value of the optional close button flag function ImGui.BeginPopupModal(name, p_open, flags) if flags == nil then flags = 0 end @@ -16372,20 +18963,23 @@ function ImGui.BeginPopupModal(name, p_open, flags) local window = g.CurrentWindow local id = window:GetID(name) if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values if p_open then p_open = false end return false, p_open end + -- 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 bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) == 0 then - local viewport = window.WasActive and window.Viewport or ImGui.GetMainViewport() + local viewport = window.WasActive and window.Viewport or ImGui.GetMainViewport() -- FIXME-VIEWPORT: What may be our reference viewport? ImGui.SetNextWindowPos(viewport:GetCenter(), ImGuiCond.FirstUseEver, ImVec2(0.5, 0.5)) end flags = bit32.bor(flags, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Modal, ImGuiWindowFlags.NoCollapse, ImGuiWindowFlags.NoDocking) local is_open p_open, is_open = ImGui.Begin(name, p_open, flags) - if not is_open or (p_open ~= nil and not p_open) then + if not is_open or (p_open ~= nil and not p_open) then -- NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) ImGui.EndPopup() if is_open then ImGui.ClosePopupToLevel(g.BeginPopupStack.Size, true) end return false, p_open @@ -16402,7 +18996,7 @@ function ImGui.IsPopupOpenRequestForWindow(popup_flags) end end if g.NavOpenContextMenuWindowId and g.NavOpenContextMenuWindowId ~= 0 and g.CurrentWindow.ID ~= 0 then - if ImGui.IsWindowChildOf(g.NavWindow, g.CurrentWindow, false, false) then return true end + if ImGui.IsWindowChildOf(g.NavWindow, g.CurrentWindow, false, false) then return true end -- This enable ordering to be used to disambiguate item vs window (#8803) end return false end @@ -16422,7 +19016,7 @@ function ImGui.BeginPopupContextVoid(str_id, popup_flags) local g = GImGui local window = g.CurrentWindow if not str_id then str_id = "void_context" end - local id = window:GetID(str_id) + local id = window:GetID(str_id) -- FIXME: Use a global ID? local mouse_button = ImGui.GetMouseButtonFromPopupFlags(popup_flags) if ImGui.IsMouseReleased(mouse_button, id) and not ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) then if ImGui.GetTopMostPopupModal() == nil then ImGui.OpenPopupEx(id, popup_flags) end @@ -16438,7 +19032,9 @@ function ImGui.BeginTooltipHidden() return ret end +------------------------------------------------------------------------------- -- [SECTION] MISC GETTERS/SETTERS, FOCUS +------------------------------------------------------------------------------- function ImGui.NavMoveRequestResolveWithLastItem(result) local g = GImGui @@ -16447,12 +19043,18 @@ function ImGui.NavMoveRequestResolveWithLastItem(result) ImGui.NavUpdateAnyRequestFlag() end +-- Note: this will likely be called ActivateItem() once we rework our Focus/Activation system! +-- But ActivateItem() should function without altering scroll/focus? function ImGui.SetKeyboardFocusHere(offset) if offset == nil then offset = 0 end local g = GImGui local window = g.CurrentWindow IM_ASSERT(offset >= -1) -- -1 is allowed but not below + -- It makes sense in the vast majority of cases to never interrupt a drag and drop. + -- When we refactor this function into ActivateItem() we may want to make this an option. + -- MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but + -- is also automatically dropped in the event g.ActiveId is stolen. if g.DragDropActive or g.MovingWindow ~= nil then return end @@ -16461,7 +19063,7 @@ function ImGui.SetKeyboardFocusHere(offset) local move_flags = bit32.bor(ImGuiNavMoveFlags.IsTabbing, ImGuiNavMoveFlags.Activate, ImGuiNavMoveFlags.FocusApi, ImGuiNavMoveFlags.NoSetNavCursorVisible) local scroll_flags = window.Appearing and bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.AlwaysCenterY) or bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleEdgeY) - ImGui.NavMoveRequestSubmit(ImGuiDir.None, (offset < 0) and ImGuiDir.Up or ImGuiDir.Down, move_flags, scroll_flags) + ImGui.NavMoveRequestSubmit(ImGuiDir.None, (offset < 0) and ImGuiDir.Up or ImGuiDir.Down, move_flags, scroll_flags) -- FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable. if offset == -1 then ImGui.NavMoveRequestResolveWithLastItem(g.NavMoveResultLocal) else @@ -16470,10 +19072,11 @@ function ImGui.SetKeyboardFocusHere(offset) end end +-- Focus = move navigation cursor, set scrolling, set focus window. function ImGui.FocusItem() local g = GImGui local window = g.CurrentWindow - if g.DragDropActive or g.MovingWindow ~= nil then + if g.DragDropActive or g.MovingWindow ~= nil then -- FIXME: Opt-in flags for this? return end local move_flags = bit32.bor(ImGuiNavMoveFlags.IsTabbing, ImGuiNavMoveFlags.FocusApi, ImGuiNavMoveFlags.NoSetNavCursorVisible, ImGuiNavMoveFlags.NoSelect) @@ -16518,10 +19121,13 @@ function ImGui.GetStyleColorName(idx) return StyleColorNames[idx] or "Unknown" end +------------------------------------------------------------------------------- -- [SECTION] NAV END FRAME +------------------------------------------------------------------------------- local NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15 +-- Window has already passed the IsWindowNavFocusable() local function GetFallbackWindowNameForWindowingList(window) if bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then return "(Popup)" @@ -16530,11 +19136,12 @@ local function GetFallbackWindowNameForWindowingList(window) return "(Main menu bar)" end if window.DockNodeAsHost then - return "(Dock node)" + return "(Dock node)" -- Not normally shown to user. end return "(Untitled)" end +-- Overlay displayed when using Ctrl+Tab. Called by EndFrame(). function ImGui.NavUpdateWindowingOverlay() local g = GImGui IM_ASSERT(g.NavWindowingTarget ~= nil) @@ -16551,7 +19158,7 @@ function ImGui.NavUpdateWindowingOverlay() g.NavWindowingListWindow = g.CurrentWindow for n = g.WindowsFocusOrder.Size, 1, -1 do local window = g.WindowsFocusOrder.Data[n] - IM_ASSERT(window ~= nil) + IM_ASSERT(window ~= nil) -- Fix static analyzers if ImGui.IsWindowNavFocusable(window) then local label = window.Name if ImGui.FindRenderedTextEnd(label) == 1 then @@ -16574,12 +19181,15 @@ local function NavUpdateCreateWrappingRequest() local clip_dir = g.NavMoveDir local move_flags = g.NavMoveFlags + -- local move_axis = (g.NavMoveDir == ImGuiDir.Up or g.NavMoveDir == ImGuiDir.Down) and ImGuiAxis.Y or ImGuiAxis.X + + -- Menu layer does not maintain scrolling / content size (#9178) local wrap_size = (g.NavLayer == ImGuiNavLayer.Menu) and window.Size or (window.ContentSize + window.WindowPadding) if g.NavMoveDir == ImGuiDir.Left and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapX, ImGuiNavMoveFlags.LoopX)) ~= 0 then bb_rel.Min.x = wrap_size.x; bb_rel.Max.x = wrap_size.x if bit32.band(move_flags, ImGuiNavMoveFlags.WrapX) ~= 0 then - bb_rel:TranslateY(-bb_rel:GetHeight()) + bb_rel:TranslateY(-bb_rel:GetHeight()) -- Previous row clip_dir = ImGuiDir.Up end do_forward = true @@ -16587,7 +19197,7 @@ local function NavUpdateCreateWrappingRequest() if g.NavMoveDir == ImGuiDir.Right and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapX, ImGuiNavMoveFlags.LoopX)) ~= 0 then bb_rel.Min.x = -window.WindowPadding.x; bb_rel.Max.x = -window.WindowPadding.x if bit32.band(move_flags, ImGuiNavMoveFlags.WrapX) ~= 0 then - bb_rel:TranslateY(bb_rel:GetHeight()) + bb_rel:TranslateY(bb_rel:GetHeight()) -- Next row clip_dir = ImGuiDir.Down end do_forward = true @@ -16595,7 +19205,7 @@ local function NavUpdateCreateWrappingRequest() if g.NavMoveDir == ImGuiDir.Up and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapY, ImGuiNavMoveFlags.LoopY)) ~= 0 then bb_rel.Min.y = wrap_size.y; bb_rel.Max.y = wrap_size.y if bit32.band(move_flags, ImGuiNavMoveFlags.WrapY) ~= 0 then - bb_rel:TranslateX(-bb_rel:GetWidth()) + bb_rel:TranslateX(-bb_rel:GetWidth()) -- Previous column clip_dir = ImGuiDir.Left end do_forward = true @@ -16603,7 +19213,7 @@ local function NavUpdateCreateWrappingRequest() if g.NavMoveDir == ImGuiDir.Down and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapY, ImGuiNavMoveFlags.LoopY)) ~= 0 then bb_rel.Min.y = -window.WindowPadding.y; bb_rel.Max.y = -window.WindowPadding.y if bit32.band(move_flags, ImGuiNavMoveFlags.WrapY) ~= 0 then - bb_rel:TranslateX(bb_rel:GetWidth()) + bb_rel:TranslateX(bb_rel:GetWidth()) -- Next column clip_dir = ImGuiDir.Right end do_forward = true @@ -16620,21 +19230,28 @@ end function ImGui.NavEndFrame() local g = GImGui + -- Show Ctrl+Tab list window if g.NavWindowingTarget ~= nil then ImGui.NavUpdateWindowingOverlay() end + -- Perform wrap-around in menus + -- FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly. + -- FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame. if g.NavWindow and ImGui.NavMoveRequestButNoResultYet() and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.WrapMask_) ~= 0 and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) == 0 then NavUpdateCreateWrappingRequest() end end +------------------------------------------------------------------------------- -- [SECTION] ImGuiTextFilter +------------------------------------------------------------------------------- --- @class ImGuiTextFilter MT.ImGuiTextFilter = {} MT.ImGuiTextFilter.__index = MT.ImGuiTextFilter +-- Helper: Parse and apply text filters e.g. 'aaa bbb -ccc'. --- @param default_filter? string function ImGuiTextFilter(default_filter) local this = setmetatable({ InputBuf = {}, _CountExclude = 0, _Items = ImVector() }, MT.ImGuiTextFilter) @@ -16652,6 +19269,7 @@ function MT.ImGuiTextFilter:Draw(label, width) return self:DrawWithHint(label, "incl -excl") end +-- Use ImGui.SetNextItemWidth() manually if you want to use this. function MT.ImGuiTextFilter:DrawWithHint(label, hint) if label == nil then label = "Filter" end if hint == nil then hint = "incl -excl" end @@ -16665,6 +19283,7 @@ end function MT.ImGuiTextFilter:Clear() self.InputBuf[1] = 0; self:Build() end function MT.ImGuiTextFilter:IsActive() return self._Items.Size ~= 0 end +-- Parse filter and split into a format optimal for PassFilter() -- Items are { Text = string (lowercased), CountInclude = int } function MT.ImGuiTextFilter:Build() local items = self._Items @@ -16678,6 +19297,7 @@ function MT.ImGuiTextFilter:Build() local word_b = 1 local seq_start_idx = -1 -- 1-based index into items, -1 = none while word_b < buf_e do + -- Trim blanks while word_b < buf_e and ImCharIsBlankA(string.byte(buf, word_b)) do word_b = word_b + 1 end @@ -16686,10 +19306,12 @@ function MT.ImGuiTextFilter:Build() local is_quote = word_b < buf_e and string.byte(buf, word_b) == 34 -- '"' local word_e if is_quote then + -- Parsing quotes. Omit storing leading/trailing quotes. word_b = word_b + 1 word_e = string.find(buf, '"', word_b, true) or buf_e if word_e > buf_e then word_e = buf_e end else + -- Handle both ' ' and ',' separators. word_e = word_b while word_e < buf_e do local c = string.byte(buf, word_e) @@ -16698,7 +19320,9 @@ function MT.ImGuiTextFilter:Build() end end + -- Min length if word_e - word_b > 0 then + -- Add to list. The '-' is not stored in items but implicitly inferred using (n < CountExclude). local item = { Text = string.lower(string.sub(buf, word_b, word_e - 1)), CountInclude = 0 } if is_excl then items:insert(self._CountExclude + 1, item) @@ -16711,6 +19335,7 @@ function MT.ImGuiTextFilter:Build() end end + -- Next sequence if word_e < buf_e and string.byte(buf, word_e) == 44 then -- ',' seq_start_idx = -1 end @@ -16718,6 +19343,7 @@ function MT.ImGuiTextFilter:Build() end end +-- FIXME: Could use a specialized ImStristr() + pre-convert our filter to uppercase. --- @param text string? --- @param text_end? int # exclusive, 1-based function MT.ImGuiTextFilter:PassFilter(text, text_end) @@ -16727,6 +19353,7 @@ function MT.ImGuiTextFilter:PassFilter(text, text_end) if text_end ~= nil then text = string.sub(text, 1, text_end - 1) end text = string.lower(text) + -- Filters are sorted so that '-' ones are always leading. local seq = 1 local seq_excl_end = self._CountExclude + 1 while seq < seq_excl_end do @@ -16734,24 +19361,29 @@ function MT.ImGuiTextFilter:PassFilter(text, text_end) seq = seq + 1 end + -- Process includes local seq_end = items.Size + 1 - if seq == seq_end then return true end + if seq == seq_end then return true end -- When no inclusion are specified (only exclusions) we implicitly pass while seq < seq_end do local seq_incl_end = seq + items.Data[seq].CountInclude while seq < seq_incl_end do if not string.find(text, items.Data[seq].Text, 1, true) then break end seq = seq + 1 end - if seq == seq_incl_end then return true end - seq = seq_incl_end + if seq == seq_incl_end then return true end -- All matched + seq = seq_incl_end -- Try next end return false end +------------------------------------------------------------------------------- -- [SECTION] ImGuiListClipper +------------------------------------------------------------------------------- ImGuiListClipperFlags = ImGuiListClipperFlags or { None = 0, NoSetTableRowCounters = bit32.lshift(1, 0) } +-- FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell. +-- The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous. local function GetSkipItemForListClipping() local g = GImGui if g.CurrentTable then return g.CurrentTable.HostSkipItems end @@ -16766,11 +19398,13 @@ local function ImGuiListClipper_SortAndFuseRanges(ranges, offset) if offset == nil then offset = 0 end if ranges.Size - offset <= 1 then return end local d = ranges.Data + -- Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries) for sort_end = ranges.Size - offset - 1, 1, -1 do for i = offset + 1, sort_end + offset do if d[i].Min > d[i + 1].Min then d[i], d[i + 1] = d[i + 1], d[i] end end end + -- Now fuse ranges together as much as possible. local i = 2 + offset while i <= ranges.Size do IM_ASSERT(not d[i].PosToIndexConvert and not d[i - 1].PosToIndexConvert) @@ -16785,16 +19419,19 @@ local function ImGuiListClipper_SortAndFuseRanges(ranges, offset) end local function ImGuiListClipper_SeekCursorAndSetupPrevLine(clipper, pos_y, line_height) + -- Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. + -- FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. + -- The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek? local g = GImGui local window = g.CurrentWindow local off_y = pos_y - window.DC.CursorPos.y window.DC.CursorPos.y = pos_y window.DC.CursorMaxPos.y = ImMax(window.DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y) - window.DC.CursorPosPrevLine.y = window.DC.CursorPos.y - line_height - window.DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y) + window.DC.CursorPosPrevLine.y = window.DC.CursorPos.y - line_height -- Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. + window.DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y) -- If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. local columns = window.DC.CurrentColumns if columns then - columns.LineMinY = window.DC.CursorPos.y + columns.LineMinY = window.DC.CursorPos.y -- Setting this so that cell Y position are set properly end local tbl = g.CurrentTable if tbl then @@ -16802,7 +19439,7 @@ local function ImGuiListClipper_SeekCursorAndSetupPrevLine(clipper, pos_y, line_ ImGui.TableEndRow(tbl) end local row_increase = math.floor((off_y / line_height) + 0.5) - if row_increase > 0 and bit32.band(clipper.Flags, ImGuiListClipperFlags.NoSetTableRowCounters) == 0 then + if row_increase > 0 and bit32.band(clipper.Flags, ImGuiListClipperFlags.NoSetTableRowCounters) == 0 then -- If your clipper item height is ~= from actual table row height, consider using ImGuiListClipperFlags.NoSetTableRowCounters. See #8886. tbl.CurrentRow = tbl.CurrentRow + row_increase tbl.RowBgColorCounter = tbl.RowBgColorCounter + row_increase end @@ -16838,6 +19475,7 @@ function MT.ImGuiListClipper:Begin(items_count, items_height) self.DisplayStart = -1 self.DisplayEnd = 0 + -- Acquire temporary buffer g.ClipperTempDataStacked = g.ClipperTempDataStacked + 1 while g.ClipperTempDataStacked > g.ClipperTempData.Size do g.ClipperTempData:push_back({ ListClipper = nil, LossynessOffset = 0.0, StepNo = 0, ItemsFrozen = 0, Ranges = ImVector() }) @@ -16852,10 +19490,13 @@ end function MT.ImGuiListClipper:End() local data = self.TempData if data then + -- In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user. local g = self.Ctx if self.ItemsCount >= 0 and self.ItemsCount < INT_MAX and self.DisplayStart >= 0 then self:SeekCursorForItem(self.ItemsCount) end + + -- Restore temporary buffer and fix back pointers which may be invalidated when nesting IM_ASSERT(data.ListClipper == self) data.StepNo = data.Ranges.Size g.ClipperTempDataStacked = g.ClipperTempDataStacked - 1 @@ -16865,7 +19506,7 @@ function MT.ImGuiListClipper:End() end self.TempData = nil end - self.DisplayStart = self.ItemsCount + self.DisplayStart = self.ItemsCount -- Clear this so code which may be reused past last Step() won't trip on a non-empty range. self.DisplayEnd = self.ItemsCount self.ItemsCount = -1 end @@ -16874,14 +19515,18 @@ function MT.ImGuiListClipper:IncludeItemByIndex(item_index) self:IncludeItemsByI function MT.ImGuiListClipper:IncludeItemsByIndex(item_begin, item_end) local data = self.TempData - IM_ASSERT(self.DisplayStart < 0) + IM_ASSERT(self.DisplayStart < 0) -- Only allowed after Begin() and if there has not been a specified range yet. IM_ASSERT(item_begin <= item_end) if item_begin < item_end then data.Ranges:push_back(ClipperRangeFromIndices(item_begin, item_end)) end end +-- This is already called while stepping. +-- The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper:Begin() because you couldn't step item count beforehand. function MT.ImGuiListClipper:SeekCursorForItem(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. local pos_y = self.StartPosY + self.StartSeekOffsetY + item_n * self.ItemsHeight ImGuiListClipper_SeekCursorAndSetupPrevLine(self, pos_y, self.ItemsHeight) end @@ -16897,10 +19542,13 @@ local function ImGuiListClipper_StepInternal(clipper) ImGui.TableEndRow(tbl) end + -- No items if clipper.ItemsCount == 0 or GetSkipItemForListClipping() then return false end + -- While we are in frozen row state, keep displaying items one by one, unclipped + -- FIXME: Could be stored as a table-agnostic state. if data.StepNo == 0 and tbl ~= nil and not tbl.IsUnfrozenRows then clipper.DisplayStart = data.ItemsFrozen clipper.DisplayEnd = ImMin(data.ItemsFrozen + 1, clipper.ItemsCount) @@ -16910,40 +19558,47 @@ local function ImGuiListClipper_StepInternal(clipper) return true end + -- Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height) local calc_clipping = false if data.StepNo == 0 then clipper.StartPosY = window.DC.CursorPos.y if clipper.ItemsHeight <= 0.0 then + -- Submit the first item (or range) so we can measure its height (generally the first range is 0..1) data.Ranges:push_front(ClipperRangeFromIndices(data.ItemsFrozen, data.ItemsFrozen + 1)) clipper.DisplayStart = ImMax(data.Ranges.Data[1].Min, data.ItemsFrozen) clipper.DisplayEnd = ImMin(data.Ranges.Data[1].Max, clipper.ItemsCount) data.StepNo = 1 return true end - calc_clipping = true + calc_clipping = true -- If on the first step with known item height, calculate clipping. end + -- Step 1: Let the clipper infer height from first range if clipper.ItemsHeight <= 0.0 then IM_ASSERT(data.StepNo == 1) -- (no float precision mitigation needed: Luau numbers are doubles) clipper.ItemsHeight = (window.DC.CursorPos.y - clipper.StartPosY) / (clipper.DisplayEnd - clipper.DisplayStart) - if clipper.ItemsHeight == 0.0 and clipper.ItemsCount == INT_MAX then + if clipper.ItemsHeight == 0.0 and clipper.ItemsCount == INT_MAX then -- Accept that no item have been submitted if in indeterminate mode. return false end if clipper.ItemsHeight <= 0.0 then IM_ASSERT_USER_ERROR(clipper.ItemsHeight > 0.0, "ImGuiListClipper: Failed to calculate item height! First item hasn't been submitted by user code, or has not moved the cursor vertically!") return false end - calc_clipping = true + calc_clipping = true -- If item height had to be calculated, calculate clipping afterwards. end + -- Step 0 or 1: Calculate the actual ranges of visible elements. local already_submitted = clipper.DisplayEnd if calc_clipping then + -- Record seek offset, this is so ImGuiListClipper:Seek() can be called after ImGuiListClipperData is done clipper.StartSeekOffsetY = data.LossynessOffset - data.ItemsFrozen * clipper.ItemsHeight if g.LogEnabled then + -- If logging is active, do not perform any clipping data.Ranges:push_back(ClipperRangeFromIndices(0, clipper.ItemsCount)) else + -- Add range selected to be included for navigation local is_nav_request = (g.NavMoveScoringItems and g.NavWindow and g.NavWindow.RootWindowForNav == window.RootWindowForNav) and true or false local nav_off_min = (is_nav_request and g.NavMoveClipDir == ImGuiDir.Up) and -1 or 0 local nav_off_max = (is_nav_request and g.NavMoveClipDir == ImGuiDir.Down) and 1 or 0 @@ -16957,6 +19612,7 @@ local function ImGuiListClipper_StepInternal(clipper) data.Ranges:push_back(ClipperRangeFromIndices(clipper.ItemsCount - 1, clipper.ItemsCount)) end + -- Add focused/active item local nav_rect_abs = ImGui.WindowRectRelToAbs(window, window.NavRectRel[0]) if g.NavId ~= 0 and window.NavLastIds[0] == g.NavId then data.Ranges:push_back(ClipperRangeFromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0)) @@ -16965,19 +19621,31 @@ local function ImGuiListClipper_StepInternal(clipper) local min_y = window.ClipRect.Min.y local max_y = window.ClipRect.Max.y + -- Add box selection range local bs = g.BoxSelectState if bs and bs.IsActive and bs.Window == window then + -- FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos. + -- RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that. + -- As a workaround we currently half ItemSpacing worth on each side. local pad_y = g.Style.ItemSpacing.y min_y = min_y - pad_y max_y = max_y + pad_y + + -- Box-select on 2D area requires different clipping. + -- (best adding pad_y here than in BeginBoxSelect() as we are closer to current state) if bs.UnclipMode then data.Ranges:push_back(ClipperRangeFromPositions(bs.UnclipRect.Min.y - pad_y, bs.UnclipRect.Max.y + pad_y, 0, 0)) end end + -- Add main visible range data.Ranges:push_back(ClipperRangeFromPositions(min_y, max_y, nav_off_min, nav_off_max)) end + -- Convert position ranges to item index ranges + -- - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping. + -- - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list, + -- which with the flooring/ceiling tend to lead to 2 items instead of one being submitted. for _, range in data.Ranges:iter() do if range.PosToIndexConvert then local m1 = ImTrunc((range.Min - window.DC.CursorPos.y - data.LossynessOffset) / clipper.ItemsHeight) @@ -16990,6 +19658,7 @@ local function ImGuiListClipper_StepInternal(clipper) ImGuiListClipper_SortAndFuseRanges(data.Ranges, data.StepNo) end + -- Step 0+ (if item height is given in advance) or 1+: Display the next range in line. while data.StepNo < data.Ranges.Size do local r = data.Ranges.Data[data.StepNo + 1] clipper.DisplayStart = ImMax(r.Min, already_submitted) @@ -17003,6 +19672,8 @@ local function ImGuiListClipper_StepInternal(clipper) end end + -- After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), + -- Advance the cursor to the end of the list and then returns 'false' to end the loop. if clipper.ItemsCount < INT_MAX then clipper:SeekCursorForItem(clipper.ItemsCount) end @@ -17020,13 +19691,22 @@ function MT.ImGuiListClipper:Step() return ret end +-- Generic helper, equivalent to old ImGui.CalcListClipping() but stateless +-- Returns (out_visible_start, out_visible_end) function ImGui.CalcClipRectVisibleItemsY(clip_rect, pos, items_height) local out_visible_start = ImMax(ImTrunc((clip_rect.Min.y - pos.y) / items_height), 0) local out_visible_end = ImMax(ImTrunc(ImCeil((clip_rect.Max.y - pos.y) / items_height)), out_visible_start) return out_visible_start, out_visible_end end +------------------------------------------------------------------------------- -- [SECTION] ERROR CHECKING, STATE RECOVERY +------------------------------------------------------------------------------- +-- - ErrorRecoveryStoreState() +-- - ErrorRecoveryTryToRecoverState() +-- - ErrorRecoveryTryToRecoverWindowState() +-- - ErrorLog() +------------------------------------------------------------------------------- function ImGuiErrorRecoveryState() return { SizeOfWindowStack = 0, SizeOfIDStack = 0, SizeOfTreeStack = 0, SizeOfColorStack = 0, SizeOfStyleVarStack = 0, @@ -17034,6 +19714,7 @@ function ImGuiErrorRecoveryState() SizeOfBeginPopupStack = 0, SizeOfDisabledStack = 0 } end +-- Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery. function ImGui.ErrorRecoveryStoreState(state_out) local g = GImGui state_out.SizeOfWindowStack = g.CurrentWindowStack.Size @@ -17049,9 +19730,17 @@ function ImGui.ErrorRecoveryStoreState(state_out) state_out.SizeOfDisabledStack = g.DisabledStackSize end +-- Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery. +-- Called by e.g. EndFrame() but may be called for manual recovery. +-- Attempt to recover full window stack. function ImGui.ErrorRecoveryTryToRecoverState(state_in) local g = GImGui while g.CurrentWindowStack.Size > state_in.SizeOfWindowStack do + -- Recap: + -- - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped. + -- - Always call a matching End() for each Begin() call, regardless of its return value! + -- - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS. + -- - We will fix that in a future major update. local window = g.CurrentWindow if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then if g.CurrentTable ~= nil and g.CurrentTable.InnerWindow == g.CurrentWindow then @@ -17071,6 +19760,8 @@ function ImGui.ErrorRecoveryTryToRecoverState(state_in) end end +-- Called by e.g. End() but may be called for manual recovery. +-- Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls. function ImGui.ErrorRecoveryTryToRecoverWindowState(state_in) local g = GImGui @@ -17137,6 +19828,7 @@ function ImGui.ErrorRecoveryTryToRecoverWindowState(state_in) IM_ASSERT_USER_ERROR(false, "Missing PopFocusScope()") ImGui.PopFocusScope() end + -- IM_ASSERT(g.FocusScopeStack.Size == state_in.SizeOfFocusScopeStack) end -- Lines are stored in g.DebugLogBuf (one chunk per call) @@ -17162,6 +19854,7 @@ end function ImGui.ErrorLog(msg) local g = GImGui if g == nil then return true end + -- Output to debug log local window = g.CurrentWindow if g.IO.ConfigErrorRecoveryEnableDebugLog then @@ -17173,6 +19866,7 @@ function ImGui.ErrorLog(msg) end g.ErrorFirst = false + -- Output to tooltip if g.IO.ConfigErrorRecoveryEnableTooltip then if g.WithinFrameScope and ImGui.BeginErrorTooltip() then if g.ErrorCountCurrentFrame < 20 then @@ -17184,18 +19878,23 @@ function ImGui.ErrorLog(msg) if g.ErrorCountCurrentFrame == 20 then ImGui.Text("(and more errors)") end + -- EndFrame() will amend debug buttons to this window, after all errors have been submitted. ImGui.EndErrorTooltip() end g.ErrorCountCurrentFrame = g.ErrorCountCurrentFrame + 1 end + -- Output to callback if g.ErrorCallback ~= nil then g.ErrorCallback(g, g.ErrorCallbackUserData, msg) end + -- Return whether we should assert return g.IO.ConfigErrorRecoveryEnableAssert end +-- Display an error tooltip when same ID as HoveredId was submitted multiple times. +-- See code in ItemHoverable() for an explanation of why we associate this error to HoveredId + code drawing of rectangles over individual items instances. function ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() local g = GImGui if g.DebugDrawIdConflictsId ~= 0 and g.IO.KeyCtrl == false then @@ -17205,6 +19904,7 @@ function ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() ImGui.Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount) ImGui.BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!") ImGui.BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!") + -- ImGui.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. ImGui.BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.") ImGui.Separator() ImGui.Text("(Hold Ctrl to: ") @@ -17215,19 +19915,24 @@ function ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() ImGui.EndErrorTooltip() end - if g.ErrorCountCurrentFrame > 0 and ImGui.BeginErrorTooltip() then + if g.ErrorCountCurrentFrame > 0 and ImGui.BeginErrorTooltip() then -- Amend at end of frame ImGui.Separator() ImGui.Text("(Hold Ctrl to: ") ImGui.SameLine(0.0, 0.0) if ImGui.SmallButton("Enable Asserts") then g.IO.ConfigErrorRecoveryEnableAssert = true end + -- ImGui.SameLine() + -- if ImGui.SmallButton("Hide Error Tooltips") then + -- g.IO.ConfigErrorRecoveryEnableTooltip = false -- Too dangerous + -- end ImGui.SameLine(0, 0) ImGui.Text(")") ImGui.EndErrorTooltip() end end +-- Pseudo-tooltip. Follow mouse until Ctrl is held. When Ctrl is held we lock position, allowing to click it. function ImGui.BeginErrorTooltip() local g = GImGui local window = ImGui.FindWindowByName("##Tooltip_Error") @@ -17257,9 +19962,9 @@ end do --[[ [SECTION] METRICS/DEBUGGER WINDOW, DEBUG LOG, ID STACK TOOL, FONT DEBUG ]] ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Font atlas / font debugging ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- byte buffers for InputText (same as the demo's DemoBuf/DemoBufStr; kept here so the library doesn't need the demo) local function DemoBuf(str, size) @@ -17276,6 +19981,7 @@ local function DemoBufStr(buf) return ImGui._ByteArrayToString(buf, 1, n + 1) end +-- Avoid naming collision with imgui_demo's HelpMarker() for unity builds. local function MetricsHelpMarker(desc) ImGui.TextDisabled("(?)") if ImGui.BeginItemTooltip() then @@ -17289,6 +19995,8 @@ ImGui.MetricsHelpMarker = MetricsHelpMarker local function U8(c) return (c and c > 0) and utf8.char(c) or "" end +-- Demo helper function to select among loaded fonts. +-- Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one. function ImGui.ShowFontSelector(label) local io = ImGui.GetIO() local font_current = ImGui.GetFont() @@ -17337,9 +20045,12 @@ function ImGui.DebugNodeFontGlyphsForSrcMask(font, baked, src_mask) end end if count > 0 and ImGui.TreeNode(base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, (count > 1) and "glyphs" or "glyph") then + -- Draw a 16x16 grid of glyphs local base_pos = ImGui.GetCursorScreenPos() for n = 0, 255 do local c = base + 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. local cell_p1 = ImVec2(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + math.floor(n / 16) * (cell_size + cell_spacing)) local cell_p2 = ImVec2(cell_p1.x + cell_size, cell_p1.y + cell_size) local glyph = baked:IsGlyphLoaded(c) and baked:FindGlyphNoFallback(c) or nil @@ -17359,11 +20070,14 @@ function ImGui.DebugNodeFontGlyphsForSrcMask(font, baked, src_mask) end end +-- [DEBUG] Display details for a single font, called by ShowStyleEditor(). function ImGui.DebugNodeFont(font) local g = ImGui.GetCurrentContext() local cfg = g.DebugMetricsConfig local atlas = font.OwnerAtlas local opened = ImGui.TreeNode(tostring(font), "Font: \"%s\": %d sources(s)", font:GetDebugName(), font.Sources.Size) + + -- Display preview text if not opened then ImGui.Indent() end ImGui.Indent() if cfg.ShowFontPreview then @@ -17386,6 +20100,7 @@ function ImGui.DebugNodeFont(font) ImGui.SameLine() if ImGui.SmallButton("Clear unused") then ImFontAtlasFontDiscardBakes(atlas, font, 2) end + -- Display details ImGui.Text("Fallback character: '%s' (U+%04X)", U8(font.FallbackChar), font.FallbackChar or 0) ImGui.Text("Ellipsis character: '%s' (U+%04X)", U8(font.EllipsisChar), font.EllipsisChar or 0) for src_n, src in font.Sources:iter() do @@ -17393,10 +20108,15 @@ function ImGui.DebugNodeFont(font) src_n - 1, src.Name or "", src.FontNo or 0, src.OversampleH or 0, src.OversampleV or 0, src.PixelSnapH and 1 or 0, src.GlyphOffset.x, src.GlyphOffset.y) then local loader = src.FontLoader or atlas.FontLoader ImGui.Text("Loader: '%s'", (loader and loader.Name) or "N/A") + + -- if ImGui.DragFloat("ExtraSizeScale", src.ExtraSizeScale, 0.01, 0.10, 2.0) then + -- ImFontAtlasFontRebuildOutput(atlas, font) + -- end ImGui.TreePop() end end + -- Display all glyphs of the fonts in separate pages of 256 characters local builder = atlas.Builder if builder then for _, baked in builder.BakedPool:iter() do @@ -17460,6 +20180,7 @@ function ImGui.DebugNodeTexture(tex, int_id, highlight_rect) ImGui.PopID() end +-- [DEBUG] List fonts in a font atlas and display its texture function ImGui.ShowFontAtlas(atlas) local g = ImGui.GetCurrentContext() local io = g.IO @@ -17470,7 +20191,7 @@ function ImGui.ShowFontAtlas(atlas) ImGui.ShowFontSelector("Font") local changed style.FontSizeBase, changed = ImGui.DragFloat("FontSizeBase", style.FontSizeBase, 0.20, 5.0, 100.0, "%.0f") - if changed then style._NextFrameFontSizeBase = style.FontSizeBase end + if changed then style._NextFrameFontSizeBase = style.FontSizeBase end -- FIXME: Temporary hack until we finish remaining work. ImGui.SameLine(0.0, 0.0); ImGui.Text(" (out %.2f)", ImGui.GetFontSize()) ImGui.SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later.") style.FontScaleMain = ImGui.DragFloat("FontScaleMain", style.FontScaleMain, 0.02, 0.5, 4.0) @@ -17484,6 +20205,7 @@ function ImGui.ShowFontAtlas(atlas) ImGui.SeparatorText("Font List") local cfg = g.DebugMetricsConfig _, cfg.ShowFontPreview = ImGui.Checkbox("Show font preview", cfg.ShowFontPreview == true) + -- Font loaders if ImGui.TreeNode("Loader", "Loader: '%s'", atlas.FontLoaderName or "NULL") then ImGui.BeginDisabled() ImGui.RadioButtonEx("stb_truetype", true) @@ -17493,6 +20215,7 @@ function ImGui.ShowFontAtlas(atlas) ImGui.EndDisabled() ImGui.TreePop() end + -- Font list for i, font in atlas.Fonts:iter() do ImGui.PushID(i) ImGui.DebugNodeFont(font) @@ -17517,16 +20240,19 @@ function ImGui.ShowFontAtlas(atlas) ImGui.Text("Packed rects: %d, area: about %d px ~%dx%d px", b.RectsPackedCount or 0, b.RectsPackedSurface or 0, packed_sqrt, packed_sqrt) ImGui.Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", b.RectsDiscardedCount or 0, b.RectsDiscardedSurface or 0, discarded_sqrt, discarded_sqrt) end + -- Texture list + -- (ensure the last texture always use the same ID, so we can keep it open neatly) for tex_n, tex in atlas.TexList:iter() do if tex_n == atlas.TexList.Size then ImGui.SetNextItemOpen(true, ImGuiCond.Once) end ImGui.DebugNodeTexture(tex, atlas.TexList.Size - tex_n, nil) end end ----------------------------------------------------------------- --- [SECTION] Debug Log window ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] DEBUG LOG WINDOW +------------------------------------------------------------------------------- +-- FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout. local function SameLineOrWrap(size) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow @@ -17537,7 +20263,7 @@ end local function ShowDebugLogFlag(name, flags) local g = ImGui.GetCurrentContext() local size = ImVec2(ImGui.GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui.CalcTextSize(name).x, ImGui.GetFrameHeight()) - SameLineOrWrap(size) + SameLineOrWrap(size) -- FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout. local pressed pressed, g.DebugLogFlags = ImGui.CheckboxFlags(name, g.DebugLogFlags, flags) if pressed and g.IO.KeyShift and bit32.band(g.DebugLogFlags, flags) ~= 0 then @@ -17602,9 +20328,9 @@ function ImGui.ShowDebugLogWindow(p_open) return p_open end ----------------------------------------------------------------- --- [SECTION] ID Stack Tool ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL) +------------------------------------------------------------------------------- local function PathQuery(g) local q = g.DebugItemPathQuery @@ -17617,7 +20343,9 @@ local function PathQuery(g) end -- 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 local function DebugItemPathQuery_UpdateAndGetHookId(query, id) + -- Update query. Clear hook when no active query if query.MainID ~= id then query.MainID = id query.Step = -1 @@ -17627,9 +20355,11 @@ local function DebugItemPathQuery_UpdateAndGetHookId(query, id) query.Active = false if id == 0 then return 0 end local res = query.Results + -- Advance to next stack level when we got our result, or after 2 frames (in case we never get a result) if query.Step >= 0 and query.Step < #res then if res[query.Step + 1].QuerySuccess or res[query.Step + 1].QueryFrameCount > 2 then query.Step = query.Step + 1 end end + -- Update status and hook query.Complete = (query.Step == #res) if query.Step == -1 then query.Active = true @@ -17642,6 +20372,7 @@ local function DebugItemPathQuery_UpdateAndGetHookId(query, id) return 0 end +-- [DEBUG] ID Stack Tool: update query. Called by NewFrame() function ImGui.UpdateDebugToolItemPathQuery() local g = ImGui.GetCurrentContext() local q = PathQuery(g) @@ -17652,12 +20383,16 @@ function ImGui.UpdateDebugToolItemPathQuery() g.DebugHookIdInfoId = DebugItemPathQuery_UpdateAndGetHookId(q, id) end --- Hooks called by GetID() family functions. `data_id` is the string/number that was hashed. +-- [DEBUG] ID Stack tool: hooks called by GetID() family functions +-- `data_id` is the string/number that was hashed. function ImGui.DebugHookIdInfo(id, data_type, data_id) local g = ImGui.GetCurrentContext() local query = PathQuery(g) if not query.Active then return end local window = g.CurrentWindow + + -- Step -1: stack query + -- This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget. if query.Step == -1 then query.Step = 0 query.Results = {} @@ -17666,13 +20401,14 @@ function ImGui.DebugHookIdInfo(id, data_type, data_id) end return end + -- Step 0+: query for individual level if query.Step ~= window.IDStack.Size then return end local info = query.Results[query.Step + 1] if info == nil or info.ID ~= id then return end if info.Desc == nil then if data_type == ImGuiDataType.S32 then info.Desc = string.format("%d", data_id) elseif data_type == ImGuiDataType.String then info.Desc = tostring(data_id) - else info.Desc = string.format("0x%08X [override]", id) end + else info.Desc = string.format("0x%08X [override]", id) end -- PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one. end info.QuerySuccess = true if info.DataType == -1 then info.DataType = data_type end @@ -17687,9 +20423,9 @@ end local function FormatLevelInfo(g, query, n, format_for_ui) local info = query.Results[n + 1] local window = (info.Desc == nil and n == 0) and ImGui.FindWindowByID(info.ID) or nil - if window then return string.format(format_for_ui and "\"%s\" [window]" or "%s", SkipUncontributingPrefix(window.Name)) end - if info.QuerySuccess then return string.format((format_for_ui and info.DataType == ImGuiDataType.String) and "\"%s\"" or "%s", SkipUncontributingPrefix(info.Desc)) end - if query.Step < #query.Results then return "" end + if window then return string.format(format_for_ui and "\"%s\" [window]" or "%s", SkipUncontributingPrefix(window.Name)) end -- Source: window name (because the root ID don't call GetID() and so doesn't get hooked) + if info.QuerySuccess then return string.format((format_for_ui and info.DataType == ImGuiDataType.String) and "\"%s\"" or "%s", SkipUncontributingPrefix(info.Desc)) end -- Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id) + if query.Step < #query.Results then return "" end -- Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. return "???" end @@ -17707,6 +20443,7 @@ local function GetResultAsPath(g, query, hex_encode_non_ascii_chars) return table.concat(out) end +-- ID Stack Tool: Display UI function ImGui.ShowIDStackToolWindow(p_open) local g = ImGui.GetCurrentContext() if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 then @@ -17725,6 +20462,8 @@ function ImGui.ShowIDStackToolWindow(p_open) ImGui.Text("0x%08X", query.MainID) ImGui.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 local time_since_copy = g.Time - tool.CopyToClipboardLastTime ImGui.PushStyleVarY(ImGuiStyleVar.FramePadding, 0.0) _, tool.OptHexEncodeNonAsciiChars = ImGui.Checkbox("Hex-encode non-ASCII", tool.OptHexEncodeNonAsciiChars) @@ -17739,6 +20478,8 @@ function ImGui.ShowIDStackToolWindow(p_open) end ImGui.Text("- Path \"%s\"", query.Complete and result_path or "") ImGui.Separator() + + -- Display decorated stack if #query.Results > 0 and ImGui.BeginTable("##table", 3, ImGuiTableFlags.Borders) then local id_width = ImGui.CalcTextSize("0xDDDDDDDD").x ImGui.TableSetupColumn("Seed", ImGuiTableColumnFlags.WidthFixed, id_width) @@ -17761,14 +20502,30 @@ function ImGui.ShowIDStackToolWindow(p_open) return p_open end ----------------------------------------------------------------- --- [SECTION] Metrics/Debugger window ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] METRICS/DEBUGGER WINDOW +------------------------------------------------------------------------------- +-- - DebugTextEncoding() +-- - ShowMetricsWindow() +-- - DebugNodeColumns() [Internal] +-- - DebugNodeDockNode() [Internal] +-- - DebugNodeDrawList() [Internal] +-- - DebugNodeStorage() [Internal] +-- - DebugNodeTabBar() [Internal] +-- - DebugNodeTable() [Internal] +-- - DebugNodeTableSettings() [Internal] +-- - DebugNodeViewport() [Internal] +-- - DebugNodeWindow() [Internal] +-- - DebugNodeWindowSettings() [Internal] +-- - DebugNodeWindowsList() [Internal] +-- - DebugNodeWindowsListByBeginStackParent() [Internal] +------------------------------------------------------------------------------- local function B(v) return v and 1 or 0 end local function FG(window) return ImGui.GetForegroundDrawList(window and window.Viewport or ImGui.GetMainViewport()) end local function YellowRect(window, min, max) FG(window):AddRect(min, max, IM_COL32(255, 255, 0, 255)) end +-- [DEBUG] Display contents of Columns function ImGui.DebugNodeColumns(columns) if not ImGui.TreeNode(columns.ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns.ID, columns.Count, columns.Flags) then return end ImGui.BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns.OffMaxX - columns.OffMinX, columns.OffMinX, columns.OffMaxX) @@ -17778,6 +20535,7 @@ function ImGui.DebugNodeColumns(columns) ImGui.TreePop() end +-- [DEBUG] Display contents of ImGuiStorage function ImGui.DebugNodeStorage(storage, label) local n = 0 for _ in pairs(storage) do n = n + 1 end @@ -17788,6 +20546,8 @@ function ImGui.DebugNodeStorage(storage, label) ImGui.TreePop() end +-- [DEBUG] Display contents of ImDrawList +-- Note that both 'window' and 'viewport' may be nil here. Viewport is generally nil of destroyed popups which previously owned a viewport. function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) local g = ImGui.GetCurrentContext() local cfg = g.DebugMetricsConfig @@ -17798,11 +20558,11 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) local node_open = ImGui.TreeNode(tostring(draw_list), "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list._OwnerName or "", draw_list.VtxBuffer.Size, draw_list.IdxBuffer.Size, cmd_count) if draw_list == ImGui.GetWindowDrawList() then ImGui.SameLine() - ImGui.TextColored(ImVec4(1.0, 0.4, 0.4, 1.0), "CURRENTLY APPENDING") + ImGui.TextColored(ImVec4(1.0, 0.4, 0.4, 1.0), "CURRENTLY APPENDING") -- Can't display stats for active draw list! (we don't have the data double-buffered) if node_open then ImGui.TreePop() end return end - local fg_draw_list = viewport and ImGui.GetForegroundDrawList(viewport) or nil + local fg_draw_list = viewport and ImGui.GetForegroundDrawList(viewport) or nil -- Render additional visuals into the top-most draw list if window and ImGui.IsItemHovered() and fg_draw_list then fg_draw_list:AddRect(window.Pos, window.Pos + window.Size, IM_COL32(255, 255, 0, 255)) end @@ -17830,11 +20590,11 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) tri[n + 1] = ImVec2(ImDrawVtx_Pos(vtx, vi)) vtxs_rect:Add(tri[n + 1]) end - if show_mesh then fg_draw_list:AddPolyline(tri, 3, IM_COL32(255, 255, 0, 255), 1.0, ImDrawFlags.Closed) end + if show_mesh then fg_draw_list:AddPolyline(tri, 3, IM_COL32(255, 255, 0, 255), 1.0, ImDrawFlags.Closed) end -- In yellow: mesh triangles end if show_aabb then - fg_draw_list:AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)) - fg_draw_list:AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)) + fg_draw_list:AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)) -- In pink: clipping rectangle submitted to GPU + fg_draw_list:AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)) -- In cyan: bounding box of triangles end end if ImGui.IsItemHovered() and (cfg.ShowDrawCmdMesh or cfg.ShowDrawCmdBoundingBoxes) then ShowMesh(cfg.ShowDrawCmdMesh, cfg.ShowDrawCmdBoundingBoxes) end @@ -17848,7 +20608,9 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) ImGui.TreePop() end +-- [DEBUG] Display contents of ImGuiTabBar function ImGui.DebugNodeTabBar(tab_bar, label) + -- Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. local g = ImGui.GetCurrentContext() local is_active = (tab_bar.PrevFrameVisible >= ImGui.GetFrameCount() - 2) local names = {} @@ -17907,7 +20669,7 @@ end function ImGui.DebugNodeTable(tbl) local g = ImGui.GetCurrentContext() - local is_active = (tbl.LastFrameActive >= g.FrameCount - 2) + local is_active = (tbl.LastFrameActive >= g.FrameCount - 2) -- Note that fully clipped early out scrolling tables will appear as inactive here. if not is_active then ImGui.PushStyleColor(ImGuiCol.Text, g.Style.Colors[ImGuiCol.TextDisabled]) end local open = ImGui.TreeNode(tostring(tbl), "Table 0x%08X (%d columns, in '%s')%s", tbl.ID, tbl.ColumnsCount, tbl.OuterWindow and tbl.OuterWindow.Name or "?", is_active and "" or " *Inactive*") if not is_active then ImGui.PopStyleColor() end @@ -17948,7 +20710,7 @@ function ImGui.DebugNodeTable(tbl) end local settings = ImGui.TableGetBoundSettings(tbl) if settings then ImGui.DebugNodeTableSettings(settings, tbl) end - if clear_settings then tbl.IsResetAllRequest = true end + if clear_settings then tbl.IsResetAllRequest = true end -- Queue a call to TableResetSettings() ImGui.TreePop() end @@ -17968,10 +20730,11 @@ local function DebugNodeDockNodeFlags(flags, label, enabled) return flags end +-- [DEBUG] Display contents of ImDockNode function ImGui.DebugNodeDockNode(node, label) local g = ImGui.GetCurrentContext() - local is_alive = (g.FrameCount - node.LastFrameAlive < 2) - local is_active = (g.FrameCount - node.LastFrameActive < 2) + local is_alive = (g.FrameCount - node.LastFrameAlive < 2) -- Submitted with ImGuiDockNodeFlags.KeepAliveOnly + local is_active = (g.FrameCount - node.LastFrameActive < 2) -- Submitted if not is_alive then ImGui.PushStyleColor(ImGuiCol.Text, g.Style.Colors[ImGuiCol.TextDisabled]) end local tree_node_flags = node.IsFocused and ImGuiTreeNodeFlags.Selected or ImGuiTreeNodeFlags.None local open @@ -18078,7 +20841,7 @@ end function ImGui.DebugNodeWindowsList(windows, label) if not ImGui.TreeNode(label, "%s (%d)", label, windows.Size) then return end - for i = windows.Size, 1, -1 do + for i = windows.Size, 1, -1 do -- Iterate front to back ImGui.PushID(tostring(windows.Data[i])) ImGui.DebugNodeWindow(windows.Data[i], "Window") ImGui.PopID() @@ -18086,11 +20849,13 @@ function ImGui.DebugNodeWindowsList(windows, label) ImGui.TreePop() end +-- FIXME-OPT: This is technically suboptimal, but it is simpler this way. function ImGui.DebugNodeWindowsListByBeginStackParent(windows, first, last, parent_in_begin_stack) for i = first, last do local window = windows[i] if window.ParentWindowInBeginStack == parent_in_begin_stack then local buf = string.format("[%04d] Window", window.BeginOrderWithinContext) + -- ImGui.BulletText("[%04d] Window '%s'", window.BeginOrderWithinContext, window.Name) ImGui.DebugNodeWindow(window, buf) ImGui.TreePush(buf) ImGui.DebugNodeWindowsListByBeginStackParent(windows, i + 1, last, window) @@ -18116,6 +20881,7 @@ function ImGui.DebugNodeViewport(viewport) end end +-- Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct. function ImGui.DebugTextEncoding(str) ImGui.Text("Text: \"%s\"", str) if not ImGui.BeginTable("##DebugTextEncoding", 4, bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg, ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.Resizable)) then return end @@ -18141,6 +20907,7 @@ function ImGui.DebugTextEncoding(str) ImGui.EndTable() end +-- Debugging enums local WRT_Names = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" } local TRT_Names = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" } @@ -18158,14 +20925,14 @@ local function GetWindowRect(window, t) end local function GetTableRect(tbl, t, n) - local inst = ImGui.TableGetInstanceData(tbl, tbl.InstanceCurrent) + local inst = ImGui.TableGetInstanceData(tbl, tbl.InstanceCurrent) -- Always using last submitted instance if t == 0 then return tbl.OuterRect elseif t == 1 then return tbl.InnerRect elseif t == 2 then return tbl.WorkRect elseif t == 3 then return tbl.HostClipRect elseif t == 4 then return tbl.InnerClipRect elseif t == 5 then return tbl.BgClipRect end local c = tbl.Columns[n] if t == 6 then return ImRect(c.MinX, tbl.InnerClipRect.Min.y, c.MaxX, tbl.InnerClipRect.Min.y + inst.LastOuterHeight) elseif t == 7 then return ImRect(c.WorkMinX, tbl.WorkRect.Min.y, c.WorkMaxX, tbl.WorkRect.Max.y) elseif t == 8 then return c.ClipRect - elseif t == 9 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXHeadersUsed, tbl.InnerClipRect.Min.y + inst.LastTopHeadersRowHeight) + elseif t == 9 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXHeadersUsed, tbl.InnerClipRect.Min.y + inst.LastTopHeadersRowHeight) -- Note: y1/y2 not always accurate elseif t == 10 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXHeadersIdeal, tbl.InnerClipRect.Min.y + inst.LastTopHeadersRowHeight) elseif t == 11 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXFrozen, tbl.InnerClipRect.Min.y + inst.LastFrozenHeight) else return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y + inst.LastFrozenHeight, c.ContentMaxXUnfrozen, tbl.InnerClipRect.Max.y) end @@ -18194,6 +20961,7 @@ function ImGui.ShowMetricsWindow(p_open) return p_open end + -- Basic info ImGui.Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM) ImGui.Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0 / math.max(io.Framerate, 0.0001), io.Framerate) ImGui.Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, math.floor(io.MetricsRenderIndices / 3)) @@ -18231,7 +20999,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.SetNextItemWidth(ImGui.GetFontSize() * 12) cfg.ShowTablesRectsType, changed = ImGui.Combo("##show_table_rects_type", cfg.ShowTablesRectsType, TRT_Names, #TRT_Names, #TRT_Names) cfg.ShowTablesRects = cfg.ShowTablesRects or changed - _, g.DebugShowGroupRects = ImGui.Checkbox("Show groups rectangles", g.DebugShowGroupRects == true) + _, g.DebugShowGroupRects = ImGui.Checkbox("Show groups rectangles", g.DebugShowGroupRects == true) -- Storing in context as this is used by group code and prefers to be in hot-data ImGui.SeparatorText("Validate") _, io.ConfigDebugBeginReturnValueLoop = ImGui.Checkbox("Debug Begin/BeginChild return value", io.ConfigDebugBeginReturnValueLoop == true) @@ -18250,9 +21018,11 @@ function ImGui.ShowMetricsWindow(p_open) -- Windows if ImGui.TreeNode("Windows", "Windows (%d)", g.Windows.Size) then + -- ImGui.SetNextItemOpen(true, ImGuiCond.Once) ImGui.DebugNodeWindowsList(g.Windows, "By display order") ImGui.DebugNodeWindowsList(g.WindowsFocusOrder, "By focus order (root windows)") if ImGui.TreeNode("By submission order (begin stack)") then + -- Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship! local tmp = {} for _, window in g.Windows:iter() do if window.LastFrameActive + 1 >= g.FrameCount then tmp[#tmp + 1] = window end @@ -18293,7 +21063,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- Fonts + -- Details for Fonts for i, atlas in g.FontAtlases:iter() do if ImGui.TreeNode(tostring(atlas), "Fonts (%d), Textures (%d)", atlas.Fonts.Size, atlas.TexList.Size) then ImGui.ShowFontAtlas(atlas) @@ -18301,9 +21071,10 @@ function ImGui.ShowMetricsWindow(p_open) end end - -- Popups + -- Details for Popups if ImGui.TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size) then for _, popup_data in g.OpenPopupStack:iter() do + -- As it's difficult to interact with tree nodes while popups are open, we display everything inline. local window = popup_data.Window local W = ImGuiWindowFlags ImGui.BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'", popup_data.PopupId, window and window.Name or "NULL", @@ -18313,7 +21084,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- TabBars + -- Details for TabBars if ImGui.TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.AliveCount) then for n = 0, g.TabBars:GetMapSize() - 1 do local tab_bar = g.TabBars:GetByIndex(n) @@ -18326,13 +21097,13 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- Tables + -- Details for Tables if ImGui.TreeNode("Tables", "Tables (%d)", g.Tables.AliveCount) then ForEachTable(g, ImGui.DebugNodeTable) ImGui.TreePop() end - -- Docking + -- Details for Docking if ImGui.TreeNode("Docking") then local dc = g.DockContext _, MetricsDockRootOnly = ImGui.Checkbox("List root nodes", MetricsDockRootOnly) @@ -18398,6 +21169,7 @@ function ImGui.ShowMetricsWindow(p_open) -- Inputs if ImGui.TreeNode("Inputs") then ImGui.Text("KEYBOARD/GAMEPAD/MOUSE KEYS") + -- User code should never have to go through such hoops! You can generally iterate between ImGuiKey.NamedKey_BEGIN and ImGuiKey.NamedKey_END. ImGui.Indent() ImGui.Text("Keys down:") for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do @@ -18450,7 +21222,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.Indent() ImGui.Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, B(g.ActiveIdAllowOverlap)) ImGui.Text("ActiveIdWindow: '%s'", N(g.ActiveIdWindow)) - ImGui.Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, B(g.HoveredIdAllowOverlap)) + ImGui.Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, B(g.HoveredIdAllowOverlap)) -- Not displaying g.HoveredId as it is update mid-frame ImGui.Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId or 0, g.HoverItemDelayTimer or 0, g.HoverItemDelayClearTimer or 0) ImGui.Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\"", B(g.DragDropActive), g.DragDropPayload.SourceId or 0, tostring(g.DragDropPayload.DataType or "")) ImGui.Unindent() @@ -18468,7 +21240,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- Overlays + -- Overlay: Display windows Rectangles and Begin Order if cfg.ShowWindowsRects or cfg.ShowWindowsBeginOrder then for _, window in g.Windows:iter() do if window.WasActive then @@ -18485,6 +21257,8 @@ function ImGui.ShowMetricsWindow(p_open) end end end + + -- Overlay: Display Tables Rectangles if cfg.ShowTablesRects then ForEachTable(g, function(tbl) if tbl.LastFrameActive < g.FrameCount - 1 then return end @@ -18514,20 +21288,127 @@ __FILES['imgui_demo.lua'] = function() -- dear imgui demo (Luau port of imgui_demo.cpp). Optional: the library never calls into this file. do --[[ imgui_demo.lua ]] ---- Dear ImGui WIP --- (Demo Code) Port of imgui_demo.cpp (docking branch) +-- dear imgui, v1.93.0 WIP +-- (demo code) Port of imgui_demo.cpp (docking branch) -- This file: shared demo helpers, ShowDemoWindow(), DemoWindowMenuBar(), DemoWindowWidgets() dispatcher, example tree/image viewer helpers. -- Other parts (all global functions, loaded from the same bundle): +-- Help: +-- - Read FAQ at http://dearimgui.com/faq +-- - Call and read ImGui.ShowDemoWindow() in imgui_demo.lua. +-- - Need help integrating Dear ImGui in your codebase? +-- - Read Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started +-- Read top of imgui.cpp and imgui.h for many details, documentation, comments, links. +-- Get the latest version at https://github.com/ocornut/imgui + +-- How to easily locate code? +-- - Use Tools->Item Picker to debug break in code by clicking any widgets: https://github.com/ocornut/imgui/wiki/Debug-Tools +-- - Browse pthom's online imgui_explorer: web version the demo w/ source code browser: https://pthom.github.io/imgui_explorer +-- - Find a visible string and search for it in the code! + +----------------------------------------------------- +-- PLEASE DO NOT REMOVE THIS FILE FROM YOUR PROJECT! +----------------------------------------------------- +-- Message to the person tempted to delete this file when integrating Dear ImGui into their codebase: +-- Think again! It is the most useful reference code that you and other coders will want to refer to and call. +-- Have the ImGui.ShowDemoWindow() function wired in an always-available debug menu of your game/app! +-- Also include Metrics! ItemPicker! DebugLog! and other debug features. +-- Removing this file from your project is hindering access to documentation for everyone in your team, +-- likely leading you to poorer usage of the library. +-- Whenever you have Dear ImGui available you probably want this to be available for reference. +-- Thank you, +-- -Your beloved friend, imgui_demo.cpp (which you won't delete) + +---------------------------------------------- +-- ABOUT THE MEANING OF THE 'static' KEYWORD: +---------------------------------------------- +-- In the upstream C++ demo code, 'static' variables inside functions are frequently used. +-- A static variable persists across calls. It is essentially a global variable but declared inside the scope of the function. +-- Think of "static int n = 0;" as "global int n = 0;" ! +-- (PORT: Lua has no function-local statics; this port keeps them as fields of file-level tables, e.g. `S`, `SL`, `ST`.) +-- We do this IN THE DEMO because we want: +-- - to gather code and data in the same place. +-- - to make the demo source code faster to read, faster to change, smaller in size. +-- - it is also a convenient way of storing simple UI related information as long as your function +-- doesn't need to be reentrant or used in multiple threads. +-- This might be a pattern you will want to use in your code, but most of the data you would be working +-- with in a complex codebase is likely going to be stored outside your functions. + +------------------------------------------- +-- ABOUT THE CODING STYLE OF OUR DEMO CODE +------------------------------------------- +-- The Demo code in this file is designed to be easy to copy-and-paste into your application! +-- Because of this: +-- - We never omit the ImGui. prefix when calling functions. + +-- Navigating this file: +-- - You can search/grep for all sections listed in the index to find the section. + +-- Index of this file: +-- +-- [SECTION] Helpers +-- [SECTION] Demo Window / ShowDemoWindow() +-- [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) +-- [SECTION] Helpers: ExampleImageViewer +-- [SECTION] DemoWindowWidgetsBasic() +-- [SECTION] DemoWindowWidgetsBullets() +-- [SECTION] DemoWindowWidgetsCollapsingHeaders() +-- [SECTION] DemoWindowWidgetsComboBoxes() +-- [SECTION] DemoWindowWidgetsColorAndPickers() +-- [SECTION] DemoWindowWidgetsDataTypes() +-- [SECTION] DemoWindowWidgetsDisableBlocks() +-- [SECTION] DemoWindowWidgetsDragAndDrop() +-- [SECTION] DemoWindowWidgetsDragsAndSliders() +-- [SECTION] DemoWindowWidgetsFonts() +-- [SECTION] DemoWindowWidgetsImages() +-- [SECTION] DemoWindowWidgetsListBoxes() +-- [SECTION] DemoWindowWidgetsLiveEdit() +-- [SECTION] DemoWindowWidgetsMixedValues() +-- [SECTION] DemoWindowWidgetsMultiComponents() +-- [SECTION] DemoWindowWidgetsPlotting() +-- [SECTION] DemoWindowWidgetsProgressBars() +-- [SECTION] DemoWindowWidgetsQueryingStatuses() +-- [SECTION] DemoWindowWidgetsSelectables() +-- [SECTION] DemoWindowWidgetsTabs() +-- [SECTION] DemoWindowWidgetsText() +-- [SECTION] DemoWindowWidgetsTextFilter() +-- [SECTION] DemoWindowWidgetsTextInput() +-- [SECTION] DemoWindowWidgetsTooltips() +-- [SECTION] DemoWindowWidgetsTreeNodes() +-- [SECTION] DemoWindowWidgetsVerticalSliders() +-- [SECTION] DemoWindowWidgets() +-- [SECTION] DemoWindowLayout() +-- [SECTION] DemoWindowPopups() +-- [SECTION] DemoWindowTables() +-- [SECTION] About Window / ShowAboutWindow() +-- [SECTION] Style Editor / ShowStyleEditor() +-- [SECTION] User Guide / ShowUserGuide() +-- [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() +-- [SECTION] Example App: Debug Console / ShowExampleAppConsole() +-- [SECTION] Example App: Debug Log / ShowExampleAppLog() +-- [SECTION] Example App: Simple Layout / ShowExampleAppLayout() +-- [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() +-- [SECTION] Example App: Long Text / ShowExampleAppLongText() +-- [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() +-- [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize() +-- [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() +-- [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() +-- [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles() +-- [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() +-- [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() +-- [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() + local _ ----------------------------------------------------------------- --- Shared helpers (globals) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Helpers +------------------------------------------------------------------------------- +-- Helper to wire demo markers located in code to an interactive browser (e.g. https://pthom.github.io/imgui_explorer) function IMGUI_DEMO_MARKER(_) end -- upstream hook, no-op here ---- Helper to display a little (?) mark which shows a tooltip when hovered. +-- Helper to display a little (?) mark which shows a tooltip when hovered. +-- In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md) function HelpMarker(desc) ImGui.TextDisabled("(?)") if ImGui.BeginItemTooltip() then @@ -18675,9 +21556,9 @@ function DemoTextFilter() return f end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Demo Window data ----------------------------------------------------------------- +------------------------------------------------------------------------------- --- Data to be shared across different functions of the demo. function ImGuiDemoWindowData() @@ -18715,10 +21596,12 @@ function ImGuiDemoWindowData() } end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Simple representation for a tree +-- (this is designed to be simple to understand for our demos, not to be fancy or efficient etc.) function ExampleTreeNode() return { -- Tree structure @@ -18726,7 +21609,7 @@ function ExampleTreeNode() UID = 0, Parent = nil, Childs = {}, -- 1-based - IndexInParent = 0, -- 0-based + IndexInParent = 0, -- 0-based. Maintaining this allows us to implement linear traversal more easily -- Leaf Data HasData = false, -- All leaves have data @@ -18750,8 +21633,14 @@ end function ExampleTree_DestroyNode(node) end -- GC ---- Create example tree data +-- Create example tree data +-- (warning: this can allocates MANY MANY more times than other code in all of Dear ImGui + demo combined) +-- (a real application managing one million nodes would likely store its tree data differently) function ExampleTree_CreateDemoTree() + -- 20 root nodes -> 211 total nodes, ~261 allocs. + -- 1000 root nodes -> ~11K total nodes, ~14K allocs. + -- 10000 root nodes -> ~123K total nodes, ~154K allocs. + -- 100000 root nodes -> ~1338K total nodes, ~1666K allocs. local ROOT_ITEMS_COUNT = 20 local category_names = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pear", "Pineapple", "Strawberry", "Watermelon" } local category_count = #category_names @@ -18777,9 +21666,9 @@ function ExampleTree_CreateDemoTree() return node_L0 end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Helpers: ExampleImageViewer ----------------------------------------------------------------- +------------------------------------------------------------------------------- function ExampleImageViewerData() return { @@ -18795,7 +21684,7 @@ function ExampleImageViewerData() end function ExampleImageViewer_DrawOptions(data) - ImGui.SetNextItemShortcut(ImGuiKey.G, ImGuiInputFlags.Tooltip) + ImGui.SetNextItemShortcut(ImGuiKey.G, ImGuiInputFlags.Tooltip) -- | ImGuiInputFlags.RouteGlobal _, data.GridEnabled = ImGui.Checkbox("Grid", data.GridEnabled) ImGui.SameLine() ImGui.SetNextItemWidth(ImGui.GetFontSize() * 10.0) @@ -18829,7 +21718,7 @@ function ExampleImageViewer_DrawCanvas(data, canvas_size, image_tex_ref, image_w data.Zoom = DemoClamp(data.Zoom * (1.0 + io.MouseWheel * 0.10), data.ZoomMin, data.ZoomMax) end end - local zoom = data.Zoom + local zoom = data.Zoom -- (float)(int)ViewZoom; if ImGui.IsItemActive() and ImGui.IsMouseDragging(0) then data.ViewOffset.x = data.ViewOffset.x - io.MouseDelta.x / zoom data.ViewOffset.y = data.ViewOffset.y - io.MouseDelta.y / zoom @@ -18865,10 +21754,11 @@ function ExampleImageViewer_DrawCanvas(data, canvas_size, image_tex_ref, image_w draw_list:PopClipRect() end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Demo Window / ShowDemoWindow() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Stored data local demo_data = ImGuiDemoWindowData() local no_titlebar = false @@ -18926,6 +21816,7 @@ local function DemoWindowMenuBar(data) ImGui.EndMenu() end + -- if ImGui.MenuItem("MenuItem") then end -- You can also use MenuItem() inside a menu bar! if ImGui.BeginMenu("Tools") then IMGUI_DEMO_MARKER("Menu/Tools") local io = ImGui.GetIO() @@ -18942,7 +21833,7 @@ local function DemoWindowMenuBar(data) _, data.ShowDebugLog = ImGui.MenuItem("Debug Log", nil, data.ShowDebugLog, has_debug_tools and ImGui.ShowDebugLogWindow ~= nil) _, data.ShowIDStackTool = ImGui.MenuItem("ID Stack Tool", nil, data.ShowIDStackTool, has_debug_tools and ImGui.ShowIDStackToolWindow ~= nil) local is_debugger_present = io.ConfigDebugIsDebuggerPresent - if ImGui.MenuItem("Item Picker", nil, false, has_debug_tools and ImGui.DebugStartItemPicker ~= nil) then + if ImGui.MenuItem("Item Picker", nil, false, has_debug_tools and ImGui.DebugStartItemPicker ~= nil) then -- and is_debugger_present ImGui.DebugStartItemPicker() end if not is_debugger_present then @@ -19050,6 +21941,12 @@ local function DemoWindowConfiguration(io) ImGui.Unindent() end + -- ImGui.SeparatorText("DPI/Scaling") + -- CB("io.ConfigDpiScaleFonts", "ConfigDpiScaleFonts") + -- HM("Experimental: Automatically update style.FontScaleDpi when Monitor DPI changes. This will scale fonts but NOT style sizes/padding for now.") + -- CB("io.ConfigDpiScaleViewports", "ConfigDpiScaleViewports") + -- HM("Experimental: Scale Dear ImGui and Platform Windows when Monitor DPI changes.") + ImGui.SeparatorText("Windows") CB("io.ConfigWindowsResizeFromEdges", "ConfigWindowsResizeFromEdges") HM("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback.") @@ -19123,6 +22020,7 @@ local function DemoWindowConfiguration(io) "Here we expose them as read-only fields to avoid breaking interactions with your backend.") -- Make a local copy to avoid modifying actual backend flags. + -- FIXME: Maybe we need a BeginReadonly() equivalent to keep label bright? local B = ImGuiBackendFlags local backend_flags = io.BackendFlags ImGui.BeginDisabled() @@ -19176,10 +22074,14 @@ local function DemoWindowConfiguration(io) end end ---- Demonstrate most Dear ImGui features (this is big function!) +-- Demonstrate most Dear ImGui features (this is big function!) +-- You may execute this function to experiment with the UI and understand what it does. +-- You may then search for keywords in the code when you are interested by a specific feature. --- @param p_open? bool --- @return bool? p_open function ImGui.ShowDemoWindow(p_open) + -- Exceptionally add an extra assert here for people confused about initial Dear ImGui setup + -- Most functions would normally just assert/crash if the context is missing. IM_ASSERT(ImGui.GetCurrentContext() ~= nil, "Missing Dear ImGui context. Refer to examples app!") local data = demo_data @@ -19235,6 +22137,7 @@ function ImGui.ShowDemoWindow(p_open) if no_close then p_open = nil end -- Don't pass our bool* to Begin -- We specify a default position/size in case there's no data in the .ini file. + -- We only do it to make the demo applications a little more welcoming, but typically this isn't required. local main_viewport = ImGui.GetMainViewport() ImGui.SetNextWindowPos(ImVec2(main_viewport.WorkPos.x + 650, main_viewport.WorkPos.y + 20), ImGuiCond.FirstUseEver) ImGui.SetNextWindowSize(ImVec2(550, 680), ImGuiCond.FirstUseEver) @@ -19250,10 +22153,18 @@ function ImGui.ShowDemoWindow(p_open) end -- Most framed widgets share a common width settings. Remaining width is used for the label. + -- The width of the frame may be changed with PushItemWidth() or SetNextItemWidth(). + -- - Positive value for absolute size, negative value for right-alignment. + -- - The default value is about GetWindowWidth() * 0.65f. + -- - See 'Demo->Layout->Widgets Width' for details. + -- Here we change the frame width based on how much width we want to give to the label. local label_width_base = ImGui.GetFontSize() * 12 -- Some amount of width for label, based on font size. local label_width_max = ImGui.GetContentRegionAvail().x * 0.40 -- ...but always leave some room for framed widgets. local label_width = math.min(label_width_base, label_width_max) ImGui.PushItemWidth(-label_width) -- Right-align: framed items will leave 'label_width' available for the label. + -- ImGui.PushItemWidth(ImGui.GetContentRegionAvail().x * 0.40) -- e.g. Use 40% width for framed widgets, leaving 60% width for labels. + -- ImGui.PushItemWidth(-ImGui.GetContentRegionAvail().x * 0.40) -- e.g. Use 40% width for labels, leaving 60% width for framed widgets. + -- ImGui.PushItemWidth(ImGui.GetFontSize() * -12) -- e.g. Use XXX width for labels, leaving the rest for framed widgets. -- Menu Bar DemoWindowMenuBar(data) @@ -19322,9 +22233,9 @@ function ImGui.ShowDemoWindow(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] DemoWindowWidgets() ----------------------------------------------------------------- +------------------------------------------------------------------------------- --- Calls a (global) demo section if it exists, otherwise shows a placeholder local function Sub(fn, title, ...) @@ -19334,6 +22245,7 @@ local function Sub(fn, title, ...) end function DemoWindowWidgets(data) + -- ImGui.SetNextItemOpen(true, ImGuiCond.Once) if not ImGui.CollapsingHeader("Widgets") then return end @@ -19394,9 +22306,9 @@ function DemoWindowWidgets(data) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] User Guide / ShowUserGuide() ----------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.ShowUserGuide() local io = ImGui.GetIO() @@ -19445,6 +22357,10 @@ do --[[ imgui_demo_2.lua ]] -- DemoWindowInputs() and all ShowExampleAppXXX() example apps. -- Port of imgui_demo.cpp (docking branch). Globals are shared with imgui_demo.lua (HelpMarker, ShowExampleMenuFile, ...) +-- Helpers macros +-- We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste, +-- but making an exception here as those are largely simplifying code... +-- In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo. local IM_MIN = math.min local IM_MAX = math.max local function IM_CLAMP(V, MN, MX) return (V < MN) and MN or (V > MX) and MX or V end @@ -19633,6 +22549,10 @@ local function DemoWindowLayout_ChildWindows() ImGui.SeparatorText("Manual-resize") do DemoHelpMarker("Drag bottom border to resize. Double-click bottom border to auto-fit to vertical contents.") + -- if ImGui.Button("Set Height to 200") then + -- ImGui.SetNextWindowSize(ImVec2(-FLT_MIN, 200.0)) + -- end + ImGui.PushStyleColor(ImGuiCol.ChildBg, ImGui.GetStyleColorVec4(ImGuiCol.FrameBg)) if BeginChild("ResizableChild", ImVec2(-FLT_MIN, ImGui.GetTextLineHeightWithSpacing() * 8), bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.ResizeY)) then for n = 0, 9 do @@ -19662,6 +22582,13 @@ local function DemoWindowLayout_ChildWindows() ImGui.SeparatorText("Misc/Advanced") + -- Demonstrate a few extra things + -- - Changing ImGuiCol.ChildBg (which is transparent black in default styles) + -- - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window) + -- You can also call SetNextWindowPos() to position the child window. The parent window will effectively + -- layout from this position. + -- - Using ImGui.GetItemRectMin/Max() to query the "item" state (because the child window is an item from + -- the POV of the parent window). See 'Demo->Querying Status (Edited/Active/Hovered etc.)' for details. do if SL.child_flags == nil then SL.child_flags = bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY) end ImGui.SetNextItemWidth(ImGui.GetFontSize() * 8) @@ -19702,6 +22629,11 @@ local function DemoWindowLayout_WidgetsWidth() IMGUI_DEMO_MARKER("Layout/Widgets Width") _, SL.show_indented_items = ImGui.Checkbox("Show indented items", SL.show_indented_items) + -- Use SetNextItemWidth() to set the width of a single upcoming item. + -- Use PushItemWidth()/PopItemWidth() to set the width of a group of items. + -- In real code use you'll probably want to choose width values that are proportional to your font size + -- e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc. + local function block(text, help, width, l1, l2) ImGui.Text(text) if help then ImGui.SameLine(); DemoHelpMarker(help) end @@ -19720,6 +22652,7 @@ local function DemoWindowLayout_WidgetsWidth() block("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)", "Align to right edge minus half", -ImGui.GetContentRegionAvail().x * 0.5, "float##4a", "float (indented)##4b") block("SetNextItemWidth/PushItemWidth(-Min(GetContentRegionAvail().x * 0.40f, GetFontSize() * 12))", nil, -IM_MIN(ImGui.GetFontSize() * 12, ImGui.GetContentRegionAvail().x * 0.40), "float##5a", "float (indented)##5b") -- Demonstrate using PushItemWidth to surround three items. + -- Calling SetNextItemWidth() before each of them would have the same effect. block("SetNextItemWidth/PushItemWidth(-FLT_MIN)", "Align to right edge", -FLT_MIN, "##float6a", "float (indented)##6b") end @@ -19787,6 +22720,7 @@ local function DemoWindowLayout_BasicHorizontal() NotPorted("ListBox") end ImGui.PopID() + -- ImGui.SetItemTooltip("ListBox %d hovered", i) end ImGui.PopItemWidth() @@ -19798,6 +22732,7 @@ local function DemoWindowLayout_BasicHorizontal() ImGui.Button("B", button_sz) -- Manually wrapping + -- (we should eventually provide this as an automatic layout feature, but for now you can do it manually) IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Manual wrapping") ImGui.Text("Manual wrapping:") local style = ImGui.GetStyle() @@ -19871,6 +22806,9 @@ local function DemoWindowLayout_TextBaseline() ImGui.Button("Some framed item"); ImGui.SameLine() DemoHelpMarker("Baseline of button will look misaligned with text..") + -- If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. + -- (because we don't know what's coming after the Text() statement, we need to move the text baseline + -- down by FramePadding.y ahead of time) ImGui.AlignTextToFramePadding() ImGui.Text("OK Blahblah"); ImGui.SameLine() ImGui.Button("Some framed item##2"); ImGui.SameLine() @@ -19881,6 +22819,7 @@ local function DemoWindowLayout_TextBaseline() ImGui.Text("TEST"); ImGui.SameLine() ImGui.SmallButton("TEST##2") + -- If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. ImGui.AlignTextToFramePadding() ImGui.Text("Text aligned to framed item"); ImGui.SameLine() ImGui.Button("Item##1"); ImGui.SameLine() @@ -19921,6 +22860,7 @@ local function DemoWindowLayout_TextBaseline() ImGui.BulletText("Misc items:") ImGui.Indent() + -- SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. ImGui.Button("80x80", ImVec2(80, 80)) ImGui.SameLine() ImGui.Button("50x50", ImVec2(50, 50)) @@ -19930,10 +22870,12 @@ local function DemoWindowLayout_TextBaseline() ImGui.SmallButton("SmallButton()") -- Tree + -- (here the node appears after a button and has odd intent, so we use ImGuiTreeNodeFlags.DrawLinesNone to disable hierarchy outline) local spacing = ImGui.GetStyle().ItemInnerSpacing.x ImGui.Button("Button##1") -- Will make line higher ImGui.SameLine(0.0, spacing) if ImGui.TreeNodeEx("Node##1", ImGuiTreeNodeFlags.DrawLinesNone) then + -- Placeholder tree data for i = 0, 5 do ImGui.BulletText("Item %d..", i) end @@ -19949,11 +22891,16 @@ local function DemoWindowLayout_TextBaseline() ImGui.TreePop() end + -- Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. + -- Otherwise you can use SmallButton() (smaller fit). ImGui.AlignTextToFramePadding() + -- Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add + -- other contents "inside" the node. local node_open = ImGui.TreeNode("Node##3") ImGui.SameLine(0.0, spacing); ImGui.Button("Button##3") if node_open then + -- Placeholder tree data for i = 0, 5 do ImGui.BulletText("Item %d..", i) end @@ -19984,12 +22931,12 @@ local function DemoWindowLayout_HorizontalContentsSizeWindow() "Test how different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\n" .. "Use 'Metrics->Tools->Show windows rectangles' to visualize rectangles.") _, SL.show_h_scrollbar = ImGui.Checkbox("H-scrollbar", SL.show_h_scrollbar) - _, SL.show_button = ImGui.Checkbox("Button", SL.show_button) - _, SL.show_tree_nodes = ImGui.Checkbox("Tree nodes", SL.show_tree_nodes) - _, SL.show_text_wrapped = ImGui.Checkbox("Text wrapped", SL.show_text_wrapped) - _, SL.show_columns = ImGui.Checkbox("Columns", SL.show_columns) - _, SL.show_tab_bar = ImGui.Checkbox("Tab bar", SL.show_tab_bar) - _, SL.show_child = ImGui.Checkbox("Child", SL.show_child) + _, SL.show_button = ImGui.Checkbox("Button", SL.show_button) -- Will grow contents size (unless explicitly overwritten) + _, SL.show_tree_nodes = ImGui.Checkbox("Tree nodes", SL.show_tree_nodes) -- Will grow contents size and display highlight over full width + _, SL.show_text_wrapped = ImGui.Checkbox("Text wrapped", SL.show_text_wrapped) -- Will grow and use contents size + _, SL.show_columns = ImGui.Checkbox("Columns", SL.show_columns) -- Will use contents size + _, SL.show_tab_bar = ImGui.Checkbox("Tab bar", SL.show_tab_bar) -- Will use contents size + _, SL.show_child = ImGui.Checkbox("Child", SL.show_child) -- Will grow and use contents size _, SL.explicit_content_size = ImGui.Checkbox("Explicit content size", SL.explicit_content_size) ImGui.Text("Scroll %.1f/%.1f %.1f/%.1f", ImGui.GetScrollX(), ImGui.GetScrollMaxX(), ImGui.GetScrollY(), ImGui.GetScrollMaxY()) if SL.explicit_content_size then @@ -20057,6 +23004,7 @@ end local function DemoWindowLayout_Scrolling() IMGUI_DEMO_MARKER("Layout/Scrolling/Vertical") + -- Vertical scroll functions DemoHelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position.") _, SL.enable_extra_decorations = ImGui.Checkbox("Decoration", SL.enable_extra_decorations) @@ -20147,7 +23095,7 @@ local function DemoWindowLayout_Scrolling() if scroll_to_pos then ImGui.SetScrollFromPosX(ImGui.GetCursorStartPos().x + SL.scroll_to_pos_px, i * 0.25) end - if child_is_visible then + if child_is_visible then -- Avoid calling SetScrollHereY when running with culled items for item = 0, 99 do if item > 0 then ImGui.SameLine() @@ -20180,6 +23128,10 @@ local function DemoWindowLayout_Scrolling() local scrolling_child_size = ImVec2(0, ImGui.GetFrameHeightWithSpacing() * 7 + 30) BeginChild("scrolling", scrolling_child_size, ImGuiChildFlags.Borders, ImGuiWindowFlags.HorizontalScrollbar) for line = 0, SL.lines - 1 do + -- Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine() + -- If you want to create your own time line for a real application you may be better off manipulating + -- the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets + -- yourself. You may also want to use the lower-level ImDrawList API. local num_buttons = 10 + ((line % 2 == 1) and line * 9 or line * 3) local base_w = ImGui.GetFontSize() * 3 for n = 0, num_buttons - 1 do @@ -20214,6 +23166,7 @@ local function DemoWindowLayout_Scrolling() ImGui.Text("%.0f/%.0f", scroll_x, scroll_max_x) if scroll_x_delta ~= 0.0 then -- Demonstrate a trick: you can use Begin to set yourself in the context of another window + -- (here we are already out of your child window) BeginChild("scrolling") ImGui.SetScrollX(ImGui.GetScrollX() + scroll_x_delta) ImGui.EndChild() @@ -20278,7 +23231,7 @@ local function DemoWindowLayout_TextClipping() draw_list:AddText(text_pos, IM_COL32_WHITE, text_str) draw_list:PopClipRect() else - local clip_rect = ImVec4(p0.x, p0.y, p1.x, p1.y) + local clip_rect = ImVec4(p0.x, p0.y, p1.x, p1.y) -- AddText() takes a ImVec4 here so let's convert. draw_list:AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)) draw_list:AddText(ImGui.GetFont(), ImGui.GetFontSize(), text_pos, IM_COL32_WHITE, text_str, 1, #text_str + 1, 0.0, clip_rect) end @@ -20302,6 +23255,9 @@ local function DemoWindowLayout_OverlapMode() ImGui.SetCursorScreenPos(button2_pos) ImGui.Button("Button 2", ImVec2(80, 80)) + -- This is typically used with width-spanning items. + -- (note that Selectable() has a dedicated flag ImGuiSelectableFlags.AllowOverlap, which is a shortcut + -- for using SetNextItemAllowOverlap(). For demo purpose we use SetNextItemAllowOverlap() here.) if SL.enable_allow_overlap then ImGui.SetNextItemAllowOverlap() end @@ -20343,6 +23299,8 @@ local function DemoWindowPopups_Popups() local names = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" } local toggles = SP.toggles + -- Simple selection popup (if you want to show the current selection inside the Button itself, + -- you may want to build a string using the "###" operator to preserve a constant ID with a variable label) if ImGui.Button("Select..") then ImGui.OpenPopup("my_select_popup") end @@ -20424,7 +23382,20 @@ local function DemoWindowPopups_ContextMenus() IMGUI_DEMO_MARKER("Popups/Context menus") DemoHelpMarker("\"Context\" functions are simple helpers to associate a Popup to a given Item or Window identifier.") + -- BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing: + -- if id == 0 then + -- id = GetItemID() -- Use last item id + -- end + -- if IsItemHovered() and IsMouseReleased(ImGuiMouseButton.Right) then + -- OpenPopup(id) + -- end + -- return BeginPopup(id) + -- For advanced uses you may want to replicate and customize this code. + -- See more details in BeginPopupContextItem(). + -- Example 1 + -- When used after an item that has an ID (e.g. Button), we can skip providing an ID to BeginPopupContextItem(), + -- and BeginPopupContextItem() will use the last item ID as the popup ID. do local names = { "Label1", "Label2", "Label3", "Label4", "Label5" } for n = 0, 4 do @@ -20444,6 +23415,8 @@ local function DemoWindowPopups_ContextMenus() end -- Example 2 + -- Popup on a Text() element which doesn't have an identifier: we need to provide an identifier to BeginPopupContextItem(). + -- Using an explicit identifier is also convenient if you want to activate the popups from different locations. do DemoHelpMarker("Text() elements don't have stable identifiers so we need to provide one.") ImGui.Text("Value = %.3f <-- (1) right-click this text", SP.value) @@ -20455,15 +23428,22 @@ local function DemoWindowPopups_ContextMenus() ImGui.EndPopup() end + -- We can also use OpenPopupOnItemClick() to toggle the visibility of a given popup. + -- Here we make it that right-clicking this other text element opens the same popup as above. + -- The popup itself will be submitted by the code above. ImGui.Text("(2) Or right-click this text") ImGui.OpenPopupOnItemClick("my popup", ImGuiPopupFlags.MouseButtonRight) + -- Back to square one: manually open the same popup. if ImGui.Button("(3) Or click this button") then ImGui.OpenPopup("my popup") end end -- Example 3 + -- When using BeginPopupContextItem() with an implicit identifier (nil == use last item ID), + -- we need to make sure your item identifier is stable. + -- In this example we showcase altering the item label while preserving its identifier, using the ### operator (see FAQ). do DemoHelpMarker("Showcase using a popup ID linked to item ID, with the item having a changing label + stable ID using the ### operator.") if SP.name == nil then SP.name = Buf("Label1", 32) end @@ -20497,6 +23477,9 @@ local function DemoWindowPopups_Modals() ImGui.Text("All those beautiful files will be deleted.\nThis operation cannot be undone!") ImGui.Separator() + -- local unused_i = 0 + -- unused_i = ImGui.Combo("Combo", unused_i, "Delete\0Delete harder\0") + ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, ImVec2(0, 0)) _, SP.dont_ask_me_next_time = ImGui.Checkbox("Don't ask me next time", SP.dont_ask_me_next_time) ImGui.PopStyleVar() @@ -20533,6 +23516,9 @@ local function DemoWindowPopups_Modals() ImGui.OpenPopup("Stacked 2") end + -- Also demonstrate passing a p_open bool to BeginPopupModal(), this will create a regular close button which + -- will close the popup. Note that the visibility state of popups is owned by imgui, so the input value + -- of the bool actually doesn't matter here. local unused_open = true if ImGui.BeginPopupModal("Stacked 2", unused_open) then ImGui.Text("Hello from Stacked The Second!") @@ -20555,6 +23541,24 @@ function DemoWindowPopups() return end + -- The properties of popups windows are: + -- - They block normal mouse hovering detection outside them. (*) + -- - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + -- - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as + -- we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup(). + -- (*) One can use IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByPopup) to bypass it and detect hovering even + -- when normally blocked by a popup. + -- Those three properties are connected. The library needs to hold their visibility state BECAUSE it can close + -- popups at any time. + + -- Typical use for regular windows: + -- local my_tool_is_active = false; if ImGui.Button("Open") then my_tool_is_active = true end; [...] if my_tool_is_active then my_tool_is_active, visible = ImGui.Begin("My Tool", my_tool_is_active); [...] ImGui.End() end + -- Typical use for popups: + -- if ImGui.Button("Open") then ImGui.OpenPopup("MyPopup") end; if ImGui.BeginPopup("MyPopup") then [...] ImGui.EndPopup() end + + -- With popups we have to go through a library call (here OpenPopup) to manipulate the visibility state. + -- This may be a bit confusing at first but it should quickly make sense. Follow on the examples below. + if ImGui.TreeNode("Popups") then DemoWindowPopups_Popups(); ImGui.TreePop() end if ImGui.TreeNode("Context menus") then DemoWindowPopups_ContextMenus(); ImGui.TreePop() end if ImGui.TreeNode("Modals") then @@ -20581,6 +23585,11 @@ end -- [SECTION] DemoWindowTables() ------------------------------------------------------------------------------- +-- Dummy data structure that we use for the Table demo. +-- We are passing our own identifier to TableSetupColumn() to facilitate identifying columns in the sorting code. +-- This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID. +-- But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex) +-- If you don't use sorting, you will generally never care about giving column an ID! -- MyItemColumnID local MyItemColumnID_ID, MyItemColumnID_Name, MyItemColumnID_Action, MyItemColumnID_Quantity, MyItemColumnID_Description = 0, 1, 2, 3, 4 @@ -20596,6 +23605,8 @@ local function MyItem_SortWithSortSpecs(sort_specs, items, items_count) end local function cmp(a, b) -- returns <0, 0, >0 for n = 0, sort_specs.SpecsCount - 1 do + -- Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn() + -- We could also choose to identify columns based on their index (sort_spec.ColumnIndex), which is simpler! local sort_spec = get_spec(n) local delta = 0 local uid = sort_spec.ColumnUserID @@ -20611,6 +23622,10 @@ local function MyItem_SortWithSortSpecs(sort_specs, items, items_count) return (sort_spec.SortDirection == ImGuiSortDirection.Ascending) and -1 or 1 end end + + -- table.sort() is instable so always return a way to differentiate items. + -- Your own compare function may want to avoid fallback on implicit sort specs. + -- e.g. a Name compare if it wasn't already part of the sort specs. return a.ID - b.ID end local arr = items.Data or items @@ -20718,11 +23733,16 @@ local function bor(...) return bit32.bor(...) end local TF = setmetatable({}, { __index = function(_, k) return ImGuiTableFlags[k] end }) local ST = {} -- statics for DemoWindowTables (one sub-table per section) +-- Using those as a base value to create width/height that are factor of the size of our font local TEXT_BASE_WIDTH, TEXT_BASE_HEIGHT = 0, 0 local function Tables_Basic() IMGUI_DEMO_MARKER("Tables/Basic") + -- Here we will showcase three different ways to output a table. + -- They are very simple variations of a same thing! + -- [Method 1] Using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column. + -- In many situations, this is the most flexible and easy to use pattern. DemoHelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop.") if ImGui.BeginTable("table1", 3) then for row = 0, 3 do @@ -20736,6 +23756,7 @@ local function Tables_Basic() end -- [Method 2] Using TableNextColumn() called multiple times, instead of using a for loop + TableSetColumnIndex(). + -- This is generally more convenient when you have code manually submitting the contents of each column. DemoHelpMarker("Using TableNextRow() + calling TableNextColumn() _before_ each cell, manually.") if ImGui.BeginTable("table2", 3) then for row = 0, 3 do @@ -20751,6 +23772,8 @@ local function Tables_Basic() end -- [Method 3] We call TableNextColumn() _before_ each cell. We never call TableNextRow(), + -- as TableNextColumn() will automatically wrap around and create new rows as needed. + -- This is generally more convenient when your cells all contains the same type of data. DemoHelpMarker( "Only using TableNextColumn(), which tends to be convenient for tables where every cell contains " .. "the same type of contents.\n This is also more similar to the old NextColumn() function of the " .. @@ -20766,6 +23789,7 @@ end local function Tables_BordersBackground() IMGUI_DEMO_MARKER("Tables/Borders, background") + -- Expose a few Borders related flags interactively local CT_Text, CT_FillButton = 0, 1 local s = ST.borders if s == nil then s = { flags = bor(TF.Borders, TF.RowBg), display_headers = false, contents_type = CT_Text }; ST.borders = s end @@ -20800,6 +23824,8 @@ local function Tables_BordersBackground() PopStyleCompact() if ImGui.BeginTable("table1", 3, s.flags) then + -- Display headers so we can inspect their interaction with borders + -- (Headers are not the main purpose of this section of the demo, so we are not elaborating on them now. See other sections for details) if s.display_headers then ImGui.TableSetupColumn("One") ImGui.TableSetupColumn("Two") @@ -20838,6 +23864,8 @@ end local function Tables_ResizableStretch() IMGUI_DEMO_MARKER("Tables/Resizable, stretch") + -- By default, if we don't enable ScrollX the sizing policy for each column is "Stretch" + -- All columns maintain a sizing weight, and they will occupy all available width. local s = ST.rstretch if s == nil then s = { flags = bor(TF.SizingStretchSame, TF.Resizable, TF.BordersOuter, TF.BordersV, TF.ContextMenuInBody) }; ST.rstretch = s end PushStyleCompact() @@ -20853,6 +23881,10 @@ end local function Tables_ResizableFixed() IMGUI_DEMO_MARKER("Tables/Resizable, fixed") + -- Here we use ImGuiTableFlags.SizingFixedFit (even though _ScrollX is not set) + -- So columns will adopt the "Fixed" policy and will maintain a fixed width regardless of the whole available width (unless table is small) + -- If there is not enough available width to fit all columns, they will however be resized down. + -- FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings DemoHelpMarker( "Using _Resizable + _SizingFixedFit flags.\n" .. "Fixed-width columns generally makes more sense if you want to use horizontal scrolling.\n\n" .. @@ -20924,6 +23956,8 @@ local function Tables_Reorderable() PopStyleCompact() if ImGui.BeginTable("table1", 3, s.flags) then + -- Submit columns name with TableSetupColumn() and call TableHeadersRow() to create a row with a header in each column. + -- (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.) ImGui.TableSetupColumn("One") ImGui.TableSetupColumn("Two") ImGui.TableSetupColumn("Three") @@ -20939,6 +23973,7 @@ local function Tables_Reorderable() end -- Use outer_size.x == 0.0f instead of default to make the table as tight as possible + -- (only valid when no scrolling and no stretch column) if ImGui.BeginTable("table2", 3, bor(s.flags, TF.SizingFixedFit), ImVec2(0.0, 0.0)) then ImGui.TableSetupColumn("One") ImGui.TableSetupColumn("Two") @@ -20957,6 +23992,8 @@ end local function Tables_Padding() IMGUI_DEMO_MARKER("Tables/Padding") + -- First example: showcase use of padding flags and effect of BorderOuterV/BorderInnerV on X padding. + -- We don't expose BorderOuterH/BorderInnerH here because they have no effect on X padding. DemoHelpMarker( "We often want outer padding activated when any using features which makes the edges of a column visible:\n" .. "e.g.:\n" .. @@ -20970,7 +24007,7 @@ local function Tables_Padding() local s = ST.padding if s == nil then s = { flags1 = TF.BordersV, show_headers = false, flags2 = bor(TF.Borders, TF.RowBg), cell_padding = ImVec2(0.0, 0.0), - show_widget_frame_bg = true, text_bufs = {}, init = true } + show_widget_frame_bg = true, text_bufs = {}, init = true } -- text_bufs: Mini text storage for 3x5 cells ST.padding = s end PushStyleCompact() @@ -21003,12 +24040,16 @@ local function Tables_Padding() local buf = string.format("Hello %d,%d", column, row) ImGui.Button(buf, ImVec2(-FLT_MIN, 0.0)) end + -- if bit32.band(ImGui.TableGetColumnFlags(), ImGuiTableColumnFlags.IsHovered) ~= 0 then + -- ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, IM_COL32(0, 100, 0, 255)) + -- end end end ImGui.EndTable() end -- Second example: set style.CellPadding to (0.0) or a custom value. + -- FIXME-TABLE: Vertical border effectively not displayed the same way as horizontal one... DemoHelpMarker("Setting style.CellPadding to (0,0) or a custom value.") PushStyleCompact() @@ -21066,6 +24107,9 @@ local function Tables_SizingPolicies() ImGui.SetNextItemWidth(TEXT_BASE_WIDTH * 30) s.sizing_policy_flags[table_n + 1] = EditTableSizingFlags(s.sizing_policy_flags[table_n + 1]) + -- To make it easier to understand the different sizing policy, + -- For each policy: we display one table where the columns have equal contents width, + -- and one where the columns have different contents width. if ImGui.BeginTable("table1", 3, bor(s.sizing_policy_flags[table_n + 1], s.flags1)) then for row = 0, 2 do ImGui.TableNextRow() @@ -21156,6 +24200,8 @@ local function Tables_VerticalScrolling() _, s.flags = ImGui.CheckboxFlags("ImGuiTableFlags_ScrollY", s.flags, TF.ScrollY) PopStyleCompact() + -- When using ScrollX or ScrollY we need to specify a size for our table container! + -- Otherwise by default the table will fit all available space, like a BeginChild() call. local outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 8) if ImGui.BeginTable("table_scrolly", 3, s.flags, outer_size) then ImGui.TableSetupScrollFreeze(0, 1) -- Make top row always visible @@ -21206,6 +24252,8 @@ local function Tables_HorizontalScrolling() s.freeze_rows = ImGui.DragInt("freeze_rows", s.freeze_rows, 0.2, 0, 9, nil, ImGuiSliderFlags.NoInput) PopStyleCompact() + -- When using ScrollX or ScrollY we need to specify a size for our table container! + -- Otherwise by default the table will fit all available space, like a BeginChild() call. local outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 8) if ImGui.BeginTable("table_scrollx", 7, s.flags, outer_size) then ImGui.TableSetupScrollFreeze(s.freeze_cols, s.freeze_rows) @@ -21220,6 +24268,12 @@ local function Tables_HorizontalScrolling() for row = 0, 19 do ImGui.TableNextRow() for column = 0, 6 do repeat + -- Both TableNextColumn() and TableSetColumnIndex() return true when a column is visible or performing width measurement. + -- Because here we know that: + -- - A) all our columns are contributing the same to row height + -- - B) column 0 is always visible, + -- We only always submit this one column and can skip others. + -- More advanced per-column clipping behaviors may benefit from polling the status flags via TableGetColumnFlags(). if not ImGui.TableSetColumnIndex(column) and column > 0 then break -- continue end @@ -21260,11 +24314,12 @@ end local function Tables_ColumnsFlags() IMGUI_DEMO_MARKER("Tables/Columns flags") + -- Create a first table just to show all the options/flags we want to make visible in our example! local column_count = 3 local column_names = { "One", "Two", "Three" } local s = ST.colflags if s == nil then - s = { column_flags = { ImGuiTableColumnFlags.DefaultSort, ImGuiTableColumnFlags.None, ImGuiTableColumnFlags.DefaultHide }, column_flags_out = { 0, 0, 0 } } + s = { column_flags = { ImGuiTableColumnFlags.DefaultSort, ImGuiTableColumnFlags.None, ImGuiTableColumnFlags.DefaultHide }, column_flags_out = { 0, 0, 0 } } -- column_flags_out: Output from TableGetColumnFlags() ST.colflags = s end @@ -21289,6 +24344,10 @@ local function Tables_ColumnsFlags() ImGui.EndTable() end + -- Create the real table we care about for the example! + -- We use a scrolling table to be able to showcase the difference between the _IsEnabled and _IsVisible flags above, + -- otherwise in a non-scrolling table columns are always visible (unless using ImGuiTableFlags_NoKeepColumnsVisible + -- + resizing the parent window down). local flags = bor(TF.SizingFixedFit, TF.ScrollX, TF.ScrollY, TF.RowBg, TF.BordersOuter, TF.BordersV, TF.Resizable, TF.Reorderable, TF.Hideable, TF.Sortable) local outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 9) if ImGui.BeginTable("table_columns_flags", column_count, flags, outer_size) then @@ -21332,6 +24391,7 @@ local function Tables_ColumnsWidths() _, s.flags1 = ImGui.CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", s.flags1, TF.NoBordersInBodyUntilResize) PopStyleCompact() if ImGui.BeginTable("table1", 3, s.flags1) then + -- We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. ImGui.TableSetupColumn("one", CF.WidthFixed, 100.0) -- Default to 100.0f ImGui.TableSetupColumn("two", CF.WidthFixed, 200.0) -- Default to 200.0f ImGui.TableSetupColumn("three", CF.WidthFixed) -- Default to auto @@ -21360,6 +24420,8 @@ local function Tables_ColumnsWidths() _, s.flags2 = ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuterV", s.flags2, TF.BordersOuterV) PopStyleCompact() if ImGui.BeginTable("table2", 4, s.flags2) then + -- We could also set ImGuiTableFlags_SizingFixedFit on the table and then all columns + -- will default to ImGuiTableColumnFlags_WidthFixed. ImGui.TableSetupColumn("", CF.WidthFixed, 100.0) ImGui.TableSetupColumn("", CF.WidthFixed, TEXT_BASE_WIDTH * 15.0) ImGui.TableSetupColumn("", CF.WidthFixed, TEXT_BASE_WIDTH * 30.0) @@ -21477,6 +24539,8 @@ end local function Tables_OuterSize() IMGUI_DEMO_MARKER("Tables/Outer size") + -- Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY + -- Important to that note how the two flags have slightly different behaviors! ImGui.Text("Using NoHostExtendX and NoHostExtendY:") PushStyleCompact() local s = ST.outer @@ -21553,6 +24617,8 @@ local function Tables_BackgroundColor() for row = 0, 5 do ImGui.TableNextRow() + -- Demonstrate setting a row background color with 'ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBgX, ...)' + -- We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag. if s.row_bg_type ~= 0 then local row_bg_color = ImGui.GetColorU32(s.row_bg_type == 1 and ImVec4(0.7, 0.3, 0.3, 0.65) or ImVec4(0.2 + row * 0.1, 0.2, 0.2, 0.65)) -- Flat or Gradient? ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBg0 + s.row_bg_target, row_bg_color) @@ -21563,6 +24629,10 @@ local function Tables_BackgroundColor() ImGui.TableSetColumnIndex(column) ImGui.Text("%s%s", string.char(65 + row), string.char(48 + column)) + -- Change background of Cells B1->C2 + -- Demonstrate setting a cell background color with 'ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, ...)' + -- (the CellBg color will be blended over the RowBg and ColumnBg colors) + -- We can also pass a column number as a third parameter to TableSetBgColor() and do this outside the column loop. if row >= 1 and row <= 2 and column >= 1 and column <= 2 and s.cell_bg_type == 1 then local cell_bg_color = ImGui.GetColorU32(ImVec4(0.3, 0.3, 0.7, 0.65)) ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, cell_bg_color) @@ -21573,6 +24643,7 @@ local function Tables_BackgroundColor() end end +-- Simple storage to output a dummy file-system. local tree_view_nodes = { { Name = "Root with Long Name", Type = "Folder", Size = -1, ChildIdx = 1, ChildCount = 3 }, -- 0 { Name = "Music", Type = "Folder", Size = -1, ChildIdx = 4, ChildCount = 2 }, -- 1 @@ -21634,6 +24705,7 @@ local function Tables_TreeView() DemoHelpMarker("See \"Columns flags\" section to configure how indentation is applied to individual columns.") if ImGui.BeginTable("3ways", 3, s.table_flags) then + -- The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.NoHide) ImGui.TableSetupColumn("Size", ImGuiTableColumnFlags.WidthFixed, TEXT_BASE_WIDTH * 12.0) ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthFixed, TEXT_BASE_WIDTH * 18.0) @@ -21683,6 +24755,7 @@ local function Tables_ItemWidth() end end +-- Demonstrate using TableHeader() calls instead of TableHeadersRow() local function Tables_CustomHeaders() IMGUI_DEMO_MARKER("Tables/Custom headers") local COLUMNS_COUNT = 3 @@ -21692,9 +24765,15 @@ local function Tables_CustomHeaders() ImGui.TableSetupColumn("Cherry") -- Dummy entire-column selection storage + -- FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox. if ST.column_selected == nil then ST.column_selected = { false, false, false } end local column_selected = ST.column_selected + -- Instead of calling TableHeadersRow() we'll submit custom headers ourselves. + -- (A different approach is also possible: + -- - Specify ImGuiTableColumnFlags_NoHeaderLabel in some TableSetupColumn() call. + -- - Call TableHeadersRow() normally. This will submit TableHeader() with no name. + -- - Then call TableSetColumnIndex() to position yourself in the column and submit your stuff e.g. Checkbox().) ImGui.TableNextRow(ImGuiTableRowFlags.Headers) for column = 0, COLUMNS_COUNT - 1 do ImGui.TableSetColumnIndex(column) @@ -21721,6 +24800,7 @@ local function Tables_CustomHeaders() end end +-- Demonstrate using ImGuiTableColumnFlags_AngledHeader flag to create angled headers local function Tables_AngledHeaders() IMGUI_DEMO_MARKER("Tables/Angled headers") local column_names = { "Track", "cabasa", "ride", "smash", "tom-hi", "tom-mid", "tom-low", "hihat-o", "hihat-c", "snare-s", "snare-c", "clap", "rim", "kick" } @@ -21731,7 +24811,7 @@ local function Tables_AngledHeaders() if s == nil then s = { table_flags = bor(TF.SizingFixedFit, TF.ScrollX, TF.ScrollY, TF.BordersOuter, TF.BordersInnerH, TF.Hideable, TF.Resizable, TF.Reorderable, TF.HighlightHoveredColumn), column_flags = bor(ImGuiTableColumnFlags.AngledHeader, ImGuiTableColumnFlags.WidthFixed), - bools = {}, frozen_cols = 1, frozen_rows = 2 } + bools = {}, frozen_cols = 1, frozen_rows = 2 } -- bools: Dummy storage selection storage for i = 1, columns_count * rows_count do s.bools[i] = false end ST.angled = s end @@ -21787,6 +24867,8 @@ local function Tables_AngledHeaders() end end +-- Demonstrate creating custom context menus inside columns, +-- while playing it nice with context menus provided by TableHeadersRow()/TableHeader() local function Tables_ContextMenus() IMGUI_DEMO_MARKER("Tables/Context menus") DemoHelpMarker( @@ -21799,6 +24881,9 @@ local function Tables_ContextMenus() _, s.flags1 = ImGui.CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", s.flags1, TF.ContextMenuInBody) PopStyleCompact() + -- Context Menus: first example + -- [1.1] Right-click on the TableHeadersRow() line to open the default table context menu. + -- [1.2] Right-click in columns also open the default table context menu (if ImGuiTableFlags_ContextMenuInBody is set) local COLUMNS_COUNT = 3 if ImGui.BeginTable("table_context_menu", COLUMNS_COUNT, s.flags1) then ImGui.TableSetupColumn("One") @@ -21819,6 +24904,10 @@ local function Tables_ContextMenus() ImGui.EndTable() end + -- Context Menus: second example + -- [2.1] Right-click on the TableHeadersRow() line to open the default table context menu. + -- [2.2] Right-click on the ".." to open a custom popup + -- [2.3] Right-click in columns to open another custom popup DemoHelpMarker( "Demonstrate mixing table context menu (over header), item context button (over button) " .. "and custom per-column context menu (over column body).") @@ -21853,6 +24942,8 @@ local function Tables_ContextMenus() end -- [2.3] Right-click anywhere in columns to open another custom popup + -- (instead of testing for not IsAnyItemHovered() we could also call OpenPopup() with ImGuiPopupFlags_NoOpenOverExistingPopup + -- to manage popup priority as the popups triggers, here "are we hovering a column" are overlapping) local hovered_column = -1 for column = 0, COLUMNS_COUNT do ImGui.PushID(column) @@ -21881,6 +24972,7 @@ local function Tables_ContextMenus() end end +-- Demonstrate creating multiple tables with the same ID local function Tables_SyncedInstances() IMGUI_DEMO_MARKER("Tables/Synced instances") DemoHelpMarker("Multiple tables with the same identifier will share their settings, width, visibility, order etc.") @@ -21909,6 +25001,9 @@ local function Tables_SyncedInstances() end end +-- Demonstrate using Sorting facilities +-- This is a simplified version of the "Advanced" example, where we mostly focus on the code necessary to handle sorting. +-- Note that the "Advanced" example also showcase manually triggering a sort (e.g. if item quantities have been modified) local template_items_names = { "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango", "Kiwi", "Orange", "Pineapple", "Blueberry", "Plum", "Coconut", "Pear", "Apricot" @@ -21916,6 +25011,7 @@ local template_items_names = { local function Tables_Sorting() IMGUI_DEMO_MARKER("Tables/Sorting") + -- Create item list local s = ST.sorting if s == nil then s = { items = {}, @@ -21928,6 +25024,7 @@ local function Tables_Sorting() end local items = s.items + -- Options PushStyleCompact() _, s.flags = ImGui.CheckboxFlags("ImGuiTableFlags_SortMulti", s.flags, TF.SortMulti) ImGui.SameLine(); DemoHelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).") @@ -21937,6 +25034,13 @@ local function Tables_Sorting() if ImGui.BeginTable("table_sorting", 4, s.flags, ImVec2(0.0, TEXT_BASE_HEIGHT * 15), 0.0) then local CF = ImGuiTableColumnFlags + -- Declare columns + -- We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + -- This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! + -- Demonstrate using a mixture of flags among available sort-related flags: + -- - ImGuiTableColumnFlags_DefaultSort + -- - ImGuiTableColumnFlags_NoSort / ImGuiTableColumnFlags_NoSortAscending / ImGuiTableColumnFlags_NoSortDescending + -- - ImGuiTableColumnFlags_PreferSortAscending / ImGuiTableColumnFlags_PreferSortDescending ImGui.TableSetupColumn("ID", bor(CF.DefaultSort, CF.WidthFixed), 0.0, MyItemColumnID_ID) ImGui.TableSetupColumn("Name", CF.WidthFixed, 0.0, MyItemColumnID_Name) ImGui.TableSetupColumn("Action", bor(CF.NoSort, CF.WidthFixed), 0.0, MyItemColumnID_Action) @@ -22067,6 +25171,8 @@ local function Tables_AdvancedOptions(s) "- OuterSize.x = 0.0f will narrow fit the table unless there are any Stretch columns.\n" .. "- OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendY is set).") + -- From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling. + -- To facilitate toying with this demo we will actually pass 0.0f to the BeginTable() when ScrollX is disabled. s.inner_width_with_scroll = ImGui.DragFloat("inner_width (when ScrollX active)", s.inner_width_with_scroll, 1.0, 0.0, FLT_MAX) s.row_min_height = ImGui.DragFloat("row_min_height", s.row_min_height, 1.0, 0.0, FLT_MAX) @@ -22087,6 +25193,9 @@ local function Tables_AdvancedOptions(s) ImGui.Spacing() end +-- In this example we'll expose most table flags and settings. +-- For specific flags and settings refer to the corresponding section for more detailed explanation. +-- This section is mostly useful to experiment with combining certain flags or settings with each others. local function Tables_Advanced() IMGUI_DEMO_MARKER("Tables/Advanced") local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 @@ -22100,6 +25209,7 @@ local function Tables_Advanced() items = {}, selection = {}, items_need_sort = false, show_debug_details = false } ST.advanced = s end + --ImGui.SetNextItemOpen(true, ImGuiCond.Once) -- FIXME-TABLE: Enabling this results in initial clipped first pass on table which tend to affect column sizing if ImGui.TreeNode("Options") then Tables_AdvancedOptions(s) ImGui.TreePop() @@ -22119,7 +25229,7 @@ local function Tables_Advanced() local parent_draw_list = ImGui.GetWindowDrawList() local parent_draw_list_draw_cmd_count = parent_draw_list.CmdBuffer.Size local table_scroll_cur, table_scroll_max -- For debug display - local table_draw_list = nil + local table_draw_list = nil -- " -- Submit table local flags = s.flags @@ -22127,6 +25237,9 @@ local function Tables_Advanced() local inner_width_to_use = Has(flags, TF.ScrollX) and s.inner_width_with_scroll or 0.0 local CF = ImGuiTableColumnFlags if ImGui.BeginTable("table_advanced", 6, flags, s.outer_size_enabled and s.outer_size_value or ImVec2(0, 0), inner_width_to_use) then + -- Declare columns + -- We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + -- This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! ImGui.TableSetupColumn("ID", bor(columns_base_flags, CF.DefaultSort, CF.WidthFixed, CF.NoHide), 0.0, MyItemColumnID_ID) ImGui.TableSetupColumn("Name", bor(columns_base_flags, CF.WidthFixed), 0.0, MyItemColumnID_Name) ImGui.TableSetupColumn("Action", bor(columns_base_flags, CF.NoSort, CF.WidthFixed), 0.0, MyItemColumnID_Action) @@ -22146,6 +25259,8 @@ local function Tables_Advanced() end s.items_need_sort = false + -- Take note of whether we are currently sorting based on the Quantity field, + -- we will use this to trigger sorting when we know the data of this column has been modified. local sorts_specs_using_quantity = Has(ImGui.TableGetColumnFlags(3), CF.IsSorted) -- Show headers @@ -22156,6 +25271,8 @@ local function Tables_Advanced() ImGui.TableHeadersRow() end + -- Show data + -- FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here? -- Demonstrate using clipper for large vertical lists local clipper = ImGuiListClipper() clipper:Begin(#items) @@ -22199,6 +25316,10 @@ local function Tables_Advanced() ImGui.TextUnformatted(item.Name) end + -- Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity, + -- and we are currently sorting on the column showing the Quantity. + -- To avoid triggering a sort while holding the button, we only trigger it when the button has been released. + -- You will probably need some extra logic if you want to automatically sort when a specific entry changes. if ImGui.TableSetColumnIndex(2) then if ImGui.SmallButton("Chop") then item.Quantity = item.Quantity + 1 end if sorts_specs_using_quantity and ImGui.IsItemDeactivated() then s.items_need_sort = true end @@ -22248,6 +25369,8 @@ end local DCS = { selected = -1, h_borders = true, v_borders = true, columns_count = 4, foo = 1.0, bar = 1.0 } +-- Demonstrate old/legacy Columns API! +-- [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!] local function DemoWindowColumns() local open = ImGui.TreeNode("Legacy Columns API") ImGui.SameLine() @@ -22265,6 +25388,7 @@ local function DemoWindowColumns() for n = 0, 13 do local label = string.format("Item %d", n) if ImGui.Selectable(label) then end + --if ImGui.Button(label, ImVec2(-FLT_MIN,0.0)) then end ImGui.NextColumn() end ImGui.Columns(1) @@ -22463,6 +25587,7 @@ local tables_sections = { } function DemoWindowTables() + --ImGui.SetNextItemOpen(true, ImGuiCond.Once) if not ImGui.CollapsingHeader("Tables & Columns") then return end @@ -22493,6 +25618,16 @@ function DemoWindowTables() ImGui.PushStyleVar(ImGuiStyleVar.IndentSpacing, 0.0) end + -- About Styling of tables + -- Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs. + -- There are however a few settings that a shared and part of the ImGuiStyle structure: + -- style.CellPadding -- Padding within each cell + -- style.Colors[ImGuiCol.TableHeaderBg] -- Table header background + -- style.Colors[ImGuiCol.TableBorderStrong] -- Table outer and header borders + -- style.Colors[ImGuiCol.TableBorderLight] -- Table inner borders + -- style.Colors[ImGuiCol.TableRowBg] -- Table row background when ImGuiTableFlags_RowBg is enabled (even rows) + -- style.Colors[ImGuiCol.TableRowBgAlt] -- Table row background when ImGuiTableFlags_RowBg is enabled (odds rows) + -- Demos for _, sec in ipairs(tables_sections) do if open_action ~= -1 then @@ -22524,26 +25659,36 @@ local function BufSet(buf, str) buf[#str + 1] = 0 end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Debug Console / ShowExampleAppConsole() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a simple console window, with scrolling, filtering, completion and history. +-- For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions. local Console = nil local function ConsoleNew() + -- HistoryPos: -1: new line, 0..#History-1 browsing history. + -- "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. local c = { InputBuf = Buf("", 256), Items = {}, Commands = { "HELP", "HISTORY", "CLEAR", "CLASSIFY" }, History = {}, HistoryPos = -1, Filter = ImGuiTextFilter(), AutoScroll = true, ScrollToBottom = false } function c:ClearLog() self.Items = {} end function c:AddLog(fmt, ...) + -- FIXME-OPT local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt self.Items[#self.Items + 1] = s end function c:ExecCommand(command_line) self:AddLog("# %s\n", command_line) + + -- Insert into history. First find match and delete it so it can be pushed to the back. + -- This isn't trying to be smart or optimal. self.HistoryPos = -1 for i = #self.History, 1, -1 do if string.upper(self.History[i]) == string.upper(command_line) then table.remove(self.History, i); break end end self.History[#self.History + 1] = command_line + + -- Process command local cmd = string.upper(command_line) if cmd == "CLEAR" then self:ClearLog() @@ -22556,10 +25701,15 @@ local function ConsoleNew() else self:AddLog("Unknown command: '%s'\n", command_line) end + + -- On command input, we scroll to bottom even if AutoScroll==false self.ScrollToBottom = true end function c:TextEditCallback(data) + --self:AddLog("cursor: %d, selection: %d-%d", data.CursorPos, data.SelectionStart, data.SelectionEnd) if data.EventFlag == ImGuiInputTextFlags.CallbackCompletion then + -- Example of TEXT COMPLETION + -- Locate beginning of current word (positions are 0-based offsets into data.Buf) local word_end = data.CursorPos local word_start = word_end @@ -22570,17 +25720,23 @@ local function ConsoleNew() end local word = "" for i = word_start + 1, word_end do word = word .. string.char(data.Buf[i]) end + + -- Build a list of candidates local candidates = {} for i = 1, #self.Commands do if string.upper(string.sub(self.Commands[i], 1, #word)) == string.upper(word) then candidates[#candidates + 1] = self.Commands[i] end end if #candidates == 0 then + -- No match self:AddLog("No match for \"%s\"!\n", word) elseif #candidates == 1 then + -- Single match. Delete the beginning of the word and replace it entirely so we've got nice casing. data:DeleteChars(word_start, word_end - word_start) data:InsertChars(data.CursorPos, candidates[1]) data:InsertChars(data.CursorPos, " ") else + -- Multiple matches. Complete as much as we can.. + -- So inputting "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches. local match_len = word_end - word_start while true do local ch, all_match = nil, true @@ -22595,10 +25751,13 @@ local function ConsoleNew() data:DeleteChars(word_start, word_end - word_start) data:InsertChars(data.CursorPos, string.sub(candidates[1], 1, match_len)) end + + -- List matches self:AddLog("Possible matches:\n") for i = 1, #candidates do self:AddLog("- %s\n", candidates[i]) end end elseif data.EventFlag == ImGuiInputTextFlags.CallbackHistory then + -- Example of HISTORY local prev_history_pos = self.HistoryPos if data.EventKey == ImGuiKey.UpArrow then if self.HistoryPos == -1 then self.HistoryPos = #self.History - 1 @@ -22609,6 +25768,8 @@ local function ConsoleNew() if self.HistoryPos >= #self.History then self.HistoryPos = -1 end end end + + -- A better implementation would preserve the data on the current input line along with cursor position. if prev_history_pos ~= self.HistoryPos then local history_str = (self.HistoryPos >= 0) and self.History[self.HistoryPos + 1] or "" data:DeleteChars(0, data.BufTextLen) @@ -22623,12 +25784,18 @@ local function ConsoleNew() p_open, visible = ImGui.Begin(title, p_open) if not visible then ImGui.End(); return p_open end + -- As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. + -- So e.g. IsItemHovered() will return true when hovering the title bar. + -- Here we create a context menu only available from the title bar. if ImGui.BeginPopupContextItem() then if ImGui.MenuItem("Close Console") then p_open = false end ImGui.EndPopup() end ImGui.TextWrapped("This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc.") ImGui.TextWrapped("Enter 'HELP' for help.") + + -- TODO: display items starting from the bottom + if ImGui.SmallButton("Add Debug Text") then self:AddLog("%d some text", #self.Items); self:AddLog("some more text"); self:AddLog("display very important message here!") end ImGui.SameLine() if ImGui.SmallButton("Add Debug Error") then self:AddLog("[error] something went wrong") end @@ -22636,12 +25803,17 @@ local function ConsoleNew() if ImGui.SmallButton("Clear") then self:ClearLog() end ImGui.SameLine() local copy_to_clipboard = ImGui.SmallButton("Copy") + --local t = 0.0; if ImGui.GetTime() - t > 0.02 then t = ImGui.GetTime(); self:AddLog("Spam %f", t) end + ImGui.Separator() + -- Options menu if ImGui.BeginPopup("Options") then _, self.AutoScroll = ImGui.Checkbox("Auto-scroll", self.AutoScroll) ImGui.EndPopup() end + + -- Options, Filter ImGui.SetNextItemShortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.O), ImGuiInputFlags.Tooltip) if ImGui.Button("Options") then ImGui.OpenPopup("Options") end ImGui.SameLine() @@ -22650,6 +25822,7 @@ local function ConsoleNew() self.Filter:DrawWithHint("##Filter", "Filter (incl -excl)") ImGui.Separator() + -- Reserve enough left-over height for 1 separator + 1 input text local style = ImGui.GetStyle() local footer_height_to_reserve = (style.SeparatorSize or 1.0) + style.ItemSpacing.y + ImGui.GetFrameHeightWithSpacing() if ImGui.BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), ImGuiChildFlags.NavFlattened, ImGuiWindowFlags.HorizontalScrollbar) then @@ -22657,10 +25830,37 @@ local function ConsoleNew() if ImGui.Selectable("Clear") then self:ClearLog() end ImGui.EndPopup() end - ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(4, 1)) + + -- Display every line as a separate entry so we can change their color or add custom widgets. + -- If you only want raw text you can use ImGui.TextUnformatted(log.begin(), log.end()) + -- NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping + -- to only process visible items. The clipper will automatically measure the height of your first item and then + -- "seek" to display only items in the visible area. + -- To use the clipper we can replace your standard loop: + -- for i = 1, #Items do + -- With: + -- local clipper = ImGuiListClipper() + -- clipper:Begin(#Items) + -- while clipper:Step() do + -- for i = clipper.DisplayStart, clipper.DisplayEnd - 1 do + -- - That your items are evenly spaced (same height) + -- - That you have cheap random access to your elements (you can access them given their index, + -- without processing all the ones before) + -- You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property. + -- We would need random-access on the post-filtered list. + -- A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices + -- or offsets of items that passed the filtering test, recomputing this array when user changes the filter, + -- and appending newly elements as they are inserted. This is left as a task to the user until we can manage + -- to improve this example code! + -- If your items are of variable height: + -- - Split them into same height items would be simpler and facilitate random-seeking into your list. + -- - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items. + ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(4, 1)) -- Tighten spacing if copy_to_clipboard then ImGui.LogToClipboard() end for _, item in ipairs(self.Items) do if self.Filter:PassFilter(item) then + -- Normally you would store more information in your item than just a string. + -- (e.g. make Items[] an array of structure, store color/type etc.) local color if string.find(item, "[error]", 1, true) then color = ImVec4(1.0, 0.4, 0.4, 1.0) elseif string.sub(item, 1, 2) == "# " then color = ImVec4(1.0, 0.8, 0.6, 1.0) end @@ -22670,6 +25870,9 @@ local function ConsoleNew() end end if copy_to_clipboard then ImGui.LogFinish() end + + -- Keep up at the bottom of the scroll region if we were already at the bottom at the beginning of the frame. + -- Using a scrollbar or mouse-wheel will take away from the bottom edge. if self.ScrollToBottom or (self.AutoScroll and ImGui.GetScrollY() >= ImGui.GetScrollMaxY()) then ImGui.SetScrollHereY(1.0) end self.ScrollToBottom = false ImGui.PopStyleVar() @@ -22677,6 +25880,7 @@ local function ConsoleNew() ImGui.EndChild() ImGui.Separator() + -- Command-line local reclaim_focus = false local IT = ImGuiInputTextFlags local input_text_flags = bit32.bor(IT.EnterReturnsTrue, IT.EscapeClearsAll, IT.CallbackCompletion, IT.CallbackHistory) @@ -22686,8 +25890,10 @@ local function ConsoleNew() self.InputBuf[1] = 0 reclaim_focus = true end + + -- Auto-focus on window apparition ImGui.SetItemDefaultFocus() - if reclaim_focus then ImGui.SetKeyboardFocusHere(-1) end + if reclaim_focus then ImGui.SetKeyboardFocusHere(-1) end -- Auto focus previous widget ImGui.End() return p_open end @@ -22700,13 +25906,17 @@ function ShowExampleAppConsole(p_open) return Console:Draw("Example: Console", p_open) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Debug Log / ShowExampleAppLog() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Usage: +-- local my_log = ExampleAppLog() +-- my_log:AddLog("Hello %d world\n", 123) +-- my_log:Draw("title") -- Lines are stored as a Lua array (equivalent of Buf + LineOffsets) local function ExampleAppLog() - local l = { Lines = { "" }, Filter = ImGuiTextFilter(), AutoScroll = true } + local l = { Lines = { "" }, Filter = ImGuiTextFilter(), AutoScroll = true } -- AutoScroll: Keep scrolling if already at the bottom. function l:Clear() self.Lines = { "" } end function l:AddLog(fmt, ...) local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt @@ -22721,10 +25931,14 @@ local function ExampleAppLog() local visible p_open, visible = ImGui.Begin(title, p_open) if not visible then ImGui.End(); return p_open end + + -- Options menu if ImGui.BeginPopup("Options") then _, self.AutoScroll = ImGui.Checkbox("Auto-scroll", self.AutoScroll) ImGui.EndPopup() end + + -- Main window if ImGui.Button("Options") then ImGui.OpenPopup("Options") end ImGui.SameLine() local clear = ImGui.Button("Clear") @@ -22740,10 +25954,27 @@ local function ExampleAppLog() ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0)) local lines = self.Lines if self.Filter:IsActive() then + -- In this example we don't use the clipper when Filter is enabled. + -- This is because we don't have random access to the result of our filter. + -- A real application processing logs with ten of thousands of entries may want to store the result of + -- search/filter.. especially if the filtering function is not trivial (e.g. reg-exp). for line_no = 1, #lines do if self.Filter:PassFilter(lines[line_no]) then ImGui.TextUnformatted(lines[line_no]) end end else + -- The simplest and easy way to display the entire buffer: + -- ImGui.TextUnformatted(buf_begin, buf_end) + -- And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward + -- to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are + -- within the visible area. + -- If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them + -- on your side is recommended. Using ImGuiListClipper requires + -- - A) random access into your data + -- - B) items all being the same height, + -- both of which we can handle since we have an array pointing to the beginning of each line of text. + -- When using the filter (in the block of code above) we don't have random access into the data to display + -- anymore, which is why we don't use the clipper. Storing or skimming through the search result would make + -- it possible (and would be recommended if you want to search through tens of thousands of entries). local clipper = ImGuiListClipper() clipper:Begin(#lines) while clipper:Step() do @@ -22753,6 +25984,9 @@ local function ExampleAppLog() end ImGui.PopStyleVar() if copy then ImGui.LogFinish() end + + -- Keep up at the bottom of the scroll region if we were already at the bottom at the beginning of the frame. + -- Using a scrollbar or mouse-wheel will take away from the bottom edge. if self.AutoScroll and ImGui.GetScrollY() >= ImGui.GetScrollMaxY() then ImGui.SetScrollHereY(1.0) end end ImGui.EndChild() @@ -22762,9 +25996,14 @@ local function ExampleAppLog() return l end +-- Demonstrate creating a simple log window with basic filtering. local AppLog, AppLogCounter = nil, 0 function ShowExampleAppLog(p_open) AppLog = AppLog or ExampleAppLog() + + -- For the demo: add a debug button _BEFORE_ the normal log window contents + -- We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window. + -- Most of the contents of the window will be added by the log:Draw() call. ImGui.SetNextWindowSize(ImVec2(500, 400), ImGuiCond.FirstUseEver) p_open = ImGui.Begin("Example: Log", p_open) if ImGui.SmallButton("[Debug] Add 5 entries") then @@ -22778,13 +26017,16 @@ function ShowExampleAppLog(p_open) end end ImGui.End() + + -- Actually call in the regular Log helper (which will Begin() into the same window as we just did) return AppLog:Draw("Example: Log", p_open) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Simple Layout / ShowExampleAppLayout() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate create a window with multiple child windows. local LayoutSelected = 0 function ShowExampleAppLayout(p_open) ImGui.SetNextWindowSize(ImVec2(500, 440), ImGuiCond.FirstUseEver) @@ -22798,14 +26040,18 @@ function ShowExampleAppLayout(p_open) end ImGui.EndMenuBar() end + + -- Left ImGui.BeginChild("left pane", ImVec2(150, 0), bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.ResizeX)) for i = 0, 99 do if ImGui.Selectable(string.format("MyObject %d", i), LayoutSelected == i, ImGuiSelectableFlags.SelectOnNav) then LayoutSelected = i end end ImGui.EndChild() ImGui.SameLine() + + -- Right ImGui.BeginGroup() - ImGui.BeginChild("item view", ImVec2(0, -ImGui.GetFrameHeightWithSpacing())) + ImGui.BeginChild("item view", ImVec2(0, -ImGui.GetFrameHeightWithSpacing())) -- Leave room for 1 line below us ImGui.Text("MyObject: %d", LayoutSelected) ImGui.Separator() if ImGui.BeginTabBar("##Tabs", ImGuiTabBarFlags.None) then @@ -22829,9 +26075,14 @@ function ShowExampleAppLayout(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Some of the interactions are a bit lack-luster: +-- - We would want pressing validating or leaving the filter to somehow restore focus. +-- - We may want more advanced filtering (child nodes) and clipper support: both will need extra work. +-- - We would want to customize some keyboard interactions to easily keyboard navigate between the tree and the properties. +------------------------------------------------------------------------------- -- ExampleMemberInfo equivalent: field name, data type, component count local ExampleTreeNodeMemberInfos = { @@ -22843,19 +26094,30 @@ local ExampleTreeNodeMemberInfos = { local PropEd = { Filter = nil, SelectedNode = nil, UseClipper = false, NameBufs = setmetatable({}, { __mode = "k" }) } +-- Custom search filter +-- - Here we apply on root node only. +-- - This does a case insensitive stristr which is pretty heavy. In a real large-scale app you would likely store a filtered list which in turns would be trivial to linearize. function PropEd:IsNodePassingFilter(node) return node.Parent.Parent ~= nil or self.Filter:PassFilter(node.Name) end +-- To support node with same name we incorporate node.UID into the item ID. +-- (this would more naturally be done using PushID(node.UID) + TreeNodeEx(node.Name, tree_flags), +-- but it would require in DrawClippedTreeNodeAndAdvanceToNext() to add PushID() before TreePush(), and PopID() after TreePop(), +-- so instead we use TreeNodeEx(node.UID, tree_flags, "%s", node.Name) here) function PropEd:DrawTreeNode(node) local TN = ImGuiTreeNodeFlags ImGui.TableNextRow() ImGui.TableNextColumn() + -- OpenOnArrow | OpenOnDoubleClick: Standard opening mode as we are likely to want to add selection afterwards + -- NavLeftJumpsToParent: Left arrow support + -- SpanFullWidth: Span full width for easier mouse reach + -- DrawLinesToNodes: Always draw hierarchy outlines local tree_flags = bit32.bor(TN.OpenOnArrow, TN.OpenOnDoubleClick, TN.NavLeftJumpsToParent, TN.SpanFullWidth, TN.DrawLinesToNodes) - if node == self.SelectedNode then tree_flags = bit32.bor(tree_flags, TN.Selected) end - if #node.Childs == 0 then tree_flags = bit32.bor(tree_flags, TN.Leaf, TN.Bullet, TN.NoTreePushOnOpen) end + if node == self.SelectedNode then tree_flags = bit32.bor(tree_flags, TN.Selected) end -- Draw selection highlight + if #node.Childs == 0 then tree_flags = bit32.bor(tree_flags, TN.Leaf, TN.Bullet, TN.NoTreePushOnOpen) end -- Use _NoTreePushOnOpen + set is_open=false to avoid unnecessarily push/pop on leaves. if node.DataMyBool == false then ImGui.PushStyleColor(ImGuiCol.Text, ImGui.GetStyle().Colors[ImGuiCol.TextDisabled]) end - ImGui.SetNextItemStorageID(node.UID) + ImGui.SetNextItemStorageID(node.UID) -- Use node.UID as storage id local is_open = ImGui.TreeNodeEx(node.UID, tree_flags, "%s", node.Name) if #node.Childs == 0 then is_open = false end if node.DataMyBool == false then ImGui.PopStyleColor() end @@ -22863,6 +26125,10 @@ function PropEd:DrawTreeNode(node) return is_open end +-- Basic version, recursive. This is how you would generally draw a tree. +-- - Simple but going to be noticeably costly if you have a large amount of nodes as DrawTreeNode() is called for all of them. +-- - On my desktop PC (2020), for 10K nodes in an optimized build this takes ~1.2 ms +-- - Unlike arrays or grids which are very easy to clip, trees are currently more difficult to clip. function PropEd:DrawTree(node) for _, child in ipairs(node.Childs) do if self:IsNodePassingFilter(child) and self:DrawTreeNode(child) then @@ -22874,6 +26140,7 @@ end function PropEd:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) if self:IsNodePassingFilter(node) then + -- Draw node if within visible range local is_open if clipper.UserIndex >= clipper.DisplayStart and clipper.UserIndex < clipper.DisplayEnd then is_open = self:DrawTreeNode(node) @@ -22882,8 +26149,12 @@ function PropEd:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) if is_open then ImGui.TreePush(node.Name) end end clipper.UserIndex = clipper.UserIndex + 1 + + -- Next node: recurse into childs if is_open then return node.Childs[1] end end + + -- Next node: next sibling, otherwise move back to parent while node ~= nil do if node.IndexInParent + 1 < #node.Parent.Childs then return node.Parent.Childs[node.IndexInParent + 2] @@ -22895,8 +26166,18 @@ function PropEd:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) return nil end +-- More advanced version. Use a alternative clipping technique: fast-forwarding through non-visible chunks. +-- - On my desktop PC (2020), for 10K nodes in an optimized build this takes ~0.1 ms +-- (in ExampleTree_CreateDemoTree(), change 'ROOT_ITEMS_COUNT = 10000' to try with this amount of root nodes). +-- - 1. Use clipper with indeterminate count (items_count = INT_MAX): we need to call SeekCursorForItem() at the end once we know the count. +-- - 2. Use SetNextItemStorageID() to specify ID used for open/close storage, making it easy to call TreeNodeGetOpen() on any arbitrary node. +-- - 3. Linearize tree during traversal: our tree data structure makes it easy to access sibling and parents. +-- - Unlike clipping for a regular array or grid which may be done using random access limited to visible areas, +-- this technique requires traversing most accessible nodes. This could be made more optimal with extra work, +-- but this is a decent simplicity<>speed trade-off. +-- See https://github.com/ocornut/imgui/issues/3823 for discussions about this. function PropEd:DrawClippedTree(root_node) - local node = root_node.Childs[1] + local node = root_node.Childs[1] -- First node local clipper = ImGuiListClipper() clipper:Begin(INT_MAX) while clipper:Step() do @@ -22904,14 +26185,23 @@ function PropEd:DrawClippedTree(root_node) node = self:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) end end + + -- Keep going to count nodes and submit final count so we have a reliable scrollbar. + -- - One could consider caching this value and only refreshing it occasionally e.g. window is focused and an action occurs. + -- - Incorrect but cheap approximation would be to use 'clipper_current_idx = IM_MAX(clipper_current_idx, #root_node.Childs)' instead. + -- - If either of those is implemented, the general cost will approach zero when scrolling is at the top of the tree. while node ~= nil do node = self:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) end + --clipper.UserIndex = math.max(clipper.UserIndex, #root_node.Childs) -- <-- Cheap approximation instead of while() loop above. clipper:SeekCursorForItem(clipper.UserIndex) end function PropEd:Draw(root_node) self.Filter = self.Filter or ImGuiTextFilter() + -- Left side: draw tree + -- - Currently using a table to benefit from RowBg feature + -- - Our tree node are all of equal height, facilitating the use of a clipper. if ImGui.BeginChild("##tree", ImVec2(300, 0), bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.Borders, ImGuiChildFlags.NavFlattened)) then ImGui.PushItemFlag(ImGuiItemFlags.NoNavDefaultFocus, true) _, self.UseClipper = ImGui.Checkbox("Use Clipper", self.UseClipper) @@ -22930,18 +26220,24 @@ function PropEd:Draw(root_node) end ImGui.EndChild() + -- Right side: draw properties ImGui.SameLine() - ImGui.BeginGroup() + + ImGui.BeginGroup() -- Lock X position local node = self.SelectedNode if node then ImGui.Text("%s", node.Name) ImGui.TextDisabled("UID: 0x%08X", node.UID) ImGui.Separator() if ImGui.BeginTable("##properties", 2, bit32.bor(ImGuiTableFlags.Resizable, ImGuiTableFlags.ScrollY)) then + -- Push object ID after we entered the table, so table is shared for all objects ImGui.PushID(node.UID) ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed) - ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthStretch, 2.0) + ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthStretch, 2.0) -- Default twice larger if node.HasData then + -- In a typical application, the structure description would be derived from a data-driven system. + -- - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array. + -- - Limits and some details are hard-coded to simplify the demo. for _, field_desc in ipairs(ExampleTreeNodeMemberInfos) do ImGui.TableNextRow() ImGui.PushID(field_desc.Name) @@ -22973,6 +26269,7 @@ function PropEd:Draw(root_node) ImGui.EndGroup() end +-- Demonstrate creating a simple property editor. local DemoTree = nil function ShowExampleAppPropertyEditor(p_open, demo_data) ImGui.SetNextWindowSize(ImVec2(430, 450), ImGuiCond.FirstUseEver) @@ -22986,10 +26283,11 @@ function ShowExampleAppPropertyEditor(p_open, demo_data) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Long Text / ShowExampleAppLongText() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate/test rendering huge amount of text, and the incidence of clipping. local LT = { test_type = 0, log = {}, lines = 0, bytes = 0 } function ShowExampleAppLongText(p_open) ImGui.SetNextWindowSize(ImVec2(520, 600), ImGuiCond.FirstUseEver) @@ -23012,9 +26310,11 @@ function ShowExampleAppLongText(p_open) end ImGui.BeginChild("Log") if LT.test_type == 0 then + -- Single call to TextUnformatted() with a big buffer LT.text = LT.text or table.concat(LT.log) ImGui.TextUnformatted(LT.text) elseif LT.test_type == 1 then + -- Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0)) local clipper = ImGuiListClipper() clipper:Begin(LT.lines) @@ -23023,6 +26323,7 @@ function ShowExampleAppLongText(p_open) end ImGui.PopStyleVar() else + -- Multiple calls to Text(), not clipped (slow) ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0)) for i = 0, LT.lines - 1 do ImGui.Text("%i The quick brown fox jumps over the lazy dog", i) end ImGui.PopStyleVar() @@ -23032,10 +26333,11 @@ function ShowExampleAppLongText(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a window which gets auto-resized according to its content. local AutoResizeLines = 10 function ShowExampleAppAutoResize(p_open) local visible @@ -23043,17 +26345,23 @@ function ShowExampleAppAutoResize(p_open) if not visible then ImGui.End(); return p_open end ImGui.TextUnformatted("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop.") AutoResizeLines = ImGui.SliderInt("Number of lines", AutoResizeLines, 1, 20) - for i = 0, AutoResizeLines - 1 do ImGui.Text("%sThis is line %d", string.rep(" ", i * 4), i) end + for i = 0, AutoResizeLines - 1 do ImGui.Text("%sThis is line %d", string.rep(" ", i * 4), i) end -- Pad with space to extend size horizontally ImGui.End() return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize() ----------------------------------------------------------------- +------------------------------------------------------------------------------- -local CR = { auto_resize = false, window_padding = true, type = 6, display_lines = 10 } +-- Demonstrate creating a window with custom resize constraints. +-- Note that size constraints currently don't work on a docked window (when in 'docking' branch) +-- Options +local CR = { auto_resize = false, window_padding = true, type = 6, display_lines = 10 } -- type 6: Aspect Ratio function ShowExampleAppConstrainedResize(p_open) + -- Helper functions to demonstrate programmatic constraints + -- FIXME: This doesn't take account of decoration size (e.g. title bar), library should make this easier. + -- FIXME: None of the three demos works consistently when resizing from borders. local function AspectRatio(data) data.DesiredSize.y = math.floor(data.DesiredSize.x / data.UserData) end local function Square(data) local m = math.max(data.DesiredSize.x, data.DesiredSize.y); data.DesiredSize.x = m; data.DesiredSize.y = m end local function Step(data) @@ -23062,17 +26370,19 @@ function ShowExampleAppConstrainedResize(p_open) end local test_desc = { "Between 100x100 and 500x500", "At least 100x100", "Resize vertical + lock current width", "Resize horizontal + lock current height", "Width Between 400 and 500", "Height at least 400", "Custom: Aspect Ratio 16:9", "Custom: Always Square", "Custom: Fixed Steps (100)" } + -- Submit constraint local t = CR.type - if t == 0 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(500, 500)) end - if t == 1 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)) end - if t == 2 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)) end - if t == 3 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)) end - if t == 4 then ImGui.SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)) end - if t == 5 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, FLT_MAX)) end - if t == 6 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), AspectRatio, 16.0 / 9.0) end - if t == 7 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Square) end - if t == 8 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Step, 100.0) end + if t == 0 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(500, 500)) end -- Between 100x100 and 500x500 + if t == 1 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)) end -- Width > 100, Height > 100 + if t == 2 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)) end -- Resize vertical + lock current width + if t == 3 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)) end -- Resize horizontal + lock current height + if t == 4 then ImGui.SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)) end -- Width Between and 400 and 500 + if t == 5 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, FLT_MAX)) end -- Height at least 400 + if t == 6 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), AspectRatio, 16.0 / 9.0) end -- Aspect ratio + if t == 7 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Square) end -- Always Square + if t == 8 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Step, 100.0) end -- Fixed Step + -- Submit window if not CR.window_padding then ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0.0, 0.0)) end local window_flags = CR.auto_resize and ImGuiWindowFlags.AlwaysAutoResize or 0 local window_open @@ -23080,6 +26390,7 @@ function ShowExampleAppConstrainedResize(p_open) if not CR.window_padding then ImGui.PopStyleVar() end if window_open then if ImGui.GetIO().KeyShift then + -- Display a dummy viewport (in your real app you would likely use ImageButton() to display a texture) local avail_size = ImGui.GetContentRegionAvail() local pos = ImGui.GetCursorScreenPos() ImGui.ColorButton("viewport", ImVec4(0.5, 0.2, 0.5, 1.0), bit32.bor(ImGuiColorEditFlags.NoTooltip, ImGuiColorEditFlags.NoDragDrop), avail_size) @@ -23104,10 +26415,12 @@ function ShowExampleAppConstrainedResize(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a simple static window with no decoration +-- + a context-menu to choose which corner of the screen to use. local OverlayLocation = 0 function ShowExampleAppSimpleOverlay(p_open) local io = ImGui.GetIO() @@ -23116,7 +26429,7 @@ function ShowExampleAppSimpleOverlay(p_open) if OverlayLocation >= 0 then local PAD = 10.0 local viewport = ImGui.GetMainViewport() - local work_pos, work_size = viewport.WorkPos, viewport.WorkSize + local work_pos, work_size = viewport.WorkPos, viewport.WorkSize -- Use work area to avoid menu-bar/task-bar, if any! local right, bottom = OverlayLocation % 2 == 1, OverlayLocation >= 2 local window_pos = ImVec2(right and (work_pos.x + work_size.x - PAD) or (work_pos.x + PAD), bottom and (work_pos.y + work_size.y - PAD) or (work_pos.y + PAD)) local window_pos_pivot = ImVec2(right and 1.0 or 0.0, bottom and 1.0 or 0.0) @@ -23124,10 +26437,11 @@ function ShowExampleAppSimpleOverlay(p_open) ImGui.SetNextWindowViewport(viewport.ID) window_flags = bit32.bor(window_flags, W.NoMove) elseif OverlayLocation == -2 then + -- Center window ImGui.SetNextWindowPos(ImGui.GetMainViewport():GetCenter(), ImGuiCond.Always, ImVec2(0.5, 0.5)) window_flags = bit32.bor(window_flags, W.NoMove) end - ImGui.SetNextWindowBgAlpha(0.35) + ImGui.SetNextWindowBgAlpha(0.35) -- Transparent background local visible p_open, visible = ImGui.Begin("Example: Simple overlay", p_open, window_flags) if visible then @@ -23149,12 +26463,15 @@ function ShowExampleAppSimpleOverlay(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a window covering the entire screen/viewport local FS = { use_work_area = true, flags = bit32.bor(ImGuiWindowFlags.NoDecoration, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoSavedSettings) } function ShowExampleAppFullscreen(p_open) + -- We demonstrate using the full viewport area or the work area (without menu-bars, task-bars etc.) + -- Based on your use case you may want one or the other. local viewport = ImGui.GetMainViewport() ImGui.SetNextWindowPos(FS.use_work_area and viewport.WorkPos or viewport.Pos) ImGui.SetNextWindowSize(FS.use_work_area and viewport.WorkSize or viewport.Size) @@ -23178,13 +26495,21 @@ function ShowExampleAppFullscreen(p_open) return p_open end ----------------------------------------------------------------- --- [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles() +------------------------------------------------------------------------------- +-- Demonstrate the use of "##" and "###" in identifiers to manipulate ID generation. +-- This applies to all regular items as well. +-- Read FAQ section "How can I have multiple widgets with the same label?" for details. function ShowExampleAppWindowTitles(p_open) local viewport = ImGui.GetMainViewport() local base_pos = viewport.Pos + + -- By default, Windows are uniquely identified by their title. + -- You can use the "##" and "###" markers to manipulate the display/ID. + + -- Using "##" to display same title but have unique identifier. ImGui.SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 100), ImGuiCond.FirstUseEver) ImGui.Begin("Same title as another window##1") ImGui.Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique.") @@ -23193,6 +26518,8 @@ function ShowExampleAppWindowTitles(p_open) ImGui.Begin("Same title as another window##2") ImGui.Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique.") ImGui.End() + + -- Using "###" to display a changing title but keep a static identifier "AnimatedTitle" local spin = "|/-\\" local k = math.floor(ImGui.GetTime() / 0.25) % 4 + 1 local buf = string.format("Animated title %s %d###AnimatedTitle", string.sub(spin, k, k), ImGui.GetFrameCount()) @@ -23203,9 +26530,14 @@ function ShowExampleAppWindowTitles(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() ----------------------------------------------------------------- +------------------------------------------------------------------------------- + +-- See our Wiki guides: +-- - ImDrawList Vector Rendering Reference: https://github.com/ocornut/imgui/wiki/Draw-List +-- - Pixel Perfect Anti-aliased Rendering: https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering +-- - How Anti-aliased Polyline Rendering is Implemented: https://github.com/ocornut/imgui/wiki/Polyline-Rendering local CRS = { sz = 42.0, base_rounding = 8.0, base_thickness = 3.0, animate_rounding = false, animate_thickness = false, ngon_segments = 6, circle_override = false, circle_override_v = 12, curve_override = false, curve_override_v = 8, @@ -23219,6 +26551,9 @@ local function CustomRenderingPrimitives() ImGui.PushItemFlag(ImGuiItemFlags.LiveEditOnInput, true) local draw_list = ImGui.GetWindowDrawList() + -- Draw gradients + -- (note that those are currently exacerbating our sRGB/Linear issues) + -- Calling ImGui.GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well.. ImGui.Text("Gradients") local gradient_size = ImVec2(ImGui.CalcItemWidth(), ImGui.GetFrameHeight()) ImGui.InvisibleButton("##gradient1", gradient_size) @@ -23228,11 +26563,12 @@ local function CustomRenderingPrimitives() col_a, col_b = ImGui.GetColorU32(IM_COL32(0, 255, 0, 255), nil, true), ImGui.GetColorU32(IM_COL32(255, 0, 0, 255), nil, true) draw_list:AddRectFilledMultiColor(ImGui.GetItemRectMin(), ImGui.GetItemRectMax(), col_a, col_b, col_b, col_a) + -- Draw a bunch of primitives ImGui.Text("All primitives") s.sz = ImGui.DragFloat("Size", s.sz, 0.2, 0.2, 100.0, "%.0f") local t = ImGui.GetTime() local rounding_wave = 1.0 - math.abs((t % 3.0) * (2.0 / 3.0) - 1.0) - local rounding = s.animate_rounding and (math.floor(rounding_wave * s.base_rounding * 10.0) / 10.0) or s.base_rounding + local rounding = s.animate_rounding and (math.floor(rounding_wave * s.base_rounding * 10.0) / 10.0) or s.base_rounding -- Sub-integer rounding works but has discontinuities in small values, so best disable we s.base_rounding = ImGui.DragFloat("Rounding", s.base_rounding, 0.02, 0.0, 32.0, "%.1f"); ImGui.SameLine() _, s.animate_rounding = ImGui.Checkbox("Animate##rounding", s.animate_rounding); ImGui.SameLine() ImGui.Text("%.2f", rounding) @@ -23265,9 +26601,9 @@ local function CustomRenderingPrimitives() local half_sz = sz * 0.5 local circle_segments = s.circle_override and s.circle_override_v or 0 local curve_segments = s.curve_override and s.curve_override_v or 0 - local cp3 = { ImVec2(0.0, sz * 0.6), ImVec2(sz * 0.5, -sz * 0.4), ImVec2(sz, sz) } + local cp3 = { ImVec2(0.0, sz * 0.6), ImVec2(sz * 0.5, -sz * 0.4), ImVec2(sz, sz) } -- Control points for curves local cp4 = { ImVec2(0.0, 0.0), ImVec2(sz * 1.3, sz * 0.3), ImVec2(sz - sz * 1.3, sz - sz * 0.3), ImVec2(sz, sz) } - local concave_shape = { { 0.0, 0.0 }, { 0.3, 0.0 }, { 0.3, 0.7 }, { 0.7, 0.7 }, { 0.7, 0.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 0.0, 1.0 } } + local concave_shape = { { 0.0, 0.0 }, { 0.3, 0.0 }, { 0.3, 0.7 }, { 0.7, 0.7 }, { 0.7, 0.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 0.0, 1.0 } } -- |_| looking shape. Normalized. local zigzag_shape = { { 0.0, 0.0 }, { 0.9, 0.0 }, { 1.0, 0.1 }, { 1.0, 0.9 }, { 0.9, 1.0 }, { 0.3, 1.0 }, { 0.3, 0.4 }, { 0.9, 0.4 } } local rotating_square = {} for side = 0, 3 do @@ -23284,17 +26620,25 @@ local function CustomRenderingPrimitives() local draw_fill = (row == 2 or row == 3) local draw_strokes = (row == 0 or row == 1 or row == 3) if draw_fill then + -- FILLED SHAPES local col = ImGui.ColorConvertFloat4ToU32(s.colf_fill) - draw_list:AddNgonFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments); x = x + step - draw_list:AddCircleFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments); x = x + step - draw_list:AddEllipseFilled(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments); x = x + step - draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x = x + step - draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding); x = x + step - draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br); x = x + step - draw_list:AddTriangleFilled(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col); x = x + step - draw_list:AddTriangleFilled(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col); x = x + step - math.floor(sz * 0.6) + draw_list:AddNgonFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments); x = x + step -- N-gon + draw_list:AddCircleFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments); x = x + step -- Circle + draw_list:AddEllipseFilled(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments); x = x + step -- Ellipse + draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x = x + step -- Square + draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding); x = x + step -- Square with all rounded corners + draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br); x = x + step -- Square with two rounded corners + draw_list:AddTriangleFilled(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col); x = x + step -- Triangle + draw_list:AddTriangleFilled(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col); x = x + step - math.floor(sz * 0.6) -- Thin triangle + + -- Concave shape: U Shape(concave_shape, x, y); draw_list:PathFillConcave(col); x = x + step + + -- Concave shape: Zig-Zag with sharp angles Shape(zigzag_shape, x, y); draw_list:PathFillConcave(col); x = x + step + + -- Horizontal/Vertical lines + -- (here for consistency with the strokes section. AddRectFilled() is roughly close to AddLineH(), AddLineV() draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x = x + step draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x = x + step - math.floor(half_sz) if not (draw_fill and draw_strokes) then @@ -23306,10 +26650,16 @@ local function CustomRenderingPrimitives() end end x = x + step - math.floor(half_sz) + + -- Rotating square for n = 1, 4 do draw_list:PathLineTo(ImVec2(x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y)) end draw_list:PathFillConvex(col); x = x + step + + -- Path draw_list:PathArcTo(ImVec2(x + half_sz, y + half_sz), half_sz, pi * -0.5, pi * 1.1) draw_list:PathFillConvex(col); x = x + step + + -- Quadratic Bezier Curve (3 control points) draw_list:PathLineTo(ImVec2(x + cp3[1].x, y + cp3[1].y)) draw_list:PathBezierQuadraticCurveTo(ImVec2(x + cp3[2].x, y + cp3[2].y), ImVec2(x + cp3[3].x, y + cp3[3].y), curve_segments) draw_list:PathFillConvex(col); x = x + step @@ -23320,18 +26670,26 @@ local function CustomRenderingPrimitives() end if draw_fill and draw_strokes then x = start_pos.x end if draw_strokes then + -- STROKES + -- First row uses a thickness of 1.0f, second row uses the configurable thickness local col = ImGui.ColorConvertFloat4ToU32(s.colf_stroke) local th = (row == 0) and 1.0 or thickness - draw_list:AddNgon(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments, th); x = x + step - draw_list:AddCircle(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments, th); x = x + step - draw_list:AddEllipse(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments, th); x = x + step - draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0, th); x = x + step - draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th); x = x + step - draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, corners_tl_br); x = x + step - draw_list:AddTriangle(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col, th); x = x + step - draw_list:AddTriangle(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col, th); x = x + step - math.floor(sz * 0.6) + draw_list:AddNgon(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments, th); x = x + step -- N-gon + draw_list:AddCircle(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments, th); x = x + step -- Circle + draw_list:AddEllipse(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments, th); x = x + step -- Ellipse + draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0, th); x = x + step -- Square + draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th); x = x + step -- Square with all rounded corners + draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, corners_tl_br); x = x + step -- Square with two rounded corners + draw_list:AddTriangle(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col, th); x = x + step -- Triangle + draw_list:AddTriangle(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col, th); x = x + step - math.floor(sz * 0.6) -- Thin triangle + + -- Concave shape: U Shape(concave_shape, x, y); draw_list:PathStroke(col, th, ImDrawFlags.Closed); x = x + step + + -- Concave shape: Zig-Zag with sharp angles Shape(zigzag_shape, x, y); draw_list:PathStroke(col, th, ImDrawFlags.Closed); x = x + step + + -- Horizontal/Vertical/Diagonal lines local off = math.floor(sz * 0.4) draw_list:AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th) draw_list:AddLine(ImVec2(x, y + off), ImVec2(x + sz, y + off), col, th); x = x + step @@ -23342,11 +26700,19 @@ local function CustomRenderingPrimitives() draw_list:AddLine(ImVec2(x, y + sz), ImVec2(x + half_sz, y), col, th) end x = x + step - math.floor(half_sz) + + -- Rotating square for n = 1, 4 do draw_list:PathLineTo(ImVec2(x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y)) end draw_list:PathStroke(col, th, ImDrawFlags.Closed); x = x + step + + -- Path draw_list:PathArcTo(ImVec2(x + half_sz, y + half_sz), half_sz, pi * -0.5, pi * 1.1) draw_list:PathStroke(col, th); x = x + step + + -- Quadratic Bezier Curve (3 control points) draw_list:AddBezierQuadratic(ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), ImVec2(x + cp3[3].x, y + cp3[3].y), col, th, curve_segments); x = x + step + + -- Cubic Bezier Curve (4 control points) if not (draw_fill and draw_strokes) then draw_list:AddBezierCubic(ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), ImVec2(x + cp4[4].x, y + cp4[4].y), col, th, curve_segments) x = x + step @@ -23366,22 +26732,40 @@ local function CustomRenderingCanvas() _, s.opt_enable_grid = ImGui.Checkbox("Enable grid", s.opt_enable_grid) _, s.opt_enable_context_menu = ImGui.Checkbox("Enable context menu", s.opt_enable_context_menu) ImGui.Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu.") - local canvas_p0 = ImGui.GetCursorScreenPos() - local canvas_sz = ImGui.GetContentRegionAvail() + + -- Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling. + -- Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls. + -- To use a child window instead we could use, e.g: + -- ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0, 0)) -- Disable padding + -- ImGui.PushStyleColor(ImGuiCol.ChildBg, IM_COL32(50, 50, 50, 255)) -- Set a background color + -- ImGui.BeginChild("canvas", ImVec2(0.0, 0.0), ImGuiChildFlags.Borders, ImGuiWindowFlags.NoMove) + -- ImGui.PopStyleColor() + -- ImGui.PopStyleVar() + -- [...] + -- ImGui.EndChild() + + -- Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive() + local canvas_p0 = ImGui.GetCursorScreenPos() -- ImDrawList API uses screen coordinates! + local canvas_sz = ImGui.GetContentRegionAvail() -- Resize canvas to what's available if canvas_sz.x < 50.0 then canvas_sz.x = 50.0 end if canvas_sz.y < 50.0 then canvas_sz.y = 50.0 end local canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y) + + -- Draw border and background color local io = ImGui.GetIO() local draw_list = ImGui.GetWindowDrawList() draw_list:AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255)) draw_list:AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255)) + -- This will catch our interactions ImGui.InvisibleButton("canvas", canvas_sz, bit32.bor(ImGuiButtonFlags.MouseButtonLeft, ImGuiButtonFlags.MouseButtonRight)) - local is_hovered = ImGui.IsItemHovered() - local is_active = ImGui.IsItemActive() - local origin = ImVec2(canvas_p0.x + s.scrolling.x, canvas_p0.y + s.scrolling.y) + local is_hovered = ImGui.IsItemHovered() -- Hovered + local is_active = ImGui.IsItemActive() -- Held + local origin = ImVec2(canvas_p0.x + s.scrolling.x, canvas_p0.y + s.scrolling.y) -- Lock scrolled origin local mouse_pos_in_canvas = ImVec2(io.MousePos.x - origin.x, io.MousePos.y - origin.y) local points = s.points + + -- Add first and second point if is_hovered and not s.adding_line and ImGui.IsMouseClicked(ImGuiMouseButton.Left) then points[#points + 1] = ImVec2(mouse_pos_in_canvas.x, mouse_pos_in_canvas.y) points[#points + 1] = ImVec2(mouse_pos_in_canvas.x, mouse_pos_in_canvas.y) @@ -23391,11 +26775,16 @@ local function CustomRenderingCanvas() points[#points] = ImVec2(mouse_pos_in_canvas.x, mouse_pos_in_canvas.y) if not ImGui.IsMouseDown(ImGuiMouseButton.Left) then s.adding_line = false end end + + -- Pan (we use a zero mouse threshold when there's no context menu) + -- You may decide to make that threshold dynamic based on whether the mouse is hovering something etc. local mouse_threshold_for_pan = s.opt_enable_context_menu and -1.0 or 0.0 if is_active and ImGui.IsMouseDragging(ImGuiMouseButton.Right, mouse_threshold_for_pan) then s.scrolling.x = s.scrolling.x + io.MouseDelta.x s.scrolling.y = s.scrolling.y + io.MouseDelta.y end + + -- Context menu (under default mouse threshold) local drag_delta = ImGui.GetMouseDragDelta(ImGuiMouseButton.Right) if s.opt_enable_context_menu and drag_delta.x == 0.0 and drag_delta.y == 0.0 then ImGui.OpenPopupOnItemClick("context", ImGuiPopupFlags.MouseButtonRight) @@ -23407,6 +26796,8 @@ local function CustomRenderingCanvas() if ImGui.MenuItem("Remove all", nil, false, #points > 0) then table.clear(points) end ImGui.EndPopup() end + + -- Draw grid + all lines in the canvas draw_list:PushClipRect(canvas_p0, canvas_p1, true) if s.opt_enable_grid then local GRID_STEP = 64.0 @@ -23421,6 +26812,7 @@ local function CustomRenderingCanvas() draw_list:PopClipRect() end +-- Demonstrate using the low-level ImDrawList to draw custom shapes. function ShowExampleAppCustomRendering(p_open) local visible p_open, visible = ImGui.Begin("Example: Custom rendering", p_open) @@ -23440,23 +26832,33 @@ function ShowExampleAppCustomRendering(p_open) if s.draw_fg then ImGui.GetForegroundDrawList():AddCircle(window_center, window_size.y * 0.6, IM_COL32(0, 255, 0, 200), 0, 10) end ImGui.EndTabItem() end + + -- Demonstrate out-of-order rendering via channels splitting + -- We use functions in ImDrawList as each draw list contains a convenience splitter, + -- but you can also instantiate your own ImDrawListSplitter if you need to nest them. if ImGui.BeginTabItem("Draw Channels") then local draw_list = ImGui.GetWindowDrawList() ImGui.Text("Blue shape is drawn first: appears in back") ImGui.Text("Red shape is drawn after: appears in front") local p0 = ImGui.GetCursorScreenPos() - draw_list:AddRectFilled(ImVec2(p0.x, p0.y), ImVec2(p0.x + 50, p0.y + 50), IM_COL32(0, 0, 255, 255)) - draw_list:AddRectFilled(ImVec2(p0.x + 25, p0.y + 25), ImVec2(p0.x + 75, p0.y + 75), IM_COL32(255, 0, 0, 255)) + draw_list:AddRectFilled(ImVec2(p0.x, p0.y), ImVec2(p0.x + 50, p0.y + 50), IM_COL32(0, 0, 255, 255)) -- Blue + draw_list:AddRectFilled(ImVec2(p0.x + 25, p0.y + 25), ImVec2(p0.x + 75, p0.y + 75), IM_COL32(255, 0, 0, 255)) -- Red ImGui.Dummy(ImVec2(75, 75)) ImGui.Separator() ImGui.Text("Blue shape is drawn first, into channel 1: appears in front") ImGui.Text("Red shape is drawn after, into channel 0: appears in back") local p1 = ImGui.GetCursorScreenPos() + + -- Create 2 channels and draw a Blue shape THEN a Red shape. + -- You can create any number of channels. Tables API use 1 channel per column in order to better batch draw calls. draw_list:ChannelsSplit(2) draw_list:ChannelsSetCurrent(1) - draw_list:AddRectFilled(ImVec2(p1.x, p1.y), ImVec2(p1.x + 50, p1.y + 50), IM_COL32(0, 0, 255, 255)) + draw_list:AddRectFilled(ImVec2(p1.x, p1.y), ImVec2(p1.x + 50, p1.y + 50), IM_COL32(0, 0, 255, 255)) -- Blue draw_list:ChannelsSetCurrent(0) - draw_list:AddRectFilled(ImVec2(p1.x + 25, p1.y + 25), ImVec2(p1.x + 75, p1.y + 75), IM_COL32(255, 0, 0, 255)) + draw_list:AddRectFilled(ImVec2(p1.x + 25, p1.y + 25), ImVec2(p1.x + 75, p1.y + 75), IM_COL32(255, 0, 0, 255)) -- Red + + -- Flatten/reorder channels. Red shape is in channel 0 and it appears below the Blue shape in channel 1. + -- This works by copying draw indices only (vertices are not copied). draw_list:ChannelsMerge() ImGui.Dummy(ImVec2(75, 75)) ImGui.Text("After reordering, contents of channel 0 appears below channel 1.") @@ -23468,17 +26870,35 @@ function ShowExampleAppCustomRendering(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- KeepWindowPadding: Keep WindowPadding to help understand that DockSpace() is a widget inside the window. local DSA = { IsFullscreen = true, KeepWindowPadding = false, DockSpaceFlags = 0, opt_demo_mode = 0, opt_demo_mode_changed = false } +-- THIS IS A DEMO FOR ADVANCED USAGE OF DockSpace(). +-- MOST REGULAR APPLICATIONS WANTING TO ALLOW DOCKING WINDOWS ON THE EDGE OF YOUR SCREEN CAN SIMPLY USE: +-- ImGui.NewFrame() + ImGui.DockSpaceOverViewport() -- Create a dockspace in main viewport +-- OR: +-- ImGui.NewFrame() + ImGui.DockSpaceOverViewport(0, nil, ImGuiDockNodeFlags.PassthruCentralNode) -- Create a dockspace in main viewport, where central node is transparent. +-- Demonstrate using DockSpace() to create an explicit docking node within an existing window, with various options. +-- Read https://github.com/ocornut/imgui/wiki/Docking for details. +-- The reasons we do not use DockSpaceOverViewport() in this demo is because: +-- - (1) we allow the host window to be floating/moveable instead of filling the viewport (when args.IsFullscreen == false) +-- which is mostly to showcase the idea that DockSpace() may be submitted anywhere. +-- Also see 'Demo->Examples->Documents' for a less abstract version of this. +-- - (2) we allow the host window to have padding (when args.UsePadding == true) +-- - (3) we expose variety of other flags. local function ShowExampleAppDockSpaceAdvanced(args, p_open) local dockspace_flags = args.DockSpaceFlags + + -- We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, + -- because it would be confusing to have two docking targets within each others. local W = ImGuiWindowFlags local window_flags = W.NoDocking if args.IsFullscreen then + -- Fullscreen dockspace: practically the same as calling DockSpaceOverViewport() local viewport = ImGui.GetMainViewport() ImGui.SetNextWindowPos(viewport.WorkPos) ImGui.SetNextWindowSize(viewport.WorkSize) @@ -23487,12 +26907,24 @@ local function ShowExampleAppDockSpaceAdvanced(args, p_open) ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0.0) window_flags = bit32.bor(window_flags, W.NoTitleBar, W.NoCollapse, W.NoResize, W.NoMove, W.NoBringToFrontOnFocus, W.NoNavFocus, W.NoBackground) else + -- Floating dockspace dockspace_flags = bit32.band(dockspace_flags, bit32.bnot(ImGuiDockNodeFlags.PassthruCentralNode)) end + + -- Important: note that we proceed even if Begin() returns false (aka window is collapsed). + -- This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, + -- all active windows docked into it will lose their parent and become undocked. + -- We cannot preserve the docking relationship between an active window and an inactive docking, otherwise + -- any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. if not args.KeepWindowPadding then ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0.0, 0.0)) end p_open = ImGui.Begin("Window with a DockSpace", p_open, window_flags) if not args.KeepWindowPadding then ImGui.PopStyleVar() end + if args.IsFullscreen then ImGui.PopStyleVar(2) end + + -- Submit the DockSpace widget inside our window + -- - Note that the id here is different from the one used by DockSpaceOverViewport(), so docking state won't get transfered between "Basic" and "Advanced" demos. + -- - If we made the ShowExampleAppDockSpaceBasic() calculate its own ID and pass it to DockSpaceOverViewport() the ID could easily match. local dockspace_id = ImGui.GetID("MyDockSpace") ImGui.DockSpace(dockspace_id, ImVec2(0.0, 0.0), dockspace_flags) ImGui.End() @@ -23502,10 +26934,20 @@ end function ShowExampleAppDockSpace(p_open) local args = DSA if args.opt_demo_mode == 0 then + -- Basic version which you can use in many apps: + -- e.g: + -- ImGui.DockSpaceOverViewport() + -- or: + -- ImGui.DockSpaceOverViewport(0, nil, ImGuiDockNodeFlags.PassthruCentralNode) -- Central node will be transparent + -- or: + -- local viewport = ImGui.GetMainViewport() + -- ImGui.DockSpaceOverViewport(0, viewport, ImGuiDockNodeFlags.None) ImGui.DockSpaceOverViewport(0, nil, args.DockSpaceFlags) else p_open = ShowExampleAppDockSpaceAdvanced(args, p_open) end + + -- Refocus our window to minimize perceived loss of focus when changing mode (caused by the fact that each use a different window, which would not happen in a real app) if args.opt_demo_mode_changed then ImGui.SetNextWindowFocus() end p_open = ImGui.Begin("Examples: Dockspace", p_open, ImGuiWindowFlags.MenuBar) local c1, c2 @@ -23517,7 +26959,7 @@ function ShowExampleAppDockSpace(p_open) if bit32.band(ImGui.GetIO().ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then ShowDockingDisabledMessage() elseif args.opt_demo_mode == 0 then - args.DockSpaceFlags = bit32.band(args.DockSpaceFlags, D.PassthruCentralNode) + args.DockSpaceFlags = bit32.band(args.DockSpaceFlags, D.PassthruCentralNode) -- Allowed flags _, args.DockSpaceFlags = ImGui.CheckboxFlags("Flag: PassthruCentralNode", args.DockSpaceFlags, D.PassthruCentralNode) else _, args.IsFullscreen = ImGui.Checkbox("Fullscreen", args.IsFullscreen) @@ -23531,6 +26973,8 @@ function ShowExampleAppDockSpace(p_open) if D[n] then _, args.DockSpaceFlags = ImGui.CheckboxFlags("Flag: " .. n, args.DockSpaceFlags, D[n]) end end end + + -- Show demo options and help if ImGui.BeginMenuBar() then if ImGui.BeginMenu("Help") then ImGui.TextUnformatted("This demonstrates the use of ImGui::DockSpace() which allows you to manually\ncreate a docking node _within_ another window.\nThe \"Basic\" version uses the ImGui::DockSpaceOverViewport() helper. Most applications can probably use this.") @@ -23547,10 +26991,17 @@ function ShowExampleAppDockSpace(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Simplified structure to mimic a Document model +-- NameBuf: Document title +-- UID: Unique ID (necessary as we can change title) +-- Open: Set when open (we keep an array of all available documents to simplify demo code!) +-- OpenPrev: Copy of Open from last update. +-- Dirty: Set when the document has been modified +-- Color: An arbitrary variable associated to the document local function MyDocument(uid, name, open, color) if open == nil then open = true end local d = { UID = uid, NameBuf = Buf(name, 32), Open = open, OpenPrev = open, Dirty = false, Color = color or ImVec4(1.0, 1.0, 1.0, 1.0) } @@ -23576,13 +27027,16 @@ local function DocsInit() for _, d in ipairs(self.CloseQueue) do if d == doc then return end end self.CloseQueue[#self.CloseQueue + 1] = doc end + -- As we allow to change document name, we append a never-changing document ID so tabs are stable function app:GetTabName(doc) return string.format("%s###doc%d", doc:Name(), doc.UID) end + -- Display placeholder contents for the Document function app:DisplayDocContents(doc) ImGui.PushID("doc" .. doc.UID) ImGui.Text("Document \"%s\"", doc:Name()) ImGui.PushStyleColor(ImGuiCol.Text, doc.Color) ImGui.TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.") ImGui.PopStyleColor() + ImGui.SetNextItemShortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.R), ImGuiInputFlags.Tooltip) if ImGui.Button("Rename..") then self.RenamingDoc = doc; self.RenamingStarted = true end ImGui.SameLine() @@ -23594,9 +27048,10 @@ local function DocsInit() ImGui.SameLine() ImGui.SetNextItemShortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.W), ImGuiInputFlags.Tooltip) if ImGui.Button("Close") then self:QueueClose(doc) end - ImGui.ColorEdit3("color", doc.Color) + ImGui.ColorEdit3("color", doc.Color) -- Useful to test drag and drop and hold-dragged-to-open-tab behavior. ImGui.PopID() end + -- Display context menu for the Document function app:DisplayDocContextMenu(doc) if not ImGui.BeginPopupContextItem() then return end if ImGui.MenuItem("Save " .. doc:Name(), "Ctrl+S", false, doc.Open) then doc:DoSave() end @@ -23604,6 +27059,14 @@ local function DocsInit() if ImGui.MenuItem("Close", "Ctrl+W", false, doc.Open) then self:QueueClose(doc) end ImGui.EndPopup() end + -- [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface. + -- If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, + -- as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for + -- the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has + -- disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively + -- give the impression of a flicker for one frame. + -- We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch. + -- Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags.Reorderable flag. function app:NotifyOfDocumentsClosedElsewhere() for _, doc in ipairs(self.Documents) do if not doc.Open and doc.OpenPrev then ImGui.SetTabItemClosed(doc:Name()) end @@ -23616,7 +27079,18 @@ end function ShowExampleAppDocuments(p_open) Docs = Docs or DocsInit() local app = Docs + -- Options + -- Target_Tab: Create documents as local tab into a local tab bar + -- Target_DockSpaceAndWindow: Create documents as regular windows, and create an embedded dockspace local Target_Tab, Target_DockSpaceAndWindow = 1, 2 + + -- When (opt_target == Target_DockSpaceAndWindow) there is the possibily that one of our child Document window (e.g. "Eggplant") + -- that we emit gets docked into the same spot as the parent window ("Example: Documents"). + -- This would create a problematic feedback loop because selecting the "Eggplant" tab would make the "Example: Documents" tab + -- not visible, which in turn would stop submitting the "Eggplant" window. + -- We avoid this problem by submitting our documents window even if our parent window is not currently visible. + -- Another solution may be to make the "Example: Documents" window use the ImGuiWindowFlags.NoDocking. + local window_contents_visible p_open, window_contents_visible = ImGui.Begin("Example: Documents", p_open, ImGuiWindowFlags.MenuBar) if not window_contents_visible and app.opt_target ~= Target_DockSpaceAndWindow then @@ -23624,6 +27098,7 @@ function ShowExampleAppDocuments(p_open) return p_open end + -- Menu if ImGui.BeginMenuBar() then if ImGui.BeginMenu("File") then local open_count = 0 @@ -23643,6 +27118,7 @@ function ShowExampleAppDocuments(p_open) ImGui.EndMenuBar() end + -- [Debug] List documents with one checkbox for each for doc_n, doc in ipairs(app.Documents) do if doc_n > 1 then ImGui.SameLine() end ImGui.PushID("doc" .. doc.UID) @@ -23659,15 +27135,31 @@ function ShowExampleAppDocuments(p_open) if app.opt_target == Target_DockSpaceAndWindow then ImGui.SameLine(); redock_all = ImGui.Button("Redock all") end ImGui.Separator() + -- About the ImGuiWindowFlags.UnsavedDocument / ImGuiTabItemFlags.UnsavedDocument flags. + -- They have multiple effects: + -- - Display a dot next to the title. + -- - Tab is selected when clicking the X close button. + -- - Closure is not assumed (will wait for user to stop submitting the tab). + -- Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + -- We need to assume closure by default otherwise waiting for "lack of submission" on the next frame would leave an empty + -- hole for one-frame, both in the tab-bar and in tab-contents when closing a tab/window. + -- The rarely used SetTabItemClosed() function is a way to notify of programmatic closure to avoid the one-frame hole. + + -- Tabs if app.opt_target == Target_Tab then local tab_bar_flags = bit32.bor(app.opt_fitting_flags, app.opt_reorderable and ImGuiTabBarFlags.Reorderable or 0, ImGuiTabBarFlags.DrawSelectedOverline) if ImGui.BeginTabBar("##tabs", tab_bar_flags) then if app.opt_reorderable then app:NotifyOfDocumentsClosedElsewhere() end + + -- Submit Tabs for _, doc in ipairs(app.Documents) do if doc.Open then + -- As we allow to change document name, we append a never-changing document id so tabs are stable local tab_flags = doc.Dirty and ImGuiTabItemFlags.UnsavedDocument or 0 local visible visible, doc.Open = ImGui.BeginTabItem(app:GetTabName(doc), doc.Open, tab_flags) + + -- Cancel attempt to close when unsaved add to save queue so we can display a popup. if not doc.Open and doc.Dirty then doc.Open = true app:QueueClose(doc) @@ -23684,14 +27176,20 @@ function ShowExampleAppDocuments(p_open) elseif app.opt_target == Target_DockSpaceAndWindow then if bit32.band(ImGui.GetIO().ConfigFlags, ImGuiConfigFlags.DockingEnable) ~= 0 then app:NotifyOfDocumentsClosedElsewhere() + + -- Create a DockSpace node where any window can be docked local dockspace_id = ImGui.GetID("MyDockSpace") ImGui.DockSpace(dockspace_id) + + -- Create Windows for _, doc in ipairs(app.Documents) do if doc.Open then ImGui.SetNextWindowDockID(dockspace_id, redock_all and ImGuiCond.Always or ImGuiCond.FirstUseEver) local window_flags = doc.Dirty and ImGuiWindowFlags.UnsavedDocument or 0 local visible doc.Open, visible = ImGui.Begin(doc:Name(), doc.Open, window_flags) + + -- Cancel attempt to close when unsaved add to save queue so we can display a popup. if not doc.Open and doc.Dirty then doc.Open = true app:QueueClose(doc) @@ -23706,11 +27204,13 @@ function ShowExampleAppDocuments(p_open) end end + -- Early out other contents if not window_contents_visible then ImGui.End() return p_open end + -- Display renaming UI if app.RenamingDoc ~= nil then if app.RenamingStarted then ImGui.OpenPopup("Rename") end if ImGui.BeginPopup("Rename") then @@ -23727,10 +27227,12 @@ function ShowExampleAppDocuments(p_open) app.RenamingStarted = false end + -- Display closing confirmation UI if #app.CloseQueue > 0 then local close_queue_unsaved_documents = 0 for _, doc in ipairs(app.CloseQueue) do if doc.Dirty then close_queue_unsaved_documents = close_queue_unsaved_documents + 1 end end if close_queue_unsaved_documents == 0 then + -- Close documents when all are unsaved for _, doc in ipairs(app.CloseQueue) do doc:DoForceClose() end app.CloseQueue = {} else @@ -23783,6 +27285,10 @@ local ExampleNames = { "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" } +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsBasic() +------------------------------------------------------------------------------- + S.basic = { clicked = 0, check = true, e = 0, counter = 0, str0 = Buf("Hello, world!", 128), str1 = Buf("", 128), i0 = 123, f0 = 0.001, d0 = 999999.00000001, f1 = 1.e10, vec4a = { 0.10, 0.20, 0.30, 0.44 }, di1 = 50, di2 = 42, di3 = 128, df1 = 1.0, df2 = 0.0067, si1 = 0, sf1 = 0.123, sf2 = 0.0, angle = 0.0, elem = 0, @@ -23800,6 +27306,8 @@ function DemoWindowWidgetsBasic() _, s.e = ImGui.RadioButton("radio c", s.e, 2) ImGui.AlignTextToFramePadding() ImGui.TextLinkOpenURL("Hyperlink", "https://github.com/ocornut/imgui/wiki/Error-Handling") + + -- Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. for i = 0, 6 do if i > 0 then ImGui.SameLine() end ImGui.PushID(i) @@ -23810,9 +27318,15 @@ function DemoWindowWidgetsBasic() ImGui.PopStyleColor(3) ImGui.PopID() end + + -- Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements + -- (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!) + -- See 'Demo->Layout->Text Baseline Alignment' for details. ImGui.AlignTextToFramePadding() ImGui.Text("Hold to repeat:") ImGui.SameLine() + + -- Arrow buttons with Repeater local spacing = ImGui.GetStyle().ItemInnerSpacing.x ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true) if ImGui.ArrowButton("##left", ImGuiDir.Left) then s.counter = s.counter - 1 end @@ -23843,6 +27357,7 @@ function DemoWindowWidgetsBasic() s.di3 = ImGui.DragInt("drag int wrap 100..200", s.di3, 1, 100, 200, "%d", ImGuiSliderFlags.WrapAround) s.df1 = ImGui.DragFloat("drag float", s.df1, 0.005) s.df2 = ImGui.DragFloat("drag small float", s.df2, 0.0001, 0.0, 0.0, "%.06f ns") + -- ImGui.DragFloat("drag wrap -1..1", f3, 0.005, -1.0, 1.0, nil, ImGuiSliderFlags.WrapAround) ImGui.SeparatorText("Sliders") s.si1 = ImGui.SliderInt("slider int", s.si1, -1, 3) @@ -23850,23 +27365,38 @@ function DemoWindowWidgetsBasic() s.sf1 = ImGui.SliderFloat("slider float", s.sf1, 0.0, 1.0, "ratio = %.3f") s.sf2 = ImGui.SliderFloat("slider float (log)", s.sf2, -10.0, 10.0, "%.4f", ImGuiSliderFlags.Logarithmic) s.angle = ImGui.SliderAngle("slider angle", s.angle) + + -- Using the format string to display a name instead of an integer. + -- Here we completely omit '%d' from the format string, so it'll only display a name. + -- This technique can also be used with DragInt(). local elems_names = { "Fire", "Earth", "Air", "Water" } local elem_name = elems_names[s.elem + 1] or "Unknown" - s.elem = ImGui.SliderInt("slider enum", s.elem, 0, 3, elem_name) + s.elem = ImGui.SliderInt("slider enum", s.elem, 0, 3, elem_name) -- Use ImGuiSliderFlags.NoInput flag to disable Ctrl+Click here. ImGui.SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer.") ImGui.SeparatorText("Selectors/Pickers") ImGui.ColorEdit3("color 1", s.col1) ImGui.SameLine(); HelpMarker("Click on the color square to open a color picker.\nClick and hold to use drag and drop.\nRight-Click on the color square to show options.\nCtrl+Click on individual component to input value.\n") ImGui.ColorEdit4("color 2", s.col2) + + -- Using the _simplified_ one-liner Combo() api here + -- See "Combo" section for examples of how to use the more flexible BeginCombo()/EndCombo() api. s.combo = ImGui.Combo("combo", s.combo, { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }) ImGui.SameLine(); HelpMarker("Using the simplified one-liner Combo API here.") + + -- Using the _simplified_ one-liner ListBox() api here + -- See "List boxes" section for examples of how to use the more flexible BeginListBox()/EndListBox() api. s.listbox = ImGui.ListBox("listbox", s.listbox, { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }, 9, 4) ImGui.SameLine(); HelpMarker("Using the simplified one-liner ListBox API here.") ImGui.TreePop() end S.chdr = { closable_group = true } + +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsBullets() +------------------------------------------------------------------------------- + function DemoWindowWidgetsBullets() if not ImGui.TreeNode("Bullets") then return end ImGui.BulletText("Bullet point 1") @@ -23877,6 +27407,10 @@ function DemoWindowWidgetsBullets() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsCollapsingHeaders() +------------------------------------------------------------------------------- + function DemoWindowWidgetsCollapsingHeaders() if not ImGui.TreeNode("Collapsing Headers") then return end local s = S.chdr @@ -23891,9 +27425,16 @@ function DemoWindowWidgetsCollapsingHeaders() ImGui.Text("IsItemHovered: %d", ImGui.IsItemHovered() and 1 or 0) for i = 0, 4 do ImGui.Text("More content %d", i) end end + -- if ImGui.CollapsingHeader("Header with a bullet", ImGuiTreeNodeFlags.Bullet) then + -- ImGui.Text("IsItemHovered: %d", ImGui.IsItemHovered()) + -- end ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsColorAndPickers() +------------------------------------------------------------------------------- + IMGUI_PAYLOAD_TYPE_COLOR_3F = IMGUI_PAYLOAD_TYPE_COLOR_3F or "_COL3F" IMGUI_PAYLOAD_TYPE_COLOR_4F = IMGUI_PAYLOAD_TYPE_COLOR_4F or "_COL4F" @@ -23931,9 +27472,11 @@ function DemoWindowWidgetsColorAndPickers() ImGui.ColorEdit4("MyColor##3", color, bit32.bor(CE.NoInputs, CE.NoLabel, base_flags)) ImGui.Text("Color button with Custom Picker Popup:") + + -- Generate a default palette. The palette will persist and can be edited. if s.palette == nil then s.palette = {} - for n = 0, 31 do s.palette[n] = HSV(n / 31.0, 0.8, 0.8, 1.0) end + for n = 0, 31 do s.palette[n] = HSV(n / 31.0, 0.8, 0.8, 1.0) end -- Alpha = 1.0 end local open_popup = ImGui.ColorButton("MyColor##3b", color, base_flags) ImGui.SameLine(0, ImGui.GetStyle().ItemInnerSpacing.x) @@ -23947,7 +27490,7 @@ function DemoWindowWidgetsColorAndPickers() ImGui.Separator() ImGui.ColorPicker4("##picker", color, bit32.bor(base_flags, CE.NoSidePreview, CE.NoSmallPreview)) ImGui.SameLine() - ImGui.BeginGroup() + ImGui.BeginGroup() -- Lock X position ImGui.Text("Current") ImGui.ColorButton("##current", color, bit32.bor(CE.NoPicker, CE.AlphaPreviewHalf), ImVec2(60, 40)) ImGui.Text("Previous") @@ -23963,6 +27506,9 @@ function DemoWindowWidgetsColorAndPickers() if ImGui.ColorButton("##palette", pal, bit32.bor(CE.NoAlpha, CE.NoPicker, CE.NoTooltip), ImVec2(20, 20)) then color.x = pal.x; color.y = pal.y; color.z = pal.z -- Preserve alpha! end + + -- Allow user to drop colors into each palette entry. Note that ColorButton() is already a + -- drag source by default, unless specifying the ImGuiColorEditFlags.NoDragDrop flag. if ImGui.BeginDragDropTarget() then local payload = ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F) if payload and payload.Data then pal.x, pal.y, pal.z = payload.Data[1], payload.Data[2], payload.Data[3] end @@ -24001,8 +27547,8 @@ function DemoWindowWidgetsColorAndPickers() local flags = bit32.bor(base_flags, s.picker_flags) if s.picker_mode == 1 then flags = bit32.bor(flags, CE.PickerHueBar) end if s.picker_mode == 2 then flags = bit32.bor(flags, CE.PickerHueWheel) end - if s.display_mode == 1 then flags = bit32.bor(flags, CE.NoInputs) end - if s.display_mode == 2 then flags = bit32.bor(flags, CE.DisplayRGB) end + if s.display_mode == 1 then flags = bit32.bor(flags, CE.NoInputs) end -- Disable all RGB/HSV/Hex displays + if s.display_mode == 2 then flags = bit32.bor(flags, CE.DisplayRGB) end -- Override display mode if s.display_mode == 3 then flags = bit32.bor(flags, CE.DisplayHSV) end if s.display_mode == 4 then flags = bit32.bor(flags, CE.DisplayHex) end ImGui.ColorPicker4("MyColor##4", color, flags, s.ref_color and s.ref_color_v or nil) @@ -24016,6 +27562,8 @@ function DemoWindowWidgetsColorAndPickers() ImGui.GetIO().ConfigColorEditFlags = bit32.bor(CE.Float, CE.HDR, CE.PickerHueWheel, CE.DisplayRGB, CE.InputRGB) end + -- Always display a small version of both types of pickers + -- (that's in order to make it more visible in the demo to people who are skimming quickly through it) ImGui.Text("Both types:") local w = (ImGui.GetContentRegionAvail().x - ImGui.GetStyle().ItemSpacing.y) * 0.40 ImGui.SetNextItemWidth(w) @@ -24025,6 +27573,8 @@ function DemoWindowWidgetsColorAndPickers() ImGui.ColorPicker3("##MyColor##6", color, bit32.bor(CE.PickerHueWheel, CE.NoSidePreview, CE.NoInputs, CE.NoAlpha)) ImGui.PopID() + -- HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0) + -- (s.hsv is stored as HSV!) ImGui.Spacing() ImGui.Text("HSV encoded colors") ImGui.SameLine(); HelpMarker("By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV.") @@ -24035,36 +27585,53 @@ function DemoWindowWidgetsColorAndPickers() ImGui.TreePop() end -S.combo = { flags = 0, sel = 0, filter = nil, c2 = 0, c3 = -1, c4 = 0 } +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsComboBoxes() +------------------------------------------------------------------------------- + +S.combo = { flags = 0, sel = 0, filter = nil, c2 = 0, c3 = -1, c4 = 0 } -- sel: Here we store our selection data as an index. function DemoWindowWidgetsComboBoxes() if not ImGui.TreeNode("Combo") then return end local s = S.combo local CF = ImGuiComboFlags local p + -- Combo Boxes are also called "Dropdown" in other systems + -- Expose flags as checkbox for the demo _, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", s.flags, CF.PopupAlignLeft) ImGui.SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo") p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_NoArrowButton", s.flags, CF.NoArrowButton) - if p then s.flags = bit32.band(s.flags, bit32.bnot(CF.NoPreview)) end + if p then s.flags = bit32.band(s.flags, bit32.bnot(CF.NoPreview)) end -- Clear incompatible flags p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_NoPreview", s.flags, CF.NoPreview) - if p then s.flags = bit32.band(s.flags, bit32.bnot(bit32.bor(CF.NoArrowButton, CF.WidthFitPreview))) end + if p then s.flags = bit32.band(s.flags, bit32.bnot(bit32.bor(CF.NoArrowButton, CF.WidthFitPreview))) end -- Clear incompatible flags p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_WidthFitPreview", s.flags, CF.WidthFitPreview) if p then s.flags = bit32.band(s.flags, bit32.bnot(CF.NoPreview)) end + + -- Override default popup height for _, h in ipairs({ "HeightSmall", "HeightRegular", "HeightLargest" }) do p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_" .. h, s.flags, CF[h]) if p then s.flags = bit32.band(s.flags, bit32.bnot(bit32.band(CF.HeightMask_, bit32.bnot(CF[h])))) end end + -- Using the generic BeginCombo() API, you have full control over how to display the combo contents. + -- (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + -- stored in the object itself, etc.) local items = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" } + + -- Pass in the preview value visible before opening the combo (it could technically be different contents or not pulled from items[]) local combo_preview_value = items[s.sel + 1] if ImGui.BeginCombo("combo 1", combo_preview_value, s.flags) then for n = 0, #items - 1 do local is_selected = (s.sel == n) if ImGui.Selectable(items[n + 1], is_selected) then s.sel = n end + + -- Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if is_selected then ImGui.SetItemDefaultFocus() end end ImGui.EndCombo() end + -- Show case embedding a filter using a simple trick: displaying the filter inside combo contents. + -- See https://github.com/ocornut/imgui/issues/718 for advanced/esoteric alternatives. if ImGui.BeginCombo("combo 2 (w/ filter)", combo_preview_value, s.flags) then s.filter = s.filter or ImGuiTextFilter() if ImGui.IsWindowAppearing() then @@ -24086,19 +27653,46 @@ function DemoWindowWidgetsComboBoxes() ImGui.Spacing() ImGui.SeparatorText("One-liner variants") HelpMarker("The Combo() function is not greatly useful apart from cases were you want to embed all options in a single strings.\nFlags above don't apply to this section.") + + -- Simplified one-liner Combo() API, using values packed in a single constant string + -- This is a convenience for when the selection set is small and known at compile-time. s.c2 = ImGui.Combo("combo 3 (one-liner)", s.c2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0") - s.c3 = ImGui.Combo("combo 4 (array)", s.c3, items, #items) + + -- Simplified one-liner Combo() using an array of strings + -- This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control. + s.c3 = ImGui.Combo("combo 4 (array)", s.c3, items, #items) -- If the selection isn't within 0..count, Combo won't display a preview + + -- Simplified one-liner Combo() using an accessor function s.c4 = ImGui.Combo("combo 5 (function)", s.c4, function(data, n) return data[n + 1] end, items, #items) ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDataTypes() +------------------------------------------------------------------------------- + S.dt = { s8 = 127, u8 = 255, s16 = 32767, u16 = 65535, s32 = -1, u32 = 0xFFFFFFFF, s64 = -1, u64 = 0, f32 = 0.123, f64 = 90000.01234567890123456789, drag_clamp = false, inputs_step = true, flags = 0 } function DemoWindowWidgetsDataTypes() if not ImGui.TreeNode("Data Types") then return end local s = S.dt local DT = ImGuiDataType + -- DragScalar/InputScalar/SliderScalar functions allow various data types + -- - signed/unsigned + -- - 8/16/32/64-bits + -- - integer/float/double + -- To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum + -- to pass the type. + -- In practice, if you frequently use a given type that is not covered by the normal API entry points, + -- you can wrap it yourself inside a 1 line function which can take typed argument as value, + -- and then pass them to the generic function. For example: + -- local function MySliderU32(label, value, min, max, format) + -- return ImGui.SliderScalar(label, ImGuiDataType.U32, value, min or 0, max or 0, format or "%u") + -- end + -- ponytail: Luau numbers are doubles, so S64/U64 are shown with S32/Double here (no 64-bit integer type) + -- Setup limits + -- Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2. local s32_min, s32_max = math.floor(-2147483648 / 2), math.floor(2147483647 / 2) local u32_max = math.floor(4294967295 / 2) local drag_speed = 0.2 @@ -24162,6 +27756,10 @@ function DemoWindowWidgetsDataTypes() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDisableBlocks() +------------------------------------------------------------------------------- + function DemoWindowWidgetsDisableBlocks(demo_data) if not ImGui.TreeNode("Disable Blocks") then return end _, demo_data.DisableSections = ImGui.Checkbox("Disable entire section above", demo_data.DisableSections) @@ -24169,6 +27767,10 @@ function DemoWindowWidgetsDisableBlocks(demo_data) ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDragAndDrop() +------------------------------------------------------------------------------- + S.dnd = { col1 = { 1.0, 0.0, 0.2 }, col2 = { 0.4, 0.7, 0.0, 0.5 }, mode = 0, names = { "Bobby", "Beatrice", "Betty", "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" }, item_names = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" }, col4 = ImVec4(1.0, 0.0, 0.2, 1.0) } @@ -24176,6 +27778,10 @@ function DemoWindowWidgetsDragAndDrop() if not ImGui.TreeNode("Drag and Drop") then return end local s = S.dnd if ImGui.TreeNode("Drag and drop in standard widgets") then + -- ColorEdit widgets automatically act as drag source and drag target. + -- They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F + -- to allow your own widgets to use colors in their drag and drop interaction. + -- Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo. HelpMarker("You can drag from the color squares.") ImGui.ColorEdit3("color 1", s.col1) ImGui.ColorEdit4("color 2", s.col2) @@ -24192,8 +27798,14 @@ function DemoWindowWidgetsDragAndDrop() ImGui.PushID(n) if n % 3 ~= 0 then ImGui.SameLine() end ImGui.Button(names[n + 1], ImVec2(60, 60)) + + -- Our buttons are both drag sources and drag targets here! if ImGui.BeginDragDropSource(ImGuiDragDropFlags.None) then + -- Set payload to carry the index of our item (could be anything) ImGui.SetDragDropPayload("DND_DEMO_CELL", n, 4) + + -- Display preview (could be anything, e.g. when dragging an image we could decide to display + -- the filename and a small preview of the image, etc.) if s.mode == Mode_Copy then ImGui.Text("Copy %s", names[n + 1]) end if s.mode == Mode_Move then ImGui.Text("Move %s", names[n + 1]) end if s.mode == Mode_Swap then ImGui.Text("Swap %s", names[n + 1]) end @@ -24215,7 +27827,12 @@ function DemoWindowWidgetsDragAndDrop() end if ImGui.TreeNode("Drag to reorder items (simple)") then + -- FIXME: there is temporary (usually single-frame) ID Conflict during reordering as a same item may be submitting twice. + -- This code was always slightly faulty but in a way which was not easily noticeable. + -- Until we fix this, enable ImGuiItemFlags.AllowDuplicateId to disable detecting the issue. ImGui.PushItemFlag(ImGuiItemFlags.AllowDuplicateId, true) + + -- Simple reordering HelpMarker("We don't use the drag and drop api at all here! Instead we query when the item is held but not hovered, and order items accordingly.") local item_names = s.item_names for n = 1, #item_names do @@ -24236,6 +27853,7 @@ function DemoWindowWidgetsDragAndDrop() if ImGui.TreeNode("Tooltip at target location") then for n = 0, 1 do + -- Drop targets ImGui.Button((n == 1) and "drop here##1" or "drop here##0") if ImGui.BeginDragDropTarget() then local drop_target_flags = bit32.bor(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoPreviewTooltip) @@ -24245,6 +27863,8 @@ function DemoWindowWidgetsDragAndDrop() end ImGui.EndDragDropTarget() end + + -- Drop source if n == 0 then ImGui.ColorButton("drag me", s.col4) end end ImGui.TreePop() @@ -24252,9 +27872,14 @@ function DemoWindowWidgetsDragAndDrop() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDragsAndSliders() +------------------------------------------------------------------------------- + S.ds = { flags = 0, drag_f = 0.5, drag_f4 = { 0, 0, 0, 0 }, drag_i = 50, slider_f = 0.5, slider_f4 = { 0, 0, 0, 0 }, slider_i = 50 } function DemoWindowWidgetsDragsAndSliders() if not ImGui.TreeNode("Drag/Slider Flags") then return end + -- Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! local s = S.ds local SF = ImGuiSliderFlags local function F(name, help) @@ -24273,45 +27898,70 @@ function DemoWindowWidgetsDragsAndSliders() F("ColorMarkers") local flags = s.flags + -- Drags ImGui.Text("Underlying float value: %f", s.drag_f) s.drag_f = ImGui.DragFloat("DragFloat (0 -> 1)", s.drag_f, 0.005, 0.0, 1.0, "%.3f", flags) s.drag_f = ImGui.DragFloat("DragFloat (0 -> +inf)", s.drag_f, 0.005, 0.0, FLT_MAX, "%.3f", flags) s.drag_f = ImGui.DragFloat("DragFloat (-inf -> 1)", s.drag_f, 0.005, -FLT_MAX, 1.0, "%.3f", flags) s.drag_f = ImGui.DragFloat("DragFloat (-inf -> +inf)", s.drag_f, 0.005, -FLT_MAX, FLT_MAX, "%.3f", flags) + -- ImGui.DragFloat("DragFloat (0 -> 0)", drag_f, 0.005, 0.0, 0.0, "%.3f", flags) -- To test ClampZeroRange + -- ImGui.DragFloat("DragFloat (100 -> 100)", drag_f, 0.005, 100.0, 100.0, "%.3f", flags) s.drag_i = ImGui.DragInt("DragInt (0 -> 100)", s.drag_i, 0.5, 0, 100, "%d", flags) - ImGui.DragFloat4("DragFloat4 (0 -> 1)", s.drag_f4, 0.005, 0.0, 1.0, "%.3f", flags) + ImGui.DragFloat4("DragFloat4 (0 -> 1)", s.drag_f4, 0.005, 0.0, 1.0, "%.3f", flags) -- Multi-component item, mostly here to document the effect of ImGuiSliderFlags.ColorMarkers. + -- Sliders local flags_for_sliders = bit32.band(flags, bit32.bnot(SF.WrapAround)) ImGui.Text("Underlying float value: %f", s.slider_f) s.slider_f = ImGui.SliderFloat("SliderFloat (0 -> 1)", s.slider_f, 0.0, 1.0, "%.3f", flags_for_sliders) s.slider_i = ImGui.SliderInt("SliderInt (0 -> 100)", s.slider_i, 0, 100, "%d", flags_for_sliders) - ImGui.SliderFloat4("SliderFloat4 (0 -> 1)", s.slider_f4, 0.0, 1.0, "%.3f", flags_for_sliders) + ImGui.SliderFloat4("SliderFloat4 (0 -> 1)", s.slider_f4, 0.0, 1.0, "%.3f", flags_for_sliders) -- Multi-component item, mostly here to document the effect of ImGuiSliderFlags.ColorMarkers. ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsFonts() +------------------------------------------------------------------------------- + function DemoWindowWidgetsFonts() if not ImGui.TreeNode("Fonts") then return end if ImGui.ShowFontAtlas then ImGui.ShowFontAtlas(ImGui.GetIO().Fonts) else DemoNotPorted("ShowFontAtlas") end + -- FIXME-NEWATLAS: Provide a demo to add/create a procedural font? ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsImages() +------------------------------------------------------------------------------- + S.img = { viewer = nil, pressed_count = 0 } function DemoWindowWidgetsImages() if not ImGui.TreeNode("Images") then return end local s = S.img local io = ImGui.GetIO() ImGui.TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!") + + -- Below we are displaying the font texture because it is the only texture we have access to inside the demo! + -- Read description about ImTextureID/ImTextureRef and FAQ for details about texture identifiers. + -- - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer, + -- it will help you debug issues if you are confused about it. + -- - Consider using the lower-level ImDrawList:AddImage() API, via ImGui.GetWindowDrawList():AddImage(). + -- - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md + -- - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + + -- Grab the current texture identifier used by the font atlas. local atlas = io.Fonts local my_tex_id = atlas.TexRef - local my_tex_w = atlas.TexData and atlas.TexData.Width or 0 + local my_tex_w = atlas.TexData and atlas.TexData.Width or 0 -- Regular user code should never have to care about TexData fields, but since we want to display the entire texture here, we pull Width/Height from it. local my_tex_h = atlas.TexData and atlas.TexData.Height or 0 ImGui.Text("%.0fx%.0f", my_tex_w, my_tex_h) + -- Basic drawing ImGui.SeparatorText("Image()/ImageWithBg() function") ImGui.PushStyleVar(ImGuiStyleVar.ImageBorderSize, math.max(1.0, ImGui.GetStyle().ImageBorderSize)) - ImGui.ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0.0, 0.0), ImVec2(1.0, 1.0), ImVec4(0.0, 0.0, 0.0, 1.0)) + ImGui.ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0.0, 0.0), ImVec2(1.0, 1.0), ImVec4(0.0, 0.0, 0.0, 1.0)) -- uv_min: Top-left, uv_max: Lower-right ImGui.PopStyleVar() + -- Fancy widget ImGui.SeparatorText("Interactive Image Viewer") s.viewer = s.viewer or ExampleImageViewerData() local canvas_size = ImVec2(ImGui.GetContentRegionAvail().x, my_tex_h * 2.0) @@ -24321,11 +27971,15 @@ function DemoWindowWidgetsImages() ImGui.SeparatorText("Textured Buttons") ImGui.TextWrapped("And now some textured buttons..") for i = 0, 7 do + -- UV coordinates are often (0.0, 0.0) and (1.0, 1.0) to display an entire textures. + -- Here are trying to display only a 32x32 pixels area of the texture, hence the UV computation. + -- Read about UV coordinates here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples ImGui.PushID(i) if i > 0 then ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, ImVec2(i - 1.0, i - 1.0)) end - local size = ImVec2(32.0, 32.0) - local uv0 = ImVec2(0.0, 0.0) - local uv1 = ImVec2(32.0 / my_tex_w, 32.0 / my_tex_h) + local size = ImVec2(32.0, 32.0) -- Size of the image we want to make visible + local uv0 = ImVec2(0.0, 0.0) -- UV coordinates for lower-left + local uv1 = ImVec2(32.0 / my_tex_w, 32.0 / my_tex_h) -- UV coordinates for (32,32) in our texture + -- bg_col: Black background, tint_col: No tint if ImGui.ImageButton("", my_tex_id, size, uv0, uv1, ImVec4(0.0, 0.0, 0.0, 1.0), ImVec4(1.0, 1.0, 1.0, 1.0)) then s.pressed_count = s.pressed_count + 1 end @@ -24338,29 +27992,45 @@ function DemoWindowWidgetsImages() ImGui.TreePop() end -S.lb = { sel = 0, highlight = false } +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsListBoxes() +------------------------------------------------------------------------------- + +S.lb = { sel = 0, highlight = false } -- sel: Here we store our selected data as an index. function DemoWindowWidgetsListBoxes() if not ImGui.TreeNode("List Boxes") then return end + -- BeginListBox() is essentially a thin wrapper to using BeginChild()/EndChild() + -- using the ImGuiChildFlags.FrameStyle flag for stylistic changes + displaying a label. + -- You may be tempted to simply use BeginChild() directly. However note that BeginChild() requires EndChild() + -- to always be called (inconsistent with BeginListBox()/EndListBox()). + + -- Using the generic BeginListBox() API, you have full control over how to display the combo contents. + -- (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + -- stored in the object itself, etc.) local s = S.lb local items = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" } - local item_highlighted_idx = -1 + local item_highlighted_idx = -1 -- Here we store our highlighted data as an index. _, s.highlight = ImGui.Checkbox("Highlight hovered item in second listbox", s.highlight) if ImGui.BeginListBox("listbox 1") then for n = 0, #items - 1 do local is_selected = (s.sel == n) if ImGui.Selectable(items[n + 1], is_selected) then s.sel = n end if s.highlight and ImGui.IsItemHovered() then item_highlighted_idx = n end + -- Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if is_selected then ImGui.SetItemDefaultFocus() end end ImGui.EndListBox() end ImGui.SameLine(); HelpMarker("Here we are sharing selection state between both boxes.") + + -- Custom size: use all width, 5 items tall ImGui.Text("Full-width:") if ImGui.BeginListBox("##listbox 2", ImVec2(-FLT_MIN, 5 * ImGui.GetTextLineHeightWithSpacing())) then for n = 0, #items - 1 do local is_selected = (s.sel == n) local flags = (item_highlighted_idx == n) and ImGuiSelectableFlags.Highlight or 0 if ImGui.Selectable(items[n + 1], is_selected, flags) then s.sel = n end + -- Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if is_selected then ImGui.SetItemDefaultFocus() end end ImGui.EndListBox() @@ -24368,6 +28038,10 @@ function DemoWindowWidgetsListBoxes() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsLiveEdit() +------------------------------------------------------------------------------- + S.le = { str = Buf("", 32), i = 0, f = 0.0 } function DemoWindowWidgetsLiveEdit(demo_data) if not ImGui.TreeNode("Live Edit Flags") then return end @@ -24391,15 +28065,22 @@ function DemoWindowWidgetsLiveEdit(demo_data) ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsMixedValues() +------------------------------------------------------------------------------- + S.mv = { use_liveedit = false, items = { 12.0, 0.0, 0.0 } } function DemoWindowWidgetsMixedValues() if not ImGui.TreeNode("Mixed Values") then return end local s = S.mv local items = s.items + -- This is designed for advanced property editors which are generally reusable and data-driven. HelpMarker("Using ImGuiItemFlags_MixedValue.") _, s.use_liveedit = ImGui.Checkbox("ImGuiItemFlags_LiveEditOnInput", s.use_liveedit) ImGui.SeparatorText("Scalar/Text Widgets") local is_mixed = items[1] ~= items[2] or items[1] ~= items[3] + + -- Demonstrate Drags, Sliders, Inputs ImGui.PushItemFlag(ImGuiItemFlags.LiveEditOnInput, s.use_liveedit) ImGui.PushItemFlag(ImGuiItemFlags.MixedValue, is_mixed) local edited, e = false, false @@ -24414,27 +28095,32 @@ function DemoWindowWidgetsMixedValues() items[3] = ImGui.InputFloat("item 2", items[3]) ImGui.PopItemFlag() + -- Demonstrate Checkbox(), RadioButton(), Combo(), ColorEdit4() ImGui.SeparatorText("Others Widgets") - ImGui.Text("(note: edits are not applied in this demo)") + ImGui.Text("(note: edits are not applied in this demo)") -- <-- Would need more state tracking. ImGui.Checkbox("Checkbox On", true) ImGui.Checkbox("Checkbox Off", false) ImGui.PushItemFlag(ImGuiItemFlags.MixedValue, true) ImGui.Checkbox("Checkbox Mixed", false) ImGui.RadioButtonEx("RadioButton Mixed", true) ImGui.SameLine() - ImGui.RadioButtonEx("RadioButton Mixed##2", true) + ImGui.RadioButtonEx("RadioButton Mixed##2", true) -- Showing 2 radio buttons makes the example more clear ImGui.Combo("Combo", 0, "One\0Two\0Three\0") ImGui.ColorEdit4("ColorEdit4", ImVec4(0.5, 0.5, 0.5, 0.5)) ImGui.PopItemFlag() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsMultiComponents() +------------------------------------------------------------------------------- + S.mc = { vec4f = { 0.10, 0.20, 0.30, 0.44 }, vec4i = { 1, 5, 100, 255 }, flags = 0, b = 10, e = 90, bi = 100, ei = 1000 } function DemoWindowWidgetsMultiComponents() if not ImGui.TreeNode("Multi-component Widgets") then return end local s = S.mc local f, i = s.vec4f, s.vec4i - if ImGuiSliderFlags.ColorMarkers then _, s.flags = ImGui.CheckboxFlags("ImGuiSliderFlags_ColorMarkers", s.flags, ImGuiSliderFlags.ColorMarkers) end + if ImGuiSliderFlags.ColorMarkers then _, s.flags = ImGui.CheckboxFlags("ImGuiSliderFlags_ColorMarkers", s.flags, ImGuiSliderFlags.ColorMarkers) end -- Only passing this to Drag/Sliders local flags = s.flags for _, n in ipairs({ 2, 3, 4 }) do ImGui.SeparatorText(n .. "-wide") @@ -24452,6 +28138,13 @@ function DemoWindowWidgetsMultiComponents() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsPlotting() +------------------------------------------------------------------------------- + +-- Plot/Graph widgets are not very good. +-- Consider using a third-party library such as ImPlot: https://github.com/epezent/implot +-- (see others https://github.com/ocornut/imgui/wiki/Useful-Extensions) S.plot = { animate = true, arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }, values = {}, values_offset = 0, refresh_time = 0.0, phase = 0.0, func_type = 0, display_count = 70 } for n = 1, 90 do S.plot.values[n] = 0.0 end @@ -24462,22 +28155,32 @@ function DemoWindowWidgetsPlotting() ImGui.TextLinkOpenURL("https://github.com/epezent/implot") ImGui.Separator() _, s.animate = ImGui.Checkbox("Animate", s.animate) + + -- Plot as lines and plot as histogram ImGui.PlotLines("Frame Times", s.arr, nil, #s.arr) ImGui.PlotHistogram("Histogram", s.arr, nil, #s.arr, 0, nil, 0.0, 1.0, ImVec2(0, 80.0)) + -- ImGui.SameLine(); HelpMarker("Consider using ImPlot instead!") + -- Fill an array of contiguous float values to plot local values = s.values if not s.animate or s.refresh_time == 0.0 then s.refresh_time = ImGui.GetTime() end - while s.refresh_time < ImGui.GetTime() do + while s.refresh_time < ImGui.GetTime() do -- Create data at fixed 60 Hz rate for the demo values[s.values_offset + 1] = math.cos(s.phase) s.values_offset = (s.values_offset + 1) % #values s.phase = s.phase + 0.10 * s.values_offset s.refresh_time = s.refresh_time + 1.0 / 60.0 end + + -- Plots can display overlay texts + -- (in this example, we will display an average value) local average = 0.0 for n = 1, #values do average = average + values[n] end average = average / #values ImGui.PlotLines("Lines", values, nil, #values, s.values_offset, string.format("avg %f", average), -1.0, 1.0, ImVec2(0, 80.0)) + -- Use functions to generate output + -- FIXME: This is actually VERY awkward because current plot API only pass in indices. + -- We probably want an API passing floats and user provide sample rate/count. -- Getters receive a 1-based index in this port local function Sin(_, i) return math.sin((i - 1) * 0.1) end local function Saw(_, i) return ((i - 1) % 2 == 1) and 1.0 or -1.0 end @@ -24492,24 +28195,39 @@ function DemoWindowWidgetsPlotting() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsProgressBars() +------------------------------------------------------------------------------- + S.pb = { accum = 0.0, dir = 1.0 } function DemoWindowWidgetsProgressBars() if not ImGui.TreeNode("Progress Bars") then return end + -- Animate a simple progress bar local s = S.pb s.accum = s.accum + s.dir * 0.4 * ImGui.GetIO().DeltaTime if s.accum >= 1.1 then s.accum = 1.1; s.dir = -s.dir end if s.accum <= -0.1 then s.accum = -0.1; s.dir = -s.dir end local progress = DemoClamp(s.accum, 0.0, 1.0) + + -- Typically we would use ImVec2(-1.0,0.0) or ImVec2(-FLT_MIN,0.0) to use all available width, + -- or ImVec2(width,0.0) for a specified width. ImVec2(0.0,0.0) uses ItemWidth. ImGui.ProgressBar(progress, ImVec2(0.0, 0.0)) ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x) ImGui.Text("Progress Bar") ImGui.ProgressBar(progress, ImVec2(0.0, 0.0), string.format("%d/%d", math.floor(progress * 1753), 1753)) + + -- Pass an animated negative value, e.g. -1.0 * ImGui.GetTime() is the recommended value. + -- Adjust the factor if you want to adjust the animation speed. ImGui.ProgressBar(-1.0 * ImGui.GetTime(), ImVec2(0.0, 0.0), "Searching..") ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x) ImGui.Text("Indeterminate") ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsQueryingStatuses() +------------------------------------------------------------------------------- + -- Selectable(label, bool* p_selected) overload: toggles on press local function SelectableP(label, sel, flags, size) local pressed = ImGui.Selectable(label, sel, flags, size) @@ -24525,6 +28243,7 @@ S.qs = { item_type = 4, item_disabled = false, item_mixedvalue = false, liveedit function DemoWindowWidgetsQueryingStatuses() local s = S.qs if ImGui.TreeNode("Querying Item Status (Edited/Active/Hovered etc.)") then + -- Select an item type local item_names = { "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputTextMultiline", "InputFloat", "InputFloat3", "ColorEdit4", "Selectable", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "Combo", "ListBox" } s.item_type = ImGui.Combo("Item Type", s.item_type, item_names, #item_names, #item_names) @@ -24547,24 +28266,25 @@ function DemoWindowWidgetsQueryingStatuses() ImGui.PushItemFlag(ImGuiItemFlags.LiveEditOnInputScalar, bit32.band(s.liveedit_flags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0) end + -- Submit selected items so we can query their status in the code following it. local ret = false local t = s.item_type if s.item_disabled then ImGui.BeginDisabled(true) end if s.item_mixedvalue then ImGui.PushItemFlag(ImGuiItemFlags.MixedValue, true) end - if t == 0 then ImGui.Text("ITEM: Text") end - if t == 1 then ret = ImGui.Button("ITEM: Button") end - if t == 2 then ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true); ret = ImGui.Button("ITEM: Button"); ImGui.PopItemFlag() end - if t == 3 then ret, s.b = ImGui.Checkbox("ITEM: Checkbox", s.b) end - if t == 4 then s.col4f[1], ret = ImGui.SliderFloat("ITEM: SliderFloat", s.col4f[1], 0.0, 1.0) end - if t == 5 then ret = ImGui.InputText("ITEM: InputText", s.str, 16) end - if t == 6 then ret = ImGui.InputTextMultiline("ITEM: InputTextMultiline", s.str, 16) end - if t == 7 then s.col4f[1], ret = ImGui.InputFloat("ITEM: InputFloat", s.col4f[1], 1.0) end - if t == 8 then ret = ImGui.InputFloat3("ITEM: InputFloat3", s.col4f) end - if t == 9 then ret = ImGui.ColorEdit4("ITEM: ColorEdit4", s.col4f) end - if t == 10 then ret = ImGui.Selectable("ITEM: Selectable") end - if t == 11 then ret = ImGui.MenuItem("ITEM: MenuItem") end - if t == 12 then ret = ImGui.TreeNode("ITEM: TreeNode"); if ret then ImGui.TreePop() end end - if t == 13 then ret = ImGui.TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", bit32.bor(ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.NoTreePushOnOpen)) end + if t == 0 then ImGui.Text("ITEM: Text") end -- Testing text items with no identifier/interaction + if t == 1 then ret = ImGui.Button("ITEM: Button") end -- Testing button + if t == 2 then ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true); ret = ImGui.Button("ITEM: Button"); ImGui.PopItemFlag() end -- Testing button (with repeater) + if t == 3 then ret, s.b = ImGui.Checkbox("ITEM: Checkbox", s.b) end -- Testing checkbox + if t == 4 then s.col4f[1], ret = ImGui.SliderFloat("ITEM: SliderFloat", s.col4f[1], 0.0, 1.0) end -- Testing basic item + if t == 5 then ret = ImGui.InputText("ITEM: InputText", s.str, 16) end -- Testing input text (which handles tabbing) + if t == 6 then ret = ImGui.InputTextMultiline("ITEM: InputTextMultiline", s.str, 16) end -- Testing input text (which uses a child window) + if t == 7 then s.col4f[1], ret = ImGui.InputFloat("ITEM: InputFloat", s.col4f[1], 1.0) end -- Testing +/- buttons on scalar input + if t == 8 then ret = ImGui.InputFloat3("ITEM: InputFloat3", s.col4f) end -- Testing multi-component items (IsItemXXX flags are reported merged) + if t == 9 then ret = ImGui.ColorEdit4("ITEM: ColorEdit4", s.col4f) end -- Testing multi-component items (IsItemXXX flags are reported merged) + if t == 10 then ret = ImGui.Selectable("ITEM: Selectable") end -- Testing selectable item + if t == 11 then ret = ImGui.MenuItem("ITEM: MenuItem") end -- Testing menu item (they use ImGuiButtonFlags.PressedOnRelease button policy) + if t == 12 then ret = ImGui.TreeNode("ITEM: TreeNode"); if ret then ImGui.TreePop() end end -- Testing tree node + if t == 13 then ret = ImGui.TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", bit32.bor(ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.NoTreePushOnOpen)) end -- Testing tree node with ImGuiButtonFlags.PressedOnDoubleClick button policy. if t == 14 then s.combo, ret = ImGui.Combo("ITEM: Combo", s.combo, { "Apple", "Banana", "Cherry", "Kiwi" }) end if t == 15 then s.listbox, ret = ImGui.ListBox("ITEM: ListBox", s.listbox, { "Apple", "Banana", "Cherry", "Kiwi" }, 4, 4) end @@ -24573,7 +28293,12 @@ function DemoWindowWidgetsQueryingStatuses() local hovered_delay_stationary = ImGui.IsItemHovered(HF.Stationary) local hovered_delay_short = ImGui.IsItemHovered(HF.DelayShort) local hovered_delay_normal = ImGui.IsItemHovered(HF.DelayNormal) - local hovered_delay_tooltip = ImGui.IsItemHovered(HF.ForTooltip) + local hovered_delay_tooltip = ImGui.IsItemHovered(HF.ForTooltip) -- = Normal + Stationary + + -- Display the values of IsItemHovered() and other common item state functions. + -- Note that the ImGuiHoveredFlags.XXX flags can be combined. + -- Because BulletText is an item itself and that would affect the output of IsItemXXX functions, + -- we query every state in a single call to avoid storing them and to simplify the code. local rmin, rmax, rsize = ImGui.GetItemRectMin(), ImGui.GetItemRectMax(), ImGui.GetItemRectSize() ImGui.BulletText( "Return value = %d\nIsItemFocused() = %d\nIsItemHovered() = %d\nIsItemHovered(_AllowWhenBlockedByPopup) = %d\n" .. @@ -24607,6 +28332,7 @@ function DemoWindowWidgetsQueryingStatuses() if s.embed then ImGui.BeginChild("outer_child", ImVec2(0, ImGui.GetFontSize() * 20.0), ImGuiChildFlags.Borders) end local FF, HF = ImGuiFocusedFlags, ImGuiHoveredFlags local bor = bit32.bor + -- Testing IsWindowFocused() function with its various flags. ImGui.BulletText( "IsWindowFocused() = %d\nIsWindowFocused(_ChildWindows) = %d\nIsWindowFocused(_ChildWindows|_NoPopupHierarchy) = %d\n" .. "IsWindowFocused(_ChildWindows|_DockHierarchy) = %d\nIsWindowFocused(_ChildWindows|_RootWindow) = %d\n" .. @@ -24618,6 +28344,8 @@ function DemoWindowWidgetsQueryingStatuses() B(ImGui.IsWindowFocused(bor(FF.ChildWindows, FF.RootWindow, FF.NoPopupHierarchy))), B(ImGui.IsWindowFocused(bor(FF.ChildWindows, FF.RootWindow, FF.DockHierarchy))), B(ImGui.IsWindowFocused(FF.RootWindow)), B(ImGui.IsWindowFocused(bor(FF.RootWindow, FF.NoPopupHierarchy))), B(ImGui.IsWindowFocused(bor(FF.RootWindow, FF.DockHierarchy))), B(ImGui.IsWindowFocused(FF.AnyWindow))) + + -- Testing IsWindowHovered() function with its various flags. ImGui.BulletText( "IsWindowHovered() = %d\nIsWindowHovered(_AllowWhenBlockedByPopup) = %d\nIsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n" .. "IsWindowHovered(_ChildWindows) = %d\nIsWindowHovered(_ChildWindows|_NoPopupHierarchy) = %d\nIsWindowHovered(_ChildWindows|_DockHierarchy) = %d\n" .. @@ -24636,10 +28364,15 @@ function DemoWindowWidgetsQueryingStatuses() ImGui.EndChild() if s.embed then ImGui.EndChild() end + -- Calling IsItemHovered() after begin returns the hovered status of the title bar. + -- This is useful in particular if you want to create a context menu associated to the title bar of a window. + -- This will also work when docked into a Tab (the Tab replace the Title Bar and guarantee the same properties). _, s.test_window = ImGui.Checkbox("Hovered/Active tests after Begin() for title bar testing", s.test_window) if s.test_window then + -- FIXME-DOCK: This window cannot be docked within the ImGui Demo window, this will cause a feedback loop and get them stuck. + -- Could we fix this through an ImGuiWindowClass feature? Or an API call to tag our parent as "don't skip items"? s.test_window = ImGui.Begin("Title bar Hovered/Active tests", s.test_window) - if ImGui.BeginPopupContextItem() then + if ImGui.BeginPopupContextItem() then -- <-- This is using IsItemHovered() if ImGui.MenuItem("Close") then s.test_window = false end ImGui.EndPopup() end @@ -24651,13 +28384,25 @@ function DemoWindowWidgetsQueryingStatuses() end end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsSelectables() +------------------------------------------------------------------------------- + S.sel = { basic = { false, true, false, false }, multi = { false, false, false }, checked = { false, false, false, false, false }, selected_n = 0, tables = {}, grid = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }, align = { true, false, true, false, true, false, true, false, true } } for i = 1, 10 do S.sel.tables[i] = false end function DemoWindowWidgetsSelectables() + -- ImGui.SetNextItemOpen(true, ImGuiCond.Once) if not ImGui.TreeNode("Selectables") then return end local s = S.sel + -- Selectable() has 2 overloads: + -- - The one taking "bool selected" as a read-only selection information. + -- When Selectable() has been clicked it returns true and you can alter selection state accordingly. + -- - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases) + -- (in this port: the SelectableP() helper above, which returns (pressed, selected)) + -- The earlier is more flexible, as in real application your selection may be stored in many different ways + -- and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc). if ImGui.TreeNode("Basic") then local b = s.basic _, b[1] = SelectableP("1. I am selectable", b[1]) @@ -24670,10 +28415,17 @@ function DemoWindowWidgetsSelectables() end if ImGui.TreeNode("Multiple items on the same line") then + -- - Using SetNextItemAllowOverlap() + -- - Using the Selectable() override that takes "bool* p_selected" parameter, the bool value is toggled automatically. local m = s.multi ImGui.SetNextItemAllowOverlap(); _, m[1] = SelectableP("main.c", m[1]); ImGui.SameLine(); ImGui.SmallButton("Link 1") ImGui.SetNextItemAllowOverlap(); _, m[2] = SelectableP("hello.cpp", m[2]); ImGui.SameLine(); ImGui.SmallButton("Link 2") ImGui.SetNextItemAllowOverlap(); _, m[3] = SelectableP("hello.h", m[3]); ImGui.SameLine(); ImGui.SmallButton("Link 3") + + -- (2) + -- - Using ImGuiSelectableFlags.AllowOverlap is a shortcut for calling SetNextItemAllowOverlap() + -- - No visible label, display contents inside the selectable bounds. + -- - We don't maintain actual selection in this example to keep things simple. ImGui.Spacing() local color_marker_w = ImGui.CalcTextSize("x").x for n = 0, 4 do @@ -24698,7 +28450,7 @@ function DemoWindowWidgetsSelectables() if ImGui.BeginTable("split1", 3, bit32.bor(TF.Resizable, TF.NoSavedSettings, TF.Borders)) then for i = 0, 9 do ImGui.TableNextColumn() - _, sel[i + 1] = SelectableP(string.format("Item %d", i), sel[i + 1]) + _, sel[i + 1] = SelectableP(string.format("Item %d", i), sel[i + 1]) -- FIXME-TABLE: Selection overlap end ImGui.EndTable() end @@ -24720,9 +28472,11 @@ function DemoWindowWidgetsSelectables() if ImGui.TreeNode("Grid") then local g = s.grid + + -- Add in a bit of silly fun... local time = ImGui.GetTime() local winning_state = true - for y = 1, 4 do for x = 1, 4 do if g[y][x] == 0 then winning_state = false end end end + for y = 1, 4 do for x = 1, 4 do if g[y][x] == 0 then winning_state = false end end end -- If all cells are selected... if winning_state then ImGui.PushStyleVar(ImGuiStyleVar.SelectableTextAlign, ImVec2(0.5 + 0.5 * math.cos(time * 2.0), 0.5 + 0.5 * math.sin(time * 3.0))) end @@ -24732,6 +28486,7 @@ function DemoWindowWidgetsSelectables() if x > 1 then ImGui.SameLine() end ImGui.PushID((y - 1) * 4 + (x - 1)) if ImGui.Selectable("Sailor", g[y][x] ~= 0, 0, ImVec2(size, size)) then + -- Toggle clicked cell + toggle neighbors g[y][x] = 1 - g[y][x] if x > 1 then g[y][x - 1] = 1 - g[y][x - 1] end if x < 4 then g[y][x + 1] = 1 - g[y][x + 1] end @@ -24763,6 +28518,10 @@ function DemoWindowWidgetsSelectables() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTabs() +------------------------------------------------------------------------------- + local function EditTabBarFittingPolicyFlags(flags) local TB = ImGuiTabBarFlags if bit32.band(flags, TB.FittingPolicyMask_) == 0 then flags = bit32.bor(flags, TB.FittingPolicyDefault_) end @@ -24793,17 +28552,23 @@ function DemoWindowWidgetsTabs() end if ImGui.TreeNode("Advanced & Close Button") then + -- Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0). for _, n in ipairs({ "Reorderable", "AutoSelectNewTabs", "TabListPopupButton", "NoCloseWithMiddleMouseButton", "DrawSelectedOverline" }) do _, s.adv_flags = ImGui.CheckboxFlags("ImGuiTabBarFlags_" .. n, s.adv_flags, TB[n]) end s.adv_flags = EditTabBarFittingPolicyFlags(s.adv_flags) + + -- Tab Bar ImGui.AlignTextToFramePadding() ImGui.Text("Opened:") local names = { "Artichoke", "Beetroot", "Celery", "Daikon" } - for n = 1, 4 do + for n = 1, 4 do -- s.opened: Persistent user state ImGui.SameLine() _, s.opened[n] = ImGui.Checkbox(names[n], s.opened[n]) end + + -- Passing an open flag to BeginTabItem() is similar to passing one to Begin(): + -- the returned open value will be false when the tab is closed. if ImGui.BeginTabBar("MyTabBar", s.adv_flags) then for n = 1, 4 do if s.opened[n] then @@ -24823,14 +28588,22 @@ function DemoWindowWidgetsTabs() end if ImGui.TreeNode("TabItemButton & Leading/Trailing flags") then - if s.next_tab_id == 0 then + if s.next_tab_id == 0 then -- Initialize with some default tabs for _ = 1, 3 do s.active_tabs[#s.active_tabs + 1] = s.next_tab_id; s.next_tab_id = s.next_tab_id + 1 end end + + -- TabItemButton() and Leading/Trailing flags are distinct features which we will demo together. + -- (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags... + -- but they tend to make more sense together) _, s.show_leading = ImGui.Checkbox("Show Leading TabItemButton()", s.show_leading) _, s.show_trailing = ImGui.Checkbox("Show Trailing TabItemButton()", s.show_trailing) _, s.show_lt_tabs = ImGui.Checkbox("Show Leading+Trailing TabItem()", s.show_lt_tabs) + + -- Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs s.tib_flags = EditTabBarFittingPolicyFlags(s.tib_flags) + if ImGui.BeginTabBar("MyTabBar", s.tib_flags) then + -- Demo a Leading TabItemButton(): click the "?" button to open a menu if s.show_leading then if ImGui.TabItemButton("?", bit32.bor(TI.Leading, TI.NoTooltip)) then ImGui.OpenPopup("MyHelpMenu") end end @@ -24838,15 +28611,23 @@ function DemoWindowWidgetsTabs() ImGui.Selectable("Hello!") ImGui.EndPopup() end + + -- Demo Leading/Trailing Tabs if s.show_lt_tabs then if ImGui.BeginTabItem("Leading", nil, TI.Leading) then ImGui.EndTabItem() end if ImGui.BeginTabItem("Trailing", nil, TI.Trailing) then ImGui.EndTabItem() end end + + -- Demo Trailing Tabs: click the "+" button to add a new tab. + -- (In your app you may want to use a font icon instead of the "+") + -- We submit it before the regular tabs, but thanks to the ImGuiTabItemFlags.Trailing flag it will always appear at the end. if s.show_trailing then if ImGui.TabItemButton("+", bit32.bor(TI.Trailing, TI.NoTooltip)) then - s.active_tabs[#s.active_tabs + 1] = s.next_tab_id; s.next_tab_id = s.next_tab_id + 1 + s.active_tabs[#s.active_tabs + 1] = s.next_tab_id; s.next_tab_id = s.next_tab_id + 1 -- Add new tab end end + + -- Submit our regular tabs local n = 1 while n <= #s.active_tabs do local name = string.format("%04d", s.active_tabs[n]) @@ -24865,11 +28646,16 @@ function DemoWindowWidgetsTabs() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsText() +------------------------------------------------------------------------------- + S.text = { custom_size = 16.0, custom_scale = 1.0, wrap_width = 200.0, utf8 = Buf("\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e", 32) } function DemoWindowWidgetsText() if not ImGui.TreeNode("Text") then return end local s = S.text if ImGui.TreeNode("Colorful Text") then + -- Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. ImGui.TextColored(ImVec4(1.0, 0.0, 1.0, 1.0), "Pink") ImGui.TextColored(ImVec4(1.0, 1.0, 0.0, 1.0), "Yellow") ImGui.TextDisabled("Disabled") @@ -24882,8 +28668,9 @@ function DemoWindowWidgetsText() local global_scale = style.FontScaleMain * style.FontScaleDpi ImGui.Text("style.FontScaleMain = %0.2f", style.FontScaleMain) ImGui.Text("style.FontScaleDpi = %0.2f", style.FontScaleDpi) - ImGui.Text("global_scale = ~%0.2f", global_scale) + ImGui.Text("global_scale = ~%0.2f", global_scale) -- This is not technically accurate as internal scales may apply, but conceptually let's pretend it is. ImGui.Text("FontSize = %0.2f", ImGui.GetFontSize()) + ImGui.SeparatorText("") s.custom_size = ImGui.SliderFloat("custom_size", s.custom_size, 10.0, 100.0, "%.0f") ImGui.Text("ImGui::PushFont(nullptr, custom_size);") @@ -24908,6 +28695,7 @@ function DemoWindowWidgetsText() end if ImGui.TreeNode("Word Wrapping") then + -- Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. ImGui.TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages.") ImGui.Spacing() s.wrap_width = ImGui.SliderFloat("Wrap width", s.wrap_width, -20, 600, "%.0f") @@ -24923,6 +28711,8 @@ function DemoWindowWidgetsText() else ImGui.Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh") end + + -- Draw actual text bounding box, following by marker of our expected limit (should not overlap!) draw_list:AddRect(ImGui.GetItemRectMin(), ImGui.GetItemRectMax(), IM_COL32(255, 255, 0, 255)) draw_list:AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255)) ImGui.PopTextWrapPos() @@ -24931,6 +28721,12 @@ function DemoWindowWidgetsText() end if ImGui.TreeNode("UTF-8 Text") then + -- UTF-8 test with Japanese characters + -- (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.) + -- - FOR THIS DEMO FILE ONLY, WE ARE *NOT* INCLUDING RAW UTF-8 + -- CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal escapes. + -- Note that characters values are preserved even by InputText() if the font cannot be displayed, + -- so you can safely copy & paste garbled characters into another application. ImGui.TextWrapped("CJK text will only appear if the font was loaded with the appropriate CJK character ranges. Call io.Fonts->AddFontFromFileTTF() manually to load extra character ranges. Read docs/FONTS.md for details.") ImGui.Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)") ImGui.Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)") @@ -24940,9 +28736,15 @@ function DemoWindowWidgetsText() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTextFilter() +------------------------------------------------------------------------------- + S.tf = { filter = nil } function DemoWindowWidgetsTextFilter() if not ImGui.TreeNode("Text Filter") then return end + -- Helper class to easy setup a text filter. + -- You may want to implement a more feature-full filtering scheme in your own application. S.tf.filter = S.tf.filter or ImGuiTextFilter() local filter = S.tf.filter HelpMarker("Not a widget per-se, but ImGuiTextFilter is a helper to perform simple filtering on text strings.") @@ -24961,6 +28763,10 @@ function DemoWindowWidgetsTextFilter() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTextInput() +------------------------------------------------------------------------------- + S.ti = { text = Buf("/*\n The Pentium F00F bug, shorthand for F0 0F C7 C8,\n the hexadecimal encoding of one offending instruction,\n more formally, the invalid operand with locked CMPXCHG8B\n instruction bug, is a design flaw in the majority of\n Intel Pentium, Pentium MMX, and Pentium OverDrive\n processors (all in the P5 microarchitecture).\n*/\n\nlabel:\n\tlock cmpxchg8b eax\n", 1024 * 16), ml_flags = ImGuiInputTextFlags.AllowTabInput, @@ -24977,6 +28783,7 @@ function DemoWindowWidgetsTextInput() if IT[name] then _, s[key] = ImGui.CheckboxFlags("ImGuiInputTextFlags_" .. name, s[key], IT[name]) end end if ImGui.TreeNode("Multi-line Text Input") then + -- WE ARE USING A FIXED-SIZE BUFFER FOR SIMPLICITY HERE. HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type.") FlagBox("ml_flags", "ReadOnly") FlagBox("ml_flags", "WordWrap") @@ -24990,12 +28797,14 @@ function DemoWindowWidgetsTextInput() if ImGui.TreeNode("Filtered Text Input") then local a, z, A, Z = string.byte("a"), string.byte("z"), string.byte("A"), string.byte("Z") + -- Modify character input by altering 'data.EventChar' (ImGuiInputTextFlags.CallbackCharFilter callback) local function FilterCasingSwap(data) local c = data.EventChar - if c >= a and c <= z then data.EventChar = c - (a - A) - elseif c >= A and c <= Z then data.EventChar = c + (a - A) end + if c >= a and c <= z then data.EventChar = c - (a - A) -- Lowercase becomes uppercase + elseif c >= A and c <= Z then data.EventChar = c + (a - A) end -- Uppercase becomes lowercase return 0 end + -- Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i', otherwise return 1 (filter out) local function FilterImGuiLetters(data) local c = data.EventChar if c < 256 and string.find("imgui", string.char(c), 1, true) then return 0 end @@ -25007,8 +28816,8 @@ function DemoWindowWidgetsTextInput() ImGui.InputText("hexadecimal", f[3], 32, bit32.bor(IT.CharsHexadecimal, IT.CharsUppercase)) ImGui.InputText("uppercase", f[4], 32, IT.CharsUppercase) ImGui.InputText("no blank", f[5], 32, IT.CharsNoBlank) - ImGui.InputText("casing swap", f[6], 32, IT.CallbackCharFilter, FilterCasingSwap) - ImGui.InputText("\"imgui\"", f[7], 32, IT.CallbackCharFilter, FilterImGuiLetters) + ImGui.InputText("casing swap", f[6], 32, IT.CallbackCharFilter, FilterCasingSwap) -- Use CharFilter callback to replace characters. + ImGui.InputText("\"imgui\"", f[7], 32, IT.CallbackCharFilter, FilterImGuiLetters) -- Use CharFilter callback to disable some characters. ImGui.TreePop() end @@ -25035,9 +28844,12 @@ function DemoWindowWidgetsTextInput() data:SelectAll() end elseif data.EventFlag == IT.CallbackEdit then + -- Toggle casing of first character local c = data.Buf[1] if (c >= 97 and c <= 122) or (c >= 65 and c <= 90) then data.Buf[1] = bit32.bxor(c, 32) end data.BufDirty = true + + -- Increment a counter local p_int = data.UserData p_int[1] = p_int[1] + 1 end @@ -25077,12 +28889,25 @@ function DemoWindowWidgetsTextInput() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTooltips() +------------------------------------------------------------------------------- + S.tt = { arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }, always_on = 0 } function DemoWindowWidgetsTooltips() if not ImGui.TreeNode("Tooltips") then return end local s = S.tt local HF = ImGuiHoveredFlags + -- Tooltips are windows following the mouse. They do not take focus away. ImGui.SeparatorText("General") + + -- Typical use cases: + -- - Short-form (text only): SetItemTooltip("Hello") + -- - Short-form (any contents): if BeginItemTooltip() then Text("Hello"); EndTooltip() end + + -- - Full-form (text only): if IsItemHovered(...) then SetTooltip("Hello") end + -- - Full-form (any contents): if IsItemHovered(...) and BeginTooltip() then Text("Hello"); EndTooltip() end + HelpMarker("Tooltip are typically created by using a IsItemHovered() + SetTooltip() sequence.\n\nWe provide a helper SetItemTooltip() function to perform the two with standards flags.") local sz = ImVec2(-FLT_MIN, 0.0) ImGui.Button("Basic", sz) @@ -25096,6 +28921,9 @@ function DemoWindowWidgetsTooltips() end ImGui.SeparatorText("Always On") + + -- Showcase NOT relying on a IsItemHovered() to emit a tooltip. + -- Here the tooltip is always emitted when 'always_on == true'. _, s.always_on = ImGui.RadioButton("Off", s.always_on, 0) ImGui.SameLine() _, s.always_on = ImGui.RadioButton("Always On (Simple)", s.always_on, 1) @@ -25110,6 +28938,11 @@ function DemoWindowWidgetsTooltips() ImGui.SeparatorText("Custom") HelpMarker("Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() is the preferred way to standardize tooltip activation details across your application. You may however decide to use custom flags for a specific tooltip instance.") + + -- The following examples are passed for documentation purpose but may not be useful to most users. + -- Passing ImGuiHoveredFlags.ForTooltip to IsItemHovered() will pull ImGuiHoveredFlags flags values from + -- 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on whether mouse or keyboard/gamepad is being used. + -- With default settings, ImGuiHoveredFlags.ForTooltip is equivalent to ImGuiHoveredFlags.DelayShort + ImGuiHoveredFlags.Stationary. ImGui.Button("Manual", sz) if ImGui.IsItemHovered(HF.ForTooltip) then ImGui.SetTooltip("I am a manually emitted tooltip.") end ImGui.Button("DelayNone", sz) @@ -25120,6 +28953,9 @@ function DemoWindowWidgetsTooltips() if ImGui.IsItemHovered(bit32.bor(HF.DelayNormal, HF.NoSharedDelay)) then ImGui.SetTooltip("I am a tooltip with a long delay (%0.2f sec).", ImGui.GetStyle().HoverDelayNormal) end ImGui.Button("Stationary", sz) if ImGui.IsItemHovered(HF.Stationary) then ImGui.SetTooltip("I am a tooltip requiring mouse to be stationary before activating.") end + + -- Using ImGuiHoveredFlags.ForTooltip will pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav', + -- which default value include the ImGuiHoveredFlags.AllowWhenDisabled flag. ImGui.BeginDisabled() ImGui.Button("Disabled item", sz) if ImGui.IsItemHovered(HF.ForTooltip) then ImGui.SetTooltip("I am a tooltip for a disabled item.") end @@ -25127,6 +28963,10 @@ function DemoWindowWidgetsTooltips() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTreeNodes() +------------------------------------------------------------------------------- + S.tn = { lines_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), selection_mask = 0, adv_flags = bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.SpanAvailWidth), align_label = false, use_dnd = false } @@ -25134,9 +28974,16 @@ function DemoWindowWidgetsTreeNodes() if not ImGui.TreeNode("Tree Nodes") then return end local s = S.tn local TN = ImGuiTreeNodeFlags + -- See see "Examples -> Property Editor" (ShowExampleAppPropertyEditor() function) for a fancier, data-driven tree. if ImGui.TreeNode("Basic Trees") then for i = 0, 4 do + -- Use SetNextItemOpen() so set the default state of a node to be open. We could + -- also use TreeNodeEx() with the ImGuiTreeNodeFlags.DefaultOpen flag to achieve the same thing! if i == 0 then ImGui.SetNextItemOpen(true, ImGuiCond.Once) end + + -- Here we use PushID() to generate a unique base ID, and then the "" used as TreeNode id won't conflict. + -- An alternative to using 'PushID() + TreeNode("", ...)' to generate a unique ID is to use 'TreeNode(i, ...)', + -- aka pass a number value to be hashed. The demo below uses that technique. Both are fine. ImGui.PushID(i) if ImGui.TreeNode("", "Child %d", i) then ImGui.Text("blah blah") @@ -25172,8 +29019,18 @@ function DemoWindowWidgetsTreeNodes() if ImGui.TreeNode("Selectable Nodes") then HelpMarker("Manually implemented selectable nodes.\nClick to select, Ctrl+Click to toggle, click on arrows or double-click to open.") + + -- Hold in 'selection_mask' a simple representation of what may be user-side selection state. + -- - You may retain selection state inside or outside your objects in whatever format you see fit. + -- You may use ImGuiSelectionBasicStorage which is conceptually close to a set<> of identifiers. + -- - We record which node was clicked and then apply selection at the end of the loop. + -- - This is a manual and simplified reimplementation of multi-selection, which the full + -- BeginMultiSelect() API implements better, but which is not trivial to wire for trees. local node_clicked_idx = -1 for node_n = 0, 5 do + -- Disable the default "open on single-click behavior" + set Selected flag according to our selection. + -- To alter selection we use if 'IsItemClicked() and not IsItemToggledOpen()', so clicking on an arrow doesn't alter selection. + -- In a BeginMultiSelect()/EndMultiSelect() we could use IsItemToggledSelection() but here we reimplement and use our own logic. local flags = bit32.bor(TN.OpenOnArrow, TN.OpenOnDoubleClick, TN.SpanAvailWidth) if bit32.band(s.selection_mask, bit32.lshift(1, node_n)) ~= 0 then flags = bit32.bor(flags, TN.Selected) end local is_open = ImGui.TreeNodeEx(node_n, flags, "Selectable Node %d", node_n) @@ -25184,10 +29041,11 @@ function DemoWindowWidgetsTreeNodes() end end if node_clicked_idx ~= -1 then + -- Update selection state (process outside of tree loop to avoid visual inconsistencies during the clicking frame) if ImGui.GetIO().KeyCtrl then - s.selection_mask = bit32.bxor(s.selection_mask, bit32.lshift(1, node_clicked_idx)) - else - s.selection_mask = bit32.lshift(1, node_clicked_idx) + s.selection_mask = bit32.bxor(s.selection_mask, bit32.lshift(1, node_clicked_idx)) -- Ctrl+Click to toggle + else -- if not (selection_mask & (1 << node_clicked_idx)) -- Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection + s.selection_mask = bit32.lshift(1, node_clicked_idx) -- Click to single-select end end ImGui.TreePop() @@ -25214,6 +29072,7 @@ function DemoWindowWidgetsTreeNodes() for node_n = 0, 5 do local node_flags = s.adv_flags if node_n < 3 then + -- Items 0..2 are Tree Node local is_open = ImGui.TreeNodeEx(node_n, node_flags, "Selectable Node %d", node_n) if s.use_dnd and ImGui.BeginDragDropSource() then ImGui.SetDragDropPayload("MY_TREENODE_PAYLOAD_TYPE", nil, 0) @@ -25221,6 +29080,7 @@ function DemoWindowWidgetsTreeNodes() ImGui.EndDragDropSource() end if node_n == 2 and bit32.band(s.adv_flags, TN.SpanLabelWidth) ~= 0 then + -- Item 2 has an additional inline button to help demonstrate SpanLabelWidth. ImGui.SameLine() if ImGui.SmallButton("button") then end end @@ -25231,7 +29091,10 @@ function DemoWindowWidgetsTreeNodes() ImGui.TreePop() end else - node_flags = bit32.bor(node_flags, TN.Leaf, TN.NoTreePushOnOpen) + -- Items 3..5 are Tree Leaves + -- The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can + -- use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). + node_flags = bit32.bor(node_flags, TN.Leaf, TN.NoTreePushOnOpen) -- ImGuiTreeNodeFlags.Bullet ImGui.TreeNodeEx(node_n, node_flags, "Selectable Leaf %d", node_n) if s.use_dnd and ImGui.BeginDragDropSource() then ImGui.SetDragDropPayload("MY_TREENODE_PAYLOAD_TYPE", nil, 0) @@ -25246,6 +29109,10 @@ function DemoWindowWidgetsTreeNodes() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsVerticalSliders() +------------------------------------------------------------------------------- + S.vs = { int_value = 0, values = { 0.0, 0.60, 0.35, 0.9, 0.70, 0.20, 0.0 }, values2 = { 0.20, 0.80, 0.40, 0.25 } } function DemoWindowWidgetsVerticalSliders() if not ImGui.TreeNode("Vertical Sliders") then return end @@ -25302,11 +29169,16 @@ function DemoWindowWidgetsVerticalSliders() ImGui.TreePop() end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - ShowExampleAppMainMenuBar() +-- - ShowExampleMenuFile() +------------------------------------------------------------------------------- S.menu = { enabled = true, f = 0.5, n = 0, b = true } +-- Note that shortcuts are currently provided for display only +-- (future version will add explicit flags to BeginMenu() to request processing shortcuts) function ShowExampleMenuFile() local s = S.menu ImGui.MenuItem("(demo menu)", nil, false, false) @@ -25356,12 +29228,14 @@ function ShowExampleMenuFile() end -- Here we demonstrate appending again to the "Options" menu (which we already created above) - if ImGui.BeginMenu("Options") then + -- Of course in this demo it is a little bit silly that this function calls BeginMenu("Options") twice. + -- In a real code-base using it would make senses to use this feature from very different code locations. + if ImGui.BeginMenu("Options") then -- <-- Append! _, s.b = ImGui.Checkbox("SomeOption", s.b) ImGui.EndMenu() end - if ImGui.BeginMenu("Disabled", false) then + if ImGui.BeginMenu("Disabled", false) then -- Disabled IM_ASSERT(false) end if ImGui.MenuItem("Checked", nil, true) then end @@ -25369,6 +29243,10 @@ function ShowExampleMenuFile() if ImGui.MenuItem("Quit", "Alt+F4") then end end +-- Demonstrate creating a "main" fullscreen menu bar and populating it. +-- Note the difference between BeginMainMenuBar() and BeginMenuBar(): +-- - BeginMenuBar() = menu-bar inside current window (which needs the ImGuiWindowFlags.MenuBar flag!) +-- - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it. function ShowExampleAppMainMenuBar() if ImGui.BeginMainMenuBar() then if ImGui.BeginMenu("File") then @@ -25377,7 +29255,7 @@ function ShowExampleAppMainMenuBar() end if ImGui.BeginMenu("Edit") then if ImGui.MenuItem("Undo", "Ctrl+Z") then end - if ImGui.MenuItem("Redo", "Ctrl+Y", false, false) then end + if ImGui.MenuItem("Redo", "Ctrl+Y", false, false) then end -- Disabled item ImGui.Separator() if ImGui.MenuItem("Cut", "Ctrl+X") then end if ImGui.MenuItem("Copy", "Ctrl+C") then end @@ -25388,9 +29266,12 @@ function ShowExampleAppMainMenuBar() end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Style Editor / ShowStyleEditor() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - ShowStyleSelector() +-- - ShowStyleEditor() +------------------------------------------------------------------------------- -- Deep copy of an ImGuiStyle (ImVec2/ImVec4 fields and Colors[] are copied by value) local function StyleCopy(dst, src) @@ -25415,7 +29296,10 @@ end local function ColorsEqual(a, b) return a[1] == b[1] and a[2] == b[2] and a[3] == b[3] and a[4] == b[4] end S.ss = { style_idx = -1 } +-- Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. function ImGui.ShowStyleSelector(label) + -- FIXME: This is a bit tricky to get right as style are functions, they don't register a name nor the fact that one is active. + -- So we keep track of last active one among our limited selection. local s = S.ss local style_names = { "Dark", "Light", "Classic" } local ret = false @@ -25444,13 +29328,19 @@ end S.se = { ref_saved_style = nil, init = true, output_dest = 0, output_only_modified = true, alpha_flags = 0, filter = nil } function ImGui.ShowStyleEditor(ref) + -- You can pass in a reference ImGuiStyle structure to compare to, revert to and save to + -- (without a reference style, we will use one compared locally as a reference) local se = S.se local style = ImGui.GetStyle() if se.ref_saved_style == nil then se.ref_saved_style = {} end + + -- Default to using internal storage as reference if se.init and ref == nil then StyleCopy(se.ref_saved_style, style) end se.init = false if ref == nil then ref = se.ref_saved_style end + -- The logic behind dynamically changing 'max_border_size' is to not encourage people to increase border size too much: it'll likely reveal lots of subtle rendering artifacts and this isn't a priority right now. + -- Note that _MainScale is currently internal PLEASE DO NOT USE IN YOUR CODE. local default_border_size = math.floor(style._MainScale or 1.0) local max_border_size = math.max(default_border_size, 2.0) local function SF(name, mn, mx, fmt) if style[name] ~= nil then style[name] = ImGui.SliderFloat(name, style[name], mn, mx, fmt or "%.0f") end end @@ -25459,6 +29349,7 @@ function ImGui.ShowStyleEditor(ref) ImGui.PushItemWidth(ImGui.GetWindowWidth() * 0.50) + -- General ImGui.SeparatorText("General") if bit32.band(ImGui.GetIO().BackendFlags, ImGuiBackendFlags.RendererHasTextures) == 0 then ImGui.BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!") @@ -25470,7 +29361,7 @@ function ImGui.ShowStyleEditor(ref) if ImGui.ShowFontSelector then ImGui.ShowFontSelector("Fonts##Selector") end local changed style.FontSizeBase, changed = ImGui.DragFloat("FontSizeBase", style.FontSizeBase, 0.20, 5.0, 100.0, "%.0f") - if changed then style._NextFrameFontSizeBase = style.FontSizeBase end + if changed then style._NextFrameFontSizeBase = style.FontSizeBase end -- FIXME: Temporary hack until we finish remaining work. ImGui.SameLine(0.0, 0.0); ImGui.Text(" (out %.2f)", ImGui.GetFontSize()) style.FontScaleMain = ImGui.DragFloat("FontScaleMain", style.FontScaleMain, 0.02, 0.5, 4.0) ImGui.BeginDisabled(ImGui.GetIO().ConfigDpiScaleFonts == true) @@ -25478,8 +29369,9 @@ function ImGui.ShowStyleEditor(ref) ImGui.SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten.") ImGui.EndDisabled() + -- Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0 or 1.0) style.FrameRounding, changed = ImGui.SliderFloat("FrameRounding", style.FrameRounding, 0.0, 12.0, "%.0f") - if changed then style.GrabRounding = style.FrameRounding end + if changed then style.GrabRounding = style.FrameRounding end -- Make GrabRounding always the same value as FrameRounding local p, border p, border = ImGui.Checkbox("WindowBorder", style.WindowBorderSize > 0.0); if p then style.WindowBorderSize = border and default_border_size or 0.0 end ImGui.SameLine() @@ -25487,6 +29379,7 @@ function ImGui.ShowStyleEditor(ref) ImGui.SameLine() p, border = ImGui.Checkbox("PopupBorder", style.PopupBorderSize > 0.0); if p then style.PopupBorderSize = border and default_border_size or 0.0 end + -- Save/Revert button if ImGui.Button("Save Ref") then StyleCopy(se.ref_saved_style, style); if ref ~= se.ref_saved_style then StyleCopy(ref, style) end end ImGui.SameLine() if ImGui.Button("Revert Ref") then StyleCopy(style, ref) end @@ -25508,6 +29401,7 @@ function ImGui.ShowStyleEditor(ref) ImGui.SeparatorText("Rounding") SF("WindowRounding", 0.0, 12.0); SF("ChildRounding", 0.0, 12.0); SF("FrameRounding", 0.0, 12.0) SF("PopupRounding", 0.0, 12.0); SF("GrabRounding", 0.0, 12.0); SF("MenuItemRounding", 0.0, 12.0) + -- NB: SelectableRounding is intentionally NOT made visible here. We don't want to encourage people using that. ImGui.SeparatorText("Scrollbar") SF("ScrollbarSize", 1.0, 20.0); SF("ScrollbarRounding", 0.0, 12.0); SF("ScrollbarPadding", 0.0, 10.0) @@ -25559,6 +29453,7 @@ function ImGui.ShowStyleEditor(ref) SF("LogSliderDeadzone", 0.0, 12.0); SF("ImageRounding", 0.0, 12.0); SF("ImageBorderSize", 0.0, max_border_size) ImGui.SeparatorText("Docking") + -- SetCursorPosX(GetCursorPosX() + CalcItemWidth() - GetFrameHeight()) _, style.DockingNodeHasCloseButton = ImGui.Checkbox("DockingNodeHasCloseButton", style.DockingNodeHasCloseButton) SF("DockingSeparatorSize", 0.0, 12.0) @@ -25628,6 +29523,9 @@ function ImGui.ShowStyleEditor(ref) end ImGui.ColorEdit4("##color", style.Colors[i], bit32.bor(CE.AlphaBar, se.alpha_flags)) if not ColorsEqual(style.Colors[i], ref.Colors[i]) then + -- Tips: in a real user application, you may want to merge and use an icon font into the main font, + -- so instead of "Save"/"Revert" you'd use icons! + -- Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient! ImGui.SameLine(0.0, style.ItemInnerSpacing.x); if ImGui.Button("Save") then ImVec4_Copy(ref.Colors[i], style.Colors[i]) end ImGui.SameLine(0.0, style.ItemInnerSpacing.x); if ImGui.Button("Revert") then ImVec4_Copy(style.Colors[i], ref.Colors[i]) end end @@ -25664,6 +29562,7 @@ function ImGui.ShowStyleEditor(ref) if curve_err < 0.10 then curve_err = 0.10 end style.CurveTessellationTol = curve_err * curve_err + -- When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles. style.CircleTessellationMaxError = ImGui.DragFloat("Circle Tessellation Max Error", style.CircleTessellationMaxError, 0.005, 0.10, 5.0, "%.2f", ImGuiSliderFlags.AlwaysClamp) local show_samples = ImGui.IsItemActive() if show_samples then ImGui.SetNextWindowPos(ImGui.GetCursorScreenPos()) end @@ -25676,6 +29575,8 @@ function ImGui.ShowStyleEditor(ref) local RAD_MIN, RAD_MAX = 5.0, 70.0 local rad = RAD_MIN + (RAD_MAX - RAD_MIN) * n / (8.0 - 1.0) ImGui.BeginGroup() + + -- N is not always exact here due to how PathArcTo() function work internally ImGui.Text("R: %.f\nN: %d", rad, draw_list:_CalcCircleAutoSegmentCount(rad)) local canvas_width = math.max(min_widget_width, rad * 2.0) local offset_x = math.floor(canvas_width * 0.5) @@ -25683,6 +29584,11 @@ function ImGui.ShowStyleEditor(ref) local p1 = ImGui.GetCursorScreenPos() draw_list:AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, ImGui.GetColorU32(ImGuiCol.Text)) ImGui.Dummy(ImVec2(canvas_width, RAD_MAX * 2)) + + -- local p2 = ImGui.GetCursorScreenPos() + -- draw_list:AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, ImGui.GetColorU32(ImGuiCol.Text)) + -- ImGui.Dummy(ImVec2(canvas_width, RAD_MAX * 2)) + ImGui.EndGroup() ImGui.SameLine() end @@ -25690,7 +29596,7 @@ function ImGui.ShowStyleEditor(ref) end ImGui.SameLine() HelpMarker("When drawing circle primitives with \"num_segments == 0\" tessellation will be calculated automatically.") - style.Alpha = ImGui.DragFloat("Global Alpha", style.Alpha, 0.005, 0.20, 1.0, "%.2f") + style.Alpha = ImGui.DragFloat("Global Alpha", style.Alpha, 0.005, 0.20, 1.0, "%.2f") -- Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. style.DisabledAlpha = ImGui.DragFloat("Disabled Alpha", style.DisabledAlpha, 0.005, 0.0, 1.0, "%.2f") ImGui.SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha).") ImGui.PopItemWidth() @@ -25706,9 +29612,10 @@ do --[[ About window ]] -- Demo tools: ShowAboutWindow(), ShowFontAtlas(), ShowFontSelector(), ShowDebugLogWindow(), ShowIDStackToolWindow() local _ ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] About Window / ShowAboutWindow() ----------------------------------------------------------------- +-- Access from Dear ImGui Demo -> Tools -> About +------------------------------------------------------------------------------- local show_config_info = false function ImGui.ShowAboutWindow(p_open) @@ -25739,7 +29646,7 @@ function ImGui.ShowAboutWindow(p_open) if copy_to_clipboard then ImGui.LogToClipboard() ImGui.LogText("// (Copy from the next line. Keep the ``` markers for formatting.)\n") - ImGui.LogText("```cpp\n") + ImGui.LogText("```cpp\n") -- Back quotes will make text appears without formatting when pasting on GitHub end ImGui.Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM) ImGui.Separator() @@ -25797,12 +29704,34 @@ end __FILES['imgui_draw.lua'] = function() --- Dear ImGui WIP --- (Draw Code) +-- (drawing and font code) -FONT_ATLAS_DEFAULT_TEX_DATA_W = 122 +-- +-- Index of this file: +-- +-- [SECTION] STB libraries implementation +-- [SECTION] Style functions +-- [SECTION] ImDrawList +-- [SECTION] ImTriangulator, ImDrawList concave polygon fill +-- [SECTION] ImDrawListSplitter +-- [SECTION] ImDrawData +-- [SECTION] Helpers ShadeVertsXXX functions +-- [SECTION] ImFontConfig +-- [SECTION] ImFontAtlas, ImFontAtlasBuilder +-- [SECTION] ImFontAtlas: backend for stb_truetype +-- [SECTION] ImFontAtlas: glyph ranges helpers +-- [SECTION] ImFontGlyphRangesBuilder +-- [SECTION] ImFontBaked, ImFont +-- [SECTION] ImGui Internal Render Helpers +-- [SECTION] Decompression code +-- [SECTION] Default font data (ProggyClean.ttf) +-- [SECTION] Default font data (ProggyForever.ttf) +-- + +FONT_ATLAS_DEFAULT_TEX_DATA_W = 122 -- Actual texture will be 2 times that + 1 spacing. FONT_ATLAS_DEFAULT_TEX_DATA_H = 27 -local IM_DRAWLIST_TEX_LINES_WIDTH_MAX = 32 +local IM_DRAWLIST_TEX_LINES_WIDTH_MAX = 32 -- The maximum line width to bake anti-aliased textures for. local writef64, writeu32, readf64, readu32 = buffer.writef64, buffer.writeu32, buffer.readf64, buffer.readu32 -- Write vertex i (1-based) of a VtxBuffer.Buf @@ -25812,8 +29741,8 @@ local function WV(b, i, x, y, u, v, col) end local function WVP(b, i, p, uv, col) WV(b, i, p.x, p.y, uv.x, uv.y, col) end -local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE +local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- ((ImU16)-1) +local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE -- ((ImU16)-2) --- @param str string --- @return table @@ -25833,7 +29762,9 @@ local function write_u32(buf, base, u32) buf[base + 3] = bit32.band(bit32.rshift(u32, 24), 0xFF) end ---- Original ImGui pixel art! +-- A work of art lies ahead! (. = white layer, X = black layer, others are blank) +-- The 2x2 white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes. +-- (This is used when io.MouseDrawCursor = true) local FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS = str_to_table( "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX - XX XX " .. "..- -X.....X- X.X - X.X -X.....X - X.....X- X..X -X..X X..X" .. @@ -25881,15 +29812,19 @@ local FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA = { local MT = ImGui.GetMetatables() +------------------------------------------------------------------------------- +-- [SECTION] STB libraries implementation (for stb_truetype and stb_rect_pack) +------------------------------------------------------------------------------- + --- @module "imstb_rectpack" local stbrp = IM_INCLUDE("imstb_rectpack.lua") --- @module "imstb_truetype" local stbtt = IM_INCLUDE("imstb_truetype.lua") ---------------------------------------------------------------------------------------- --- [SECTION] STYLE FUNCTIONS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Style functions +------------------------------------------------------------------------------- --- @param a ImVec4 --- @param b ImVec4 @@ -25950,8 +29885,8 @@ function ImGui.StyleColorsDark(dst) colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00) colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00) colors[ImGuiCol.TableHeaderBg] = ImVec4(0.19, 0.19, 0.20, 1.00) - colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.35, 1.00) - colors[ImGuiCol.TableBorderLight] = ImVec4(0.23, 0.23, 0.25, 1.00) + colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.35, 1.00) -- Prefer using Alpha=1.0 here + colors[ImGuiCol.TableBorderLight] = ImVec4(0.23, 0.23, 0.25, 1.00) -- Prefer using Alpha=1.0 here colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00) colors[ImGuiCol.TableRowBgAlt] = ImVec4(1.00, 1.00, 1.00, 0.06) colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive] @@ -26020,8 +29955,8 @@ function ImGui.StyleColorsClassic(dst) colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00) colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00) colors[ImGuiCol.TableHeaderBg] = ImVec4(0.27, 0.27, 0.38, 1.00) - colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.45, 1.00) - colors[ImGuiCol.TableBorderLight] = ImVec4(0.26, 0.26, 0.28, 1.00) + colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.45, 1.00) -- Prefer using Alpha=1.0 here + colors[ImGuiCol.TableBorderLight] = ImVec4(0.26, 0.26, 0.28, 1.00) -- Prefer using Alpha=1.0 here colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00) colors[ImGuiCol.TableRowBgAlt] = ImVec4(1.00, 1.00, 1.00, 0.07) colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive] @@ -26091,8 +30026,8 @@ function ImGui.StyleColorsLight(dst) colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00) colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.45, 0.00, 1.00) colors[ImGuiCol.TableHeaderBg] = ImVec4(0.78, 0.87, 0.98, 1.00) - colors[ImGuiCol.TableBorderStrong] = ImVec4(0.57, 0.57, 0.64, 1.00) - colors[ImGuiCol.TableBorderLight] = ImVec4(0.68, 0.68, 0.74, 1.00) + colors[ImGuiCol.TableBorderStrong] = ImVec4(0.57, 0.57, 0.64, 1.00) -- Prefer using Alpha=1.0 here + colors[ImGuiCol.TableBorderLight] = ImVec4(0.68, 0.68, 0.74, 1.00) -- Prefer using Alpha=1.0 here colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00) colors[ImGuiCol.TableRowBgAlt] = ImVec4(0.30, 0.30, 0.30, 0.09) colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive] @@ -26107,6 +30042,11 @@ function ImGui.StyleColorsLight(dst) colors[ImGuiCol.ModalWindowDimBg] = ImVec4(0.20, 0.20, 0.20, 0.35) end +------------------------------------------------------------------------------- +-- [SECTION] Helpers ShadeVertsXXX functions +------------------------------------------------------------------------------- + +-- Generic linear color gradient, write to RGB fields, leave A untouched. --- @param draw_list ImDrawList --- @param vert_start_idx int --- @param vert_end_idx int @@ -26239,10 +30179,102 @@ local ImTextClassifierSetCharClassFromStr local ImTextureDataGetFormatBytesPerPixel +------------------------------------------------------------------------------- +-- [SECTION] ImFontAtlas, ImFontAtlasBuilder +------------------------------------------------------------------------------- +-- - Default texture data encoded in ASCII +-- - ImFontAtlas() +-- - ImFontAtlas:Clear() +-- - ImFontAtlas:ClearFonts() +-- - ImFontAtlas:ClearInputData() +-- - ImFontAtlas:ClearTexData() +-- - ImFontAtlas:CompactCache() +-- - ImFontAtlas:SetFontLoader() +------------------------------------------------------------------------------- +-- - ImFontAtlasUpdateNewFrame() +-- - ImFontAtlasTextureBlockConvert() +-- - ImFontAtlasTextureBlockPostProcess() +-- - ImFontAtlasTextureBlockPostProcessMultiply() +-- - ImFontAtlasTextureBlockFill() +-- - ImFontAtlasTextureBlockCopy() +-- - ImFontAtlasTextureBlockQueueUpload() +------------------------------------------------------------------------------- +-- - ImFontAtlas:GetTexDataAsAlpha8() [legacy] +-- - ImFontAtlas:GetTexDataAsRGBA32() [legacy] +-- - ImFontAtlas:Build() [legacy] +------------------------------------------------------------------------------- +-- - ImFontAtlas:AddFont() +-- - ImFontAtlas:AddFontDefault() +-- - ImFontAtlas:AddFontDefaultBitmap() +-- - ImFontAtlas:AddFontDefaultVector() +-- - ImFontAtlas:AddFontFromFileTTF() +-- - ImFontAtlas:AddFontFromMemoryTTF() +-- - ImFontAtlas:AddFontFromMemoryCompressedTTF() +-- - ImFontAtlas:AddFontFromMemoryCompressedBase85TTF() +-- - ImFontAtlas:RemoveFont() +-- - ImFontAtlasBuildNotifySetFont() +------------------------------------------------------------------------------- +-- - ImFontAtlas:AddCustomRect() +-- - ImFontAtlas:RemoveCustomRect() +-- - ImFontAtlas:GetCustomRect() +-- - ImFontAtlas:AddCustomRectFontGlyph() [legacy] +-- - ImFontAtlas:AddCustomRectFontGlyphForSize() [legacy] +-- - ImFontAtlasGetMouseCursorTexData() +------------------------------------------------------------------------------- +-- - ImFontAtlasBuildMain() +-- - ImFontAtlasBuildSetupFontLoader() +-- - ImFontAtlasBuildPreloadAllGlyphRanges() +-- - ImFontAtlasBuildUpdatePointers() +-- - ImFontAtlasBuildRenderBitmapFromString() +-- - ImFontAtlasBuildAddFont() +-- - ImFontAtlasBuildSetupFontBakedEllipsis() +-- - ImFontAtlasBuildSetupFontBakedBlanks() +-- - ImFontAtlasBuildSetupFontBakedFallback() +-- - ImFontAtlasBuildSetupFontSpecialGlyphs() +-- - ImFontAtlasBuildDiscardBakes() +-- - ImFontAtlasBuildDiscardFontBakedGlyph() +-- - ImFontAtlasBuildDiscardFontBaked() +-- - ImFontAtlasBuildDiscardFontBakes() +------------------------------------------------------------------------------- +-- - ImFontAtlasAddDrawListSharedData() +-- - ImFontAtlasRemoveDrawListSharedData() +-- - ImFontAtlasUpdateDrawListsTextures() +-- - ImFontAtlasUpdateDrawListsSharedData() +------------------------------------------------------------------------------- +-- - ImFontAtlasBuildSetTexture() +-- - ImFontAtlasBuildUpdateTexData() +-- - ImFontAtlasTextureAdd() +-- - ImFontAtlasTextureRepack() +-- - ImFontAtlasTextureGrow() +-- - ImFontAtlasTextureMakeSpace() +-- - ImFontAtlasTextureGetSizeEstimate() +-- - ImFontAtlasBuildClear() +-- - ImFontAtlasTextureCompact() +-- - ImFontAtlasBuildInit() +-- - ImFontAtlasBuildDestroy() +------------------------------------------------------------------------------- +-- - ImFontAtlasPackInit() +-- - ImFontAtlasPackAllocRectEntry() +-- - ImFontAtlasPackReuseRectEntry() +-- - ImFontAtlasPackDiscardRect() +-- - ImFontAtlasPackAddRect() +-- - ImFontAtlasPackGetRect() +------------------------------------------------------------------------------- +-- - ImFontBaked_BuildGrowIndex() +-- - ImFontBaked_BuildLoadGlyph() +-- - ImFontBaked_BuildLoadGlyphAdvanceX() +-- - ImFontAtlasDebugLogTextureRequests() +------------------------------------------------------------------------------- +-- - ImFontAtlasGetFontLoaderForStbTruetype() +------------------------------------------------------------------------------- + +-- You probably should not call this directly. It is not well specified. +-- If you want to replace all your fonts mid-frame, most likely you should instead call ClearFonts() then load the new fonts. +-- Calling this mid-frame will discard the CPU-side copy of the texture data which is generally unreliable as you may have textures queued for creation or updates. function MT.ImFontAtlas:Clear() IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlas:Clear()") local backup_renderer_has_textures = self.RendererHasTextures - self.RendererHasTextures = false + self.RendererHasTextures = false -- Full Clear() is supported, but ClearTexData() only isn't. self:ClearFonts() self:ClearTexData() self.RendererHasTextures = backup_renderer_has_textures @@ -26262,12 +30294,14 @@ function MT.ImFontAtlas:ClearInputData() ImFontAtlasFontDestroySourceData(self, font_cfg) end for _, font in self.Fonts:iter() do + -- When clearing this we lose access to the font name and other information used to build the font. font.Sources:clear() font.Flags = bit32.bor(font.Flags, ImFontFlags.NoLoadGlyphs) end self.Sources:clear() end +-- Clear CPU-side copy of the texture data. function MT.ImFontAtlas:ClearTexData() IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") IM_ASSERT(self.RendererHasTextures == false, "Not supported for dynamic atlases, but you may call Clear().") @@ -26275,6 +30309,7 @@ function MT.ImFontAtlas:ClearTexData() for _, tex in self.TexList:iter() do tex:DestroyPixels() end + --self.Locked = true -- Hoped to be able to lock this down but some reload patterns may not be happy with it. end function MT.ImFontAtlas:CompactCache() @@ -26282,6 +30317,7 @@ function MT.ImFontAtlas:CompactCache() end function MT.ImFontAtlas:ClearFonts() + -- FIXME-NEWATLAS: Illegal to remove currently bound font. IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlas:ClearFonts()") IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") @@ -26312,25 +30348,34 @@ function ImTextureDataUpdateNewFrame(tex) tex.UpdateRect.w = 0 tex.UpdateRect.h = 0 end + -- 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. if (tex.WantDestroyNextFrame and tex.Status ~= ImTextureStatus.Destroyed and tex.Status ~= ImTextureStatus.WantDestroy) then IM_ASSERT(tex.Status == ImTextureStatus.OK or tex.Status == ImTextureStatus.WantCreate or tex.Status == ImTextureStatus.WantUpdates) tex.Status = ImTextureStatus.WantDestroy end + -- If a texture has never reached the backend, they don't need to know about it. + -- (note: backends between 1.92.0 and 1.92.4 could set an already destroyed texture to ImTextureStatus.WantDestroy + -- when invalidating graphics objects twice, which would previously remove it from the list and crash.) if (tex.Status == ImTextureStatus.WantDestroy and tex.TexID == ImTextureID_Invalid and tex.BackendUserData == nil and tex.QueueUserData == nil) then tex.Status = ImTextureStatus.Destroyed end + -- Process texture being destroyed if (tex.Status == ImTextureStatus.Destroyed) then IM_ASSERT(tex.TexID == ImTextureID_Invalid and tex.BackendUserData == nil, "Backend set texture Status to Destroyed but did not clear TexID/BackendUserData!") IM_ASSERT(tex.QueueUserData == nil, "Texture queue set Status to Destroyed but did not clear QueueUserData!") if (tex.WantDestroyNextFrame) then - remove_from_list = true + remove_from_list = true -- Destroy was scheduled by us else - tex.Status = ImTextureStatus.WantCreate + tex.Status = ImTextureStatus.WantCreate -- Destroy was done was backend: recreate it (e.g. freed resources mid-run) end end + -- 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) then tex.UnusedFrames = tex.UnusedFrames + 1 end @@ -26338,15 +30383,24 @@ function ImTextureDataUpdateNewFrame(tex) return remove_from_list end +-- 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. --- @param atlas ImFontAtlas --- @param frame_count int --- @param renderer_has_textures any function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures) - IM_ASSERT(atlas.Builder == nil or atlas.Builder.FrameCount < frame_count) + IM_ASSERT(atlas.Builder == nil or atlas.Builder.FrameCount < frame_count) -- Protection against being called twice. atlas.RendererHasTextures = renderer_has_textures + -- Update texture status and discard old textures. + -- (we do this first thing to handle an edge case: if user mistakenly calls ClearFonts()+SetStatus(OK) during + -- rendering, it would ImFontAtlasBuildMain() rebuilding before tex.Updates[] gets a chance to be cleared) + -- (if somehow we need to move this back lower in the function, we could manually call the code to clear Updates[]). local tex_n = 1 while tex_n <= atlas.TexList.Size do + -- Update and remove if requested local tex = atlas.TexList.Data[tex_n] if (tex.Status == ImTextureStatus.WantCreate and atlas.RendererHasTextures) then @@ -26365,13 +30419,14 @@ function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures) tex_n = tex_n + 1 end + -- Check that font atlas was built or backend support texture reload in which case we can build now if (atlas.RendererHasTextures) then atlas.TexIsBuilt = true - if (atlas.Builder == nil) then + if (atlas.Builder == nil) then -- This will only happen if fonts were not already loaded. ImFontAtlasBuildMain(atlas) end end - + -- Legacy backend if (not atlas.RendererHasTextures) then 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().") end @@ -26379,12 +30434,15 @@ function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures) 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().") end + -- Clear BakedCurrent cache, this is important because it ensure the uncached path gets taken once. + -- We also rely on ImFontBaked pointers never crossing frames. local builder = atlas.Builder builder.FrameCount = frame_count for _, font in atlas.Fonts:iter() do font.LastBaked = nil end + -- Garbage collect BakedPool if builder.BakedDiscardedCount > 0 then local dst_n = 1 @@ -26465,8 +30523,11 @@ function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixe end end +-- Source buffer may be written to (used for in-place mods). +-- Post-process hooks may eventually be added here. --- @param data ImFontAtlasPostProcessData function ImFontAtlasTextureBlockPostProcess(data) + -- Multiply operator (legacy) if data.FontSrc.RasterizerMultiply ~= 1.0 then ImFontAtlasTextureBlockPostProcessMultiply(data, data.FontSrc.RasterizerMultiply) end @@ -26507,6 +30568,7 @@ function ImFontAtlasTextureBlockPostProcessMultiply(data, multiply_factor) end end +-- Copy block from one texture to another --- @param src_tex ImTextureData --- @param src_x int --- @param src_y int @@ -26529,6 +30591,7 @@ function ImFontAtlasTextureBlockCopy(src_tex, src_x, src_y, dst_tex, dst_x, dst_ end end +-- Queue texture block update for renderer backend --- @param tex ImTextureData --- @param x int --- @param y int @@ -26550,6 +30613,7 @@ local function ImTextureDataQueueUpload(tex, x, y, w, h) tex.UsedRect.w = (ImMax(tex.UsedRect.x + tex.UsedRect.w, req.x + req.w) - tex.UsedRect.x) -- (unsigned short) tex.UsedRect.h = (ImMax(tex.UsedRect.y + tex.UsedRect.h, req.y + req.h) - tex.UsedRect.y) -- (unsigned short) + -- No need to queue if status is == ImTextureStatus.WantCreate if (tex.Status == ImTextureStatus.OK or tex.Status == ImTextureStatus.WantUpdates) then tex.Status = ImTextureStatus.WantUpdates tex.Updates:push_back(req) @@ -26567,6 +30631,7 @@ function ImFontAtlasTextureBlockQueueUpload(atlas, tex, x, y, w, h) atlas.TexIsBuilt = false end +-- Copy to texture, post-process and queue update for backend --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @param src ImFontConfig @@ -26587,6 +30652,8 @@ local function ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, glyph, r, s end local function ImFontAtlasBuildGetOversampleFactors(src, baked) + -- (Only used by stb_truetype builder) + -- Automatically disable horizontal oversampling over size 36 local raster_size = baked.Size * baked.RasterizerDensity * src.RasterizerDensity local out_oversample_h if src.OversampleH ~= 0 then @@ -26600,6 +30667,7 @@ local function ImFontAtlasBuildGetOversampleFactors(src, baked) return out_oversample_h, out_oversample_v end +-- use unused_frames==0 to discard everything. local function ImFontAtlasBuildDiscardBakes(atlas, unused_frames) local builder = atlas.Builder @@ -26620,6 +30688,7 @@ local function ImFontAtlasBuildDiscardBakes(atlas, unused_frames) end end +-- Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData --- @param atlas ImFontAtlas --- @param data ImDrawListSharedData function ImFontAtlasAddDrawListSharedData(atlas, data) @@ -26646,7 +30715,16 @@ local function ImFontAtlasTextureRepack(atlas, w, h) new_tex.UseColors = old_tex.UseColors IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d", old_tex.UniqueID, old_tex.Width, old_tex.Height, new_tex.UniqueID, new_tex.Width, new_tex.Height) + --for baked_n = 1, builder.BakedPool.Size do + -- IMGUI_DEBUG_LOG_FONT("[font] - Baked %.2fpx, %d glyphs, want_destroy=%d", builder.BakedPool[baked_n].FontSize, builder.BakedPool[baked_n].Glyphs.Size, builder.BakedPool[baked_n].WantDestroy) + --end + --IMGUI_DEBUG_LOG_FONT("[font] - Old packed rects: %d, area %d px", 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) local old_rects = ImVector() local old_index = builder.RectsIndex:copy() @@ -26665,13 +30743,15 @@ local function ImFontAtlasTextureRepack(atlas, w, h) local new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, index_entry) if new_r_id == ImFontAtlasRectId_Invalid then + -- 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.", new_tex.UniqueID) new_tex.WantDestroyNextFrame = true builder.Rects:swap(old_rects) builder.RectsIndex = old_index ImFontAtlasBuildSetTexture(atlas, old_tex) - ImFontAtlasTextureGrow(atlas, w, h) + ImFontAtlasTextureGrow(atlas, w, h) -- Recurse return end @@ -26687,6 +30767,7 @@ local function ImFontAtlasTextureRepack(atlas, w, h) builder.RectsDiscardedCount = 0 builder.RectsDiscardedSurface = 0 + -- Patch glyphs UV for baked_n = 1, builder.BakedPool.Size do for _, glyph in builder.BakedPool[baked_n].Glyphs:iter() do if (glyph.PackId ~= ImFontAtlasRectId_Invalid) then @@ -26699,14 +30780,16 @@ local function ImFontAtlasTextureRepack(atlas, w, h) end end + -- Update other cached UV ImFontAtlasBuildUpdateTexData(atlas) builder.LockDisableResize = false ImFontAtlasUpdateDrawListsSharedData(atlas) - -- ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack"); + --ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack") end function ImFontAtlasTextureGrow(atlas, old_tex_w, old_tex_h) + --ImFontAtlasDebugWriteTexToDisk(atlas.TexData, "Before Grow") local builder = atlas.Builder old_tex_w = old_tex_w or -1 @@ -26719,12 +30802,18 @@ function ImFontAtlasTextureGrow(atlas, old_tex_w, old_tex_h) old_tex_h = atlas.TexData.Height end + -- 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) and ImIsPowerOfTwo(old_tex_h)) IM_ASSERT(ImIsPowerOfTwo(atlas.TexMinWidth) and ImIsPowerOfTwo(atlas.TexMaxWidth) and ImIsPowerOfTwo(atlas.TexMinHeight) and 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. local new_tex_w = (old_tex_h <= old_tex_w) and old_tex_w or old_tex_w * 2 local new_tex_h = (old_tex_h <= old_tex_w) and old_tex_h * 2 or old_tex_h + -- Handle minimum size first (for pathologically large packed rects) local 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)) @@ -26739,9 +30828,12 @@ end --- @param atlas ImFontAtlas local function ImFontAtlasTextureMakeSpace(atlas) + -- Can some baked contents be ditched? + --IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlasBuildMakeSpace()") local builder = atlas.Builder ImFontAtlasBuildDiscardBakes(atlas, 2) + -- Currently using a heuristic for repack without growing. if (builder.RectsDiscardedSurface < builder.RectsPackedSurface * 0.20) then ImFontAtlasTextureGrow(atlas) else @@ -26749,6 +30841,7 @@ local function ImFontAtlasTextureMakeSpace(atlas) end end +-- This is essentially a free-list pattern, it may be nice to wrap it into a dedicated type. --- @param atlas ImFontAtlas --- @param rect_idx ImFontAtlasRectId local function ImFontAtlasPackAllocRectEntry(atlas, rect_idx) @@ -26762,7 +30855,7 @@ local function ImFontAtlasPackAllocRectEntry(atlas, rect_idx) else index_idx = builder.RectsIndexFreeListStart index_entry = builder.RectsIndex[index_idx + 1] - IM_ASSERT(index_entry.IsUsed == false and index_entry.Generation > 0) + IM_ASSERT(index_entry.IsUsed == false and index_entry.Generation > 0) -- Generation is incremented during DiscardRect builder.RectsIndexFreeListStart = index_entry.TargetIndex end @@ -26772,6 +30865,7 @@ local function ImFontAtlasPackAllocRectEntry(atlas, rect_idx) return ImFontAtlasRectId_Make(index_idx, index_entry.Generation) end +-- Overwrite existing entry --- @param atlas ImFontAtlas --- @param index_entry ImFontAtlasRectEntry local function ImFontAtlasPackReuseRectEntry(atlas, index_entry) @@ -26781,6 +30875,7 @@ local function ImFontAtlasPackReuseRectEntry(atlas, index_entry) return ImFontAtlasRectId_Make(index_idx, index_entry.Generation) end +-- This is expected to be called in batches and followed by a repack --- @param atlas ImFontAtlas --- @param id ImFontAtlasRectId function ImFontAtlasPackDiscardRect(atlas, id) @@ -26799,16 +30894,18 @@ function ImFontAtlasPackDiscardRect(atlas, id) index_entry.TargetIndex = builder.RectsIndexFreeListStart index_entry.Generation = index_entry.Generation + 1 if (index_entry.Generation == 0) then - index_entry.Generation = index_entry.Generation + 1 + index_entry.Generation = index_entry.Generation + 1 -- Keep non-zero on overflow end local pack_padding = atlas.TexGlyphPadding builder.RectsIndexFreeListStart = index_idx builder.RectsDiscardedCount = builder.RectsDiscardedCount + 1 builder.RectsDiscardedSurface = builder.RectsDiscardedSurface + ((rect.w + pack_padding) * (rect.h + pack_padding)) - rect.w = 0 rect.h = 0 + rect.w = 0 rect.h = 0 -- Clear rectangle so it won't be packed again end +-- 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 function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) IM_ASSERT(w > 0 and w <= 0xFFFF) IM_ASSERT(h > 0 and h <= 0xFFFF) @@ -26818,8 +30915,10 @@ function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) builder.MaxRectSize.x = ImMax(builder.MaxRectSize.x, w) builder.MaxRectSize.y = ImMax(builder.MaxRectSize.y, h) + -- Pack local r = ImTextureRect(0, 0, w, h) for attempts_remaining = 3, 0, -1 do + -- Try packing local pack_r = stbrp.rect() pack_r.w = w + pack_padding pack_r.h = h + pack_padding @@ -26830,12 +30929,14 @@ function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) break end + -- If we ran out of attempts, return fallback if (attempts_remaining == 0 or builder.LockDisableResize) then IMGUI_DEBUG_LOG_FONT("[font] Failed packing %dx%d rectangle. Returning fallback.", w, h) return ImFontAtlasRectId_Invalid end + -- Resize or repack atlas! (this should be a rare event) ImFontAtlasTextureMakeSpace(atlas) end @@ -26846,12 +30947,13 @@ function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) builder.Rects:push_back(r) if (overwrite_entry ~= nil) then - return ImFontAtlasPackReuseRectEntry(atlas, overwrite_entry) + 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) end end +-- Generally for non-user facing functions: assert on invalid ID. --- @param atlas ImFontAtlas --- @param id ImFontAtlasRectId --- @return ImTextureRect @@ -26866,6 +30968,8 @@ function ImFontAtlasPackGetRect(atlas, id) return builder.Rects.Data[index_entry.TargetIndex + 1] end +-- For user-facing functions: return nil on invalid ID. +-- Important: return value is valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous rects. --- @param atlas ImFontAtlas --- @param id ImFontAtlasRectId function ImFontAtlasPackGetRectSafe(atlas, id) @@ -26888,6 +30992,8 @@ function ImFontAtlasPackGetRectSafe(atlas, id) return builder.Rects.Data[index_entry.TargetIndex + 1] end +-- 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. --- @param src ImFontConfig --- @param codepoint ImWchar --- @return bool @@ -26918,6 +31024,13 @@ function ImFontBaked_BuildGrowIndex(baked, new_size) baked.IndexLookup:resize(new_size, IM_FONTGLYPH_INDEX_UNUSED) end +------------------------------------------------------------------------------- +-- [SECTION] ImFontAtlas: backend for stb_truetype +------------------------------------------------------------------------------- +-- (imstb_truetype.lua in included near the top of this file) +------------------------------------------------------------------------------- + +-- One for each ConfigData --- @class ImGui_ImplStbTrueType_FontSrcData --- @field FontInfo stbtt_fontinfo --- @field ScaleFactor float @@ -26945,6 +31058,7 @@ local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) local bd_font_data = ImGui_ImplStbTrueType_FontSrcData() IM_ASSERT(src.FontLoaderData == nil) + -- Initialize helper structure for font loading and verify that the TTF/OTF data is correct local font_offset = stbtt.GetFontOffsetForIndex(src.FontData, src.FontNo) if font_offset < 0 then bd_font_data = nil @@ -26965,7 +31079,7 @@ local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) bd_font_data.ScaleFactor = stbtt.ScaleForPixelHeight(bd_font_data.FontInfo, 1.0) if (src.MergeMode and src.SizePixels ~= 0.0 and ref_size ~= 0.0) then - bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * (src.SizePixels / ref_size) + bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * (src.SizePixels / ref_size) -- FIXME-NEWATLAS: Should tidy up that a bit end bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * src.ExtraSizeScale @@ -26991,11 +31105,14 @@ local function ImGui_ImplStbTrueType_FontBakedInit(atlas, src, baked) local bd_font_data = src.FontLoaderData if (src.MergeMode == false) then + -- FIXME-NEWFONTS: reevaluate how to use sizing metrics + -- FIXME-NEWFONTS: make use of line gap value local scale_for_layout = bd_font_data.ScaleFactor * baked.Size / src.ExtraSizeScale local unscaled_ascent, unscaled_descent, unscaled_line_gap = stbtt.GetFontVMetrics(bd_font_data.FontInfo) baked.Ascent = ImCeil(unscaled_ascent * scale_for_layout) baked.Descent = ImFloor(unscaled_descent * scale_for_layout) + -- FIXME: round to rasterizer density? (#9348) end return true @@ -27011,6 +31128,7 @@ end --- @return bool --- @return float? out_advance_x # Updated `advance_x` local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, codepoint, out_glyph, advance_x) + -- Search for first font which has the glyph local bd_font_data = src.FontLoaderData IM_ASSERT(bd_font_data ~= nil) local glyph_index = stbtt.FindGlyphIndex(bd_font_data.FontInfo, codepoint) @@ -27018,15 +31136,18 @@ local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, co return false, advance_x end + -- Fonts unit to pixels local oversample_h, oversample_v = ImFontAtlasBuildGetOversampleFactors(src, baked) local scale_for_layout = bd_font_data.ScaleFactor * baked.Size local rasterizer_density = src.RasterizerDensity * baked.RasterizerDensity local scale_for_raster_x = bd_font_data.ScaleFactor * baked.Size * rasterizer_density * oversample_h local scale_for_raster_y = bd_font_data.ScaleFactor * baked.Size * rasterizer_density * oversample_v + -- Obtain size and advance local x0, y0, x1, y1 = stbtt.GetGlyphBitmapBoxSubpixel(bd_font_data.FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, 0, 0) local advance, lsb = stbtt.GetGlyphHMetrics(bd_font_data.FontInfo, glyph_index) + -- Load metrics only mode if (advance_x ~= nil) then IM_ASSERT(out_glyph == nil) advance_x = advance * scale_for_layout @@ -27034,9 +31155,12 @@ local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, co return true, advance_x end + -- Prepare glyph out_glyph.Codepoint = codepoint out_glyph.AdvanceX = advance * scale_for_layout + -- Pack and retrieve position inside texture atlas + -- (generally based on stbtt_PackFontRangesRenderIntoRects) local is_visible = (x0 ~= x1 and y0 ~= y1) if is_visible then local w = (x1 - x0 + oversample_h - 1) @@ -27050,23 +31174,30 @@ local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, co local r = ImFontAtlasPackGetRect(atlas, pack_id) + -- Render x0, y0, x1, y1 = stbtt.GetGlyphBitmapBox(bd_font_data.FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y) local builder = atlas.Builder builder.TempBuffer:resize(w * h * 1) local bitmap_pixels = builder.TempBuffer.Data ImStd.memset(bitmap_pixels, 0, w * h * 1) + + -- Render with oversampling + -- (those functions conveniently assert if pixels are not cleared, which is another safety layer) local 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, glyph_index) local ref_size = baked.OwnerFont.Sources[1].SizePixels local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0 - local font_off_x = ImFloor(src.GlyphOffset.x * offsets_scale + 0.5) + local font_off_x = ImFloor(src.GlyphOffset.x * offsets_scale + 0.5) -- Snap scaled offset. local font_off_y = ImFloor(src.GlyphOffset.y * offsets_scale + 0.5) font_off_x = font_off_x + sub_x font_off_y = font_off_y + (sub_y + IM_ROUND(baked.Ascent)) local recip_h = 1.0 / (oversample_h * rasterizer_density) local recip_v = 1.0 / (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 + r.w) * recip_h + font_off_x @@ -27098,11 +31229,14 @@ end --- @param atlas ImFontAtlas --- @param baked ImFontBaked function ImFontAtlasBuildSetupFontBakedBlanks(atlas, 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) local space_glyph = baked:FindGlyphNoFallback(32) if space_glyph ~= nil then space_glyph.Visible = false end + -- 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(9) == nil and space_glyph ~= nil then local tab_glyph = ImFontGlyph() tab_glyph.Codepoint = 9 @@ -27128,8 +31262,9 @@ function ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, ba baked.OwnerFont = font baked.LastUsedFrame = atlas.Builder.FrameCount + -- Initialize backend data local loader_data_size = 0 - for _, src in font.Sources:iter() do + for _, src in font.Sources:iter() do -- Cannot easily be cached as we allow changing backend local loader = src.FontLoader and src.FontLoader or atlas.FontLoader loader_data_size = loader_data_size + loader.FontBakedSrcLoaderDataSize end @@ -27147,6 +31282,7 @@ function ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, ba return baked end +-- 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. --- @param atlas ImFontAtlas --- @param font ImFont --- @param font_size float @@ -27165,7 +31301,7 @@ function ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer break end - if (step_n == 0 and baked.RasterizerDensity ~= font_rasterizer_density) then + if (step_n == 0 and baked.RasterizerDensity ~= font_rasterizer_density) then -- First try with same density break end @@ -27222,9 +31358,10 @@ function ImFontAtlasBakedDiscard(atlas, font, baked) font.LastBaked = nil end +-- use unused_frames==0 to discard everything. function ImFontAtlasFontDiscardBakes(atlas, font, unused_frames) local builder = atlas.Builder - if builder then + if builder then -- This can be called from font destructor for baked_n = 1, builder.BakedPool.Size do repeat local baked = builder.BakedPool[baked_n] @@ -27243,6 +31380,7 @@ function ImFontAtlasFontDiscardBakes(atlas, font, unused_frames) end end +-- Was tempted to lazily init FontSrc but wouldn't save much + makes it more complicated to detect invalid data at AddFont() function ImFontAtlasFontInitOutput(atlas, font) local ret = true for _, src in font.Sources:iter() do @@ -27250,10 +31388,11 @@ function ImFontAtlasFontInitOutput(atlas, font) ret = false end end - IM_ASSERT(ret) + IM_ASSERT(ret) -- Unclear how to react to this meaningfully. Assume that result will be same as initial AddFont() call. return ret end +-- Keep source/input FontData function ImFontAtlasFontDestroyOutput(atlas, font) font:ClearOutputData() for _, src in font.Sources:iter() do @@ -27281,10 +31420,11 @@ end function ImFontAtlasFontSourceAddToFont(atlas, font, src) if src.MergeMode == false then font:ClearOutputData() + --font.FontSize = src.SizePixels font.OwnerAtlas = atlas IM_ASSERT(font.Sources[1] == src) end - atlas.TexIsBuilt = false + atlas.TexIsBuilt = false -- For legacy backends ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) end @@ -27303,6 +31443,8 @@ function ImFontAtlasFontDestroySourceData(atlas, src) src.GlyphExcludeRanges = nil end +-- Load/identify special glyphs +-- (note that this is called again for fonts with MergeMode) --- @param atlas ImFontAtlas --- @param font ImFont --- @param src ImFontConfig @@ -27310,6 +31452,7 @@ function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) -- IM_UNUSED(atlas) IM_ASSERT(font.Sources:contains(src)) + -- Find Fallback character. Actual glyph loaded in GetFontBaked(). --- @type ImWchar[] local fallback_chars = {font.FallbackChar, IM_UNICODE_CODEPOINT_INVALID, 63, 32} if font.FallbackChar == 0 then @@ -27322,6 +31465,9 @@ function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) end end + -- 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. --- @type ImWchar[] local ellipsis_chars = {src.EllipsisChar, 0x2026, 0x0085} if font.EllipsisChar == 0 then @@ -27340,6 +31486,9 @@ function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) end end +-- 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. --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @return ImFontGlyph? @@ -27354,7 +31503,7 @@ function ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) if (dot_glyph == nil) then return nil end - local dot_r_id = dot_glyph.PackId + local dot_r_id = dot_glyph.PackId -- Deep copy to avoid invalidation of glyphs and rect pointers local dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id) local dot_spacing = 1 local dot_step = (dot_glyph.X1 - dot_glyph.X0) + dot_spacing @@ -27364,7 +31513,7 @@ function ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) local glyph = ImFontGlyph() glyph.Codepoint = font.EllipsisChar - glyph.AdvanceX = ImMax(dot_glyph.AdvanceX, dot_glyph.X0 + dot_step * 3.0 - dot_spacing) + glyph.AdvanceX = ImMax(dot_glyph.AdvanceX, dot_glyph.X0 + dot_step * 3.0 - 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 @@ -27384,6 +31533,8 @@ function ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) return glyph end +-- 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) --- @param baked ImFontBaked function ImFontAtlasBuildSetupFontBakedFallback(baked) IM_ASSERT(baked.FallbackGlyphIndex == -1) @@ -27400,10 +31551,12 @@ function ImFontAtlasBuildSetupFontBakedFallback(baked) glyph.AdvanceX = space_glyph and space_glyph.AdvanceX or IM_ROUND(baked.Size * 0.40) fallback_glyph = ImFontAtlasBakedAddFontGlyph(font.OwnerAtlas, baked, nil, glyph) end - baked.FallbackGlyphIndex = baked.Glyphs:index_from_ptr(fallback_glyph) + 1 + baked.FallbackGlyphIndex = baked.Glyphs:index_from_ptr(fallback_glyph) + 1 -- Storing index avoid need to update pointer on growth and simplify inner loop code baked.FallbackAdvanceX = fallback_glyph.AdvanceX end +-- Setup main font loader for the atlas +-- Every font source (ImFontConfig) will use this unless ImFontConfig.FontLoader specify a custom loader. function ImFontAtlasBuildSetupFontLoader(atlas, font_loader) if atlas.FontLoader == font_loader then return @@ -27435,6 +31588,11 @@ function ImFontAtlasBuildSetupFontLoader(atlas, font_loader) end local function ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas) + -- [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 _, shared_data in atlas.DrawListSharedDatas:iter() do local imgui_ctx = shared_data.Context if (imgui_ctx) then @@ -27454,21 +31612,27 @@ local function ImFontAtlasBuildUpdatePointers(atlas) -- end end +-- Update texture identifier in all active draw lists --- @param atlas ImFontAtlas --- @param old_tex ImTextureRef --- @param new_tex ImTextureRef local function ImFontAtlasUpdateDrawListsTextures(atlas, old_tex, new_tex) for _, shared_data in atlas.DrawListSharedDatas:iter() do repeat + -- If Context 2 uses font owned by Context 1 which already called EndFrame()/Render(), we don't want to mess with draw commands for Context 1 if (shared_data.Context and not shared_data.Context.WithinFrameScope) then break end for _, draw_list in shared_data.DrawLists:iter() do + -- 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 and draw_list._CmdHeader.TexRef == old_tex) then draw_list:_SetTexture(new_tex) end + -- Replace in stack for i, stacked_tex in draw_list._TextureStack:iter() do if (stacked_tex == old_tex) then draw_list._TextureStack.Data[i] = new_tex @@ -27480,12 +31644,13 @@ local function ImFontAtlasUpdateDrawListsTextures(atlas, old_tex, new_tex) end end +-- Set current texture. This is mostly called from AddTexture() + to handle a failed resize. function ImFontAtlasBuildSetTexture(atlas, tex) local old_tex_ref = atlas.TexRef atlas.TexData = tex atlas.TexUvScale = ImVec2(1.0 / tex.Width, 1.0 / 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. + --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) end @@ -27495,17 +31660,28 @@ function ImFontAtlasBuildUpdateTexData(atlas) ImFontAtlasBuildUpdateTexDataBasic(atlas) end +-- Create a new texture, discard previous one function ImFontAtlasTextureAdd(atlas, w, h) local old_tex = atlas.TexData local new_tex -- FIXME: Cannot reuse texture because old UV may have been used already (unless we remap UV). + --if (old_tex ~= nil and old_tex.Status == ImTextureStatus.WantCreate) then + -- -- Reuse texture not yet used by backend. + -- IM_ASSERT(old_tex.TexID == ImTextureID_Invalid and old_tex.BackendUserData == nil) + -- old_tex:DestroyPixels() + -- old_tex.Updates:clear() + -- new_tex = old_tex + -- old_tex = nil + --else + -- Add new new_tex = ImTextureData() new_tex.UniqueID = atlas.TexNextUniqueID atlas.TexNextUniqueID = atlas.TexNextUniqueID + 1 atlas.TexList:push_back(new_tex) if old_tex ~= nil then + -- Queue old as to destroy next frame old_tex.WantDestroyNextFrame = true IM_ASSERT(old_tex.Status == ImTextureStatus.OK or old_tex.Status == ImTextureStatus.WantCreate or old_tex.Status == ImTextureStatus.WantUpdates) end @@ -27530,7 +31706,7 @@ function ImFontAtlasTextureGetSizeEstimate(atlas) local builder = atlas.Builder min_w = ImMax(ImUpperPowerOfTwo(builder.MaxRectSize.x), min_w) min_h = ImMax(ImUpperPowerOfTwo(builder.MaxRectSize.y), min_h) - local surface_approx = builder.RectsPackedSurface - builder.RectsDiscardedSurface + local surface_approx = builder.RectsPackedSurface - builder.RectsDiscardedSurface -- Expected surface after repack local surface_sqrt = ImFloor(ImSqrt(surface_approx)) local new_tex_w @@ -27553,6 +31729,7 @@ function ImFontAtlasTextureGetSizeEstimate(atlas) return ImVec2(new_tex_w, new_tex_h) -- ImVec2i end +-- Clear all output. Invalidates all AddCustomRect() return values! --- @param atlas ImFontAtlas function ImFontAtlasBuildClear(atlas) local new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas) -- ImVec2i @@ -27569,6 +31746,8 @@ function ImFontAtlasBuildClear(atlas) end end +-- You should not need to call this manually! +-- If you think you do, let us know and we can advise about policies auto-compact. --- @param atlas ImFontAtlas function ImFontAtlasTextureCompact(atlas) local builder = atlas.Builder @@ -27589,6 +31768,7 @@ function ImFontAtlasPackInit(atlas) local tex = atlas.TexData local 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. local pack_node_count = ImFloor(tex.Width / 2) builder.PackNodes:resize(pack_node_count) for i = 1, builder.PackNodes.Size do builder.PackNodes.Data[i] = stbrp.node() end @@ -27606,18 +31786,22 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) return end + -- Pack and store identifier so we can refresh UV coordinates on texture resize. local tex = atlas.TexData local builder = atlas.Builder local r = ImFontAtlasRect() local add_and_draw = (atlas:GetCustomRect(builder.PackIdLinesTexData, r) == false) if add_and_draw then + -- 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 local pack_size = ImVec2(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) -- ImVec2i builder.PackIdLinesTexData = atlas:AddCustomRect(pack_size.x, pack_size.y, r) IM_ASSERT(builder.PackIdLinesTexData ~= ImFontAtlasRectId_Invalid) end - for n = 0, IM_DRAWLIST_TEX_LINES_WIDTH_MAX do + for n = 0, IM_DRAWLIST_TEX_LINES_WIDTH_MAX do -- +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 local y = n local line_width = n @@ -27626,8 +31810,9 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) --- @type int local pad_right = r.w - (pad_left + line_width) - IM_ASSERT(pad_left + line_width + pad_right == r.w and y < r.h) + IM_ASSERT(pad_left + line_width + pad_right == r.w and y < r.h) -- Make sure we're inside the texture bounds before we start writing pixels + -- Write each slice if (add_and_draw and tex.Format == ImTextureFormat.Alpha8) then local write_ptr, write_ptr_base = tex:GetPixelsAt(r.x, r.y + y) @@ -27658,13 +31843,15 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) end end + -- Refresh UV coordinates local uv0 = ImVec2(r.x + pad_left - 1, r.y + y) * atlas.TexUvScale local uv1 = ImVec2(r.x + pad_left + line_width + 1, r.y + y + 1) * atlas.TexUvScale - local half_v = (uv0.y + uv1.y) * 0.5 + local half_v = (uv0.y + uv1.y) * 0.5 -- 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) end end +-- Render a white-colored bitmap encoded in a string --- @param atlas ImFontAtlas --- @param x int --- @param y int @@ -27704,6 +31891,8 @@ end --- @param atlas ImFontAtlas function ImFontAtlasBuildUpdateTexDataBasic(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. local builder = atlas.Builder local pack_size = (bit32.band(atlas.Flags, ImFontAtlasFlags.NoMouseCursors) ~= 0) and ImVec2(2, 2) or ImVec2(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H) @@ -27713,9 +31902,12 @@ function ImFontAtlasBuildUpdateTexDataBasic(atlas) builder.PackIdMouseCursors = atlas:AddCustomRect(pack_size.x, pack_size.y, r) IM_ASSERT(builder.PackIdMouseCursors ~= ImFontAtlasRectId_Invalid) + -- Draw to texture if bit32.band(atlas.Flags, ImFontAtlasFlags.NoMouseCursors) ~= 0 then + -- 2x2 white pixels ImFontAtlasBuildRenderBitmapFromString(atlas, r.x, r.y, 2, 2, {"X", "X", "X", "X"}, "X") else + -- 2x2 white pixels + mouse cursors local x_for_white = r.x local 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, ".") @@ -27723,9 +31915,12 @@ function ImFontAtlasBuildUpdateTexDataBasic(atlas) end end + -- Refresh UV coordinates atlas.TexUvWhitePixel = ImVec2((r.x + 0.5) * atlas.TexUvScale.x, (r.y + 0.5) * atlas.TexUvScale.y) end +-- 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? function ImFontAtlasUpdateDrawListsSharedData(atlas) for _, shared_data in atlas.DrawListSharedDatas:iter() do if (shared_data.FontAtlas == atlas) then @@ -27735,12 +31930,19 @@ function ImFontAtlasUpdateDrawListsSharedData(atlas) end end +-- Start packing over current empty texture function ImFontAtlasBuildInit(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 == nil then -- IMGUI_ENABLE_STB_TRUETYPE atlas:SetFontLoader(ImFontAtlasGetFontLoaderForStbTruetype()) end + -- Create initial texture size if atlas.TexData == nil or atlas.TexData.Pixels == nil then ImFontAtlasTextureAdd(atlas, ImUpperPowerOfTwo(atlas.TexMinWidth), ImUpperPowerOfTwo(atlas.TexMinHeight)) end @@ -27753,15 +31955,23 @@ function ImFontAtlasBuildInit(atlas) ImFontAtlasPackInit(atlas) + -- Add required texture data ImFontAtlasBuildUpdateTexData(atlas) + -- Register fonts ImFontAtlasBuildUpdatePointers(atlas) + -- Update UV coordinates etc. stored in bound ImDrawListSharedData instance ImFontAtlasUpdateDrawListsSharedData(atlas) + --atlas.TexIsBuilt = true + + -- Lazily initialize char/text classifier + -- FIXME: This could be practically anywhere, and should eventually be parameters to CalcTextSize/word-wrapping code, but there's no obvious spot now. ImTextInitClassifiers() end +-- Destroy builder and all cached glyphs. Do not destroy actual fonts. --- @param atlas ImFontAtlas function ImFontAtlasBuildDestroy(atlas) for _, font in atlas.Fonts:iter() do @@ -27774,6 +31984,8 @@ function ImFontAtlasBuildDestroy(atlas) atlas.Builder = nil end +-- 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) --- @param atlas ImFontAtlas --- @param old_font ImFont? --- @param new_font ImFont? @@ -27785,9 +31997,9 @@ function ImFontAtlasBuildNotifySetFont(atlas, old_font, new_font) local ctx = shared_data.Context if ctx then repeat + -- While this should work either way, we save ourselves the bother / debugging confusion of running ImGui code so early when it is not needed. + -- Also fixes erroneously rewriting style.FontSizeBase during init if adding default fonts. if old_font == nil and ctx.Font == nil and ctx.FontSizeBase == 0.0 then - -- While this should work either way, we save ourselves the bother / debugging confusion of running ImGui code so early when it is not needed. - -- Also fixes erroneously rewriting style.FontSizeBase during init if adding default fonts. break end @@ -27817,6 +32029,7 @@ function ImFontAtlasBuildNotifySetFont(atlas, old_font, new_font) end end +-- When atlas.RendererHasTextures = true, this is only called if no font were loaded. --- @param atlas ImFontAtlas function ImFontAtlasBuildMain(atlas) IM_ASSERT(not atlas.Locked, "Cannot modify a locked ImFontAtlas!") @@ -27835,13 +32048,20 @@ function ImFontAtlasBuildMain(atlas) -- [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs -- ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); - -- if atlas.RendererHasTextures == false then + -- if atlas.RendererHasTextures == false then -- ~ImGuiBackendFlags.RendererHasTextures -- ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas) -- end atlas.TexIsBuilt = true end +------------------------------------------------------------------------------- +-- [SECTION] ImTextureData +------------------------------------------------------------------------------- +-- - ImTextureData:Create() +-- - ImTextureData:DestroyPixels() +------------------------------------------------------------------------------- + function MT.ImTextureData:DestroyPixels() self.Pixels = nil self.UseColors = false @@ -27878,6 +32098,10 @@ function MT.ImTextureData:Create(format, w, h) self.UpdateRect.h = 0 end +------------------------------------------------------------------------------- +-- [SECTION] ImFontBaked, ImFont +------------------------------------------------------------------------------- + function MT.ImFontBaked:ClearOutputData() self.FallbackAdvanceX = 0.0 self.Glyphs:clear() @@ -27889,6 +32113,7 @@ function MT.ImFontBaked:ClearOutputData() self.MetricsTotalSurface = 0 end +-- Find glyph, load if necessary, return fallback if missing --- @param c ImWchar --- @return ImFontGlyph? function MT.ImFontBaked:FindGlyph(c) @@ -27911,6 +32136,7 @@ function MT.ImFontBaked:IsGlyphLoaded(c) return self.IndexLookup.Data[c + 1] ~= IM_FONTGLYPH_INDEX_UNUSED end +-- Attempt to load but when missing, return nil instead of FallbackGlyph --- @param c ImWchar --- @return ImFontGlyph? function MT.ImFontBaked:FindGlyphNoFallback(c) @@ -27924,7 +32150,7 @@ function MT.ImFontBaked:FindGlyphNoFallback(c) end end - self.LoadNoFallback = true + self.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. local glyph = ImFontBaked_BuildLoadGlyph(self, c, nil) self.LoadNoFallback = false return glyph @@ -27935,6 +32161,7 @@ function MT.ImFont:ClearOutputData() if atlas ~= nil then ImFontAtlasFontDiscardBakes(atlas, self, 0) end + --self.FallbackChar = 0 self.EllipsisChar = 0 for i = 1, (IM_UNICODE_CODEPOINT_MAX + 1) / 8192 / 8 do self.Used8kPagesMap[i] = 0 end self.LastBaked = nil @@ -27955,6 +32182,8 @@ end --- @param font_rasterizer_density float --- @return ImFontBaked? function ImFontAtlasBakedGetOrAdd(atlas, font, font_size, font_rasterizer_density) + -- 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.0 and font_rasterizer_density > 0.0) local baked_id = ImFontAtlasBakedGetId(font.FontId, font_size, font_rasterizer_density) local builder = atlas.Builder @@ -27965,23 +32194,29 @@ function ImFontAtlasBakedGetOrAdd(atlas, font, font_size, font_rasterizer_densit return baked end + -- If atlas is locked, find closest match + -- FIXME-OPT: This is not an optimal query. if (bit32.band(font.Flags, ImFontFlags.LockBakedSizes) ~= 0 or atlas.Locked) then baked = ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer_density) if baked ~= nil then return baked end if atlas.Locked then - IM_ASSERT(not atlas.Locked, "Cannot use dynamic font size with a locked ImFontAtlas!") + IM_ASSERT(not atlas.Locked, "Cannot use dynamic font size with a locked ImFontAtlas!") -- Locked because rendering backend does not support ImGuiBackendFlags.RendererHasTextures! return nil end end + -- Create new baked = ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, baked_id) builder.BakedMap[baked_id] = baked return baked end +-- 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 == 'self.Sources' because multiple source fonts+configs can be used to build one target font. --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @param src? ImFontConfig @@ -27991,8 +32226,9 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) local glyph_idx = baked.Glyphs.Size + 1 baked.Glyphs:push_back(in_glyph) local glyph = baked.Glyphs.Data[glyph_idx] - IM_ASSERT(baked.Glyphs.Size < 0xFFFE) + 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) then local r = ImFontAtlasPackGetRect(atlas, glyph.PackId) IM_ASSERT(glyph.U0 == 0.0 and glyph.V0 == 0.0 and glyph.U1 == 0.0 and glyph.V1 == 0.0) @@ -28004,6 +32240,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) end if (src ~= nil) then + -- Clamp & recenter if needed local ref_size = baked.OwnerFont.Sources[1].SizePixels local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0 local advance_x = ImClamp(glyph.AdvanceX, src.GlyphMinAdvanceX * offsets_scale, src.GlyphMaxAdvanceX * offsets_scale) @@ -28013,10 +32250,12 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) glyph.X1 = glyph.X1 + char_off_x end + -- Snap to pixel if (src.PixelSnapH) then advance_x = IM_ROUND(advance_x) end + -- Bake spacing glyph.AdvanceX = advance_x + src.GlyphExtraAdvanceX end if (glyph.Colored) then @@ -28024,6 +32263,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) atlas.TexPixelsUseColors = true end + -- Update lookup tables local codepoint = glyph.Codepoint ImFontBaked_BuildGrowIndex(baked, codepoint + 1) baked.IndexAdvanceX.Data[codepoint + 1] = glyph.AdvanceX @@ -28034,6 +32274,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) return glyph end +-- FIXME: Code is duplicated with code above. --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @param src? ImFontConfig @@ -28042,14 +32283,17 @@ end function ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, advance_x) -- IM_UNUSED(atlas) if (src ~= nil) then + -- Clamp & recenter if needed local ref_size = baked.OwnerFont.Sources[1].SizePixels local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0 advance_x = ImClamp(advance_x, src.GlyphMinAdvanceX * offsets_scale, src.GlyphMaxAdvanceX * offsets_scale) + -- Snap to pixel if (src.PixelSnapH) then advance_x = IM_ROUND(advance_x) end + -- Bake spacing advance_x = advance_x + src.GlyphExtraAdvanceX end @@ -28057,6 +32301,7 @@ function ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, adv baked.IndexAdvanceX.Data[codepoint + 1] = advance_x end +-- ImFontBaked are valid for the entire frame but shall never be kept between frames. --- @param size float --- @param density float? --- @return ImFontBaked? @@ -28066,6 +32311,8 @@ function MT.ImFont:GetFontBaked(size, density) --- @type ImFontBaked? local baked = self.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.0 then @@ -28111,6 +32358,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) local font = baked.OwnerFont local atlas = font.OwnerAtlas if atlas.Locked or bit32.band(font.Flags, ImFontFlags.NoLoadGlyphs) ~= 0 then + -- Lazily load fallback glyph if baked.FallbackGlyphIndex == -1 and baked.LoadNoFallback == false then ImFontAtlasBuildSetupFontBakedFallback(baked) end @@ -28118,9 +32366,14 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) return nil, only_load_advance_x end + -- User remapping hooks local src_codepoint = codepoint codepoint = ImFontAtlas_FontHookRemapCodepoint(atlas, font, codepoint) + --IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)", codepoint, ImTextCharToUtf8(codepoint)) + + -- Special hook + -- FIXME-NEWATLAS: it would be nicer if this used a more standardized way of hooking if (codepoint == font.EllipsisChar and font.EllipsisAutoBake) then local glyph = ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) if (glyph) then @@ -28128,6 +32381,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) end end + -- Call backend local loader_user_data_p = baked.FontLoaderDatas local src_n = 1 for _, src in font.Sources:iter() do @@ -28138,12 +32392,14 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) local glyph_buf = ImFontGlyph() if loader.FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, glyph_buf, nil) then + -- FIXME: Add hooks for e.g. #7962 glyph_buf.Codepoint = src_codepoint glyph_buf.SourceIdx = src_n return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph_buf) end else + -- Special mode but only loading glyphs metrics. Will rasterize and pack later. local ret --[[@as bool]] ret, only_load_advance_x = loader.FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, nil, only_load_advance_x) if ret then @@ -28159,6 +32415,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) src_n = src_n + 1 end + -- Lazily load fallback glyph if (baked.LoadNoFallback) then return nil, only_load_advance_x end @@ -28166,6 +32423,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) ImFontAtlasBuildSetupFontBakedFallback(baked) end + -- Mark index as not found, so we don't attempt the search twice ImFontBaked_BuildGrowIndex(baked, codepoint + 1); baked.IndexAdvanceX.Data[codepoint + 1] = baked.FallbackAdvanceX baked.IndexLookup.Data[codepoint + 1] = IM_FONTGLYPH_INDEX_NOT_FOUND @@ -28178,6 +32436,7 @@ end --- @return float function ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint) if (baked.Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE) or baked.LoadNoRenderOnLayout then + -- First load AdvanceX value used by CalcTextSize() API then load the rest when loaded by drawing API. local only_advance_x local glyph glyph, only_advance_x = ImFontBaked_BuildLoadGlyph(baked, codepoint, only_advance_x) @@ -28189,6 +32448,7 @@ function ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint) end end +-- This is not fast query --- @param c ImWchar --- @return bool function MT.ImFont:IsGlyphInFont(c) @@ -28204,10 +32464,12 @@ function MT.ImFont:IsGlyphInFont(c) return false end +-- This is manually inlined in CalcTextSizeA() and CalcWordWrapPosition(), with a non-inline call to BuildLoadGlyphGetAdvanceOrFallback(). --- @param c ImWchar --- @return float function MT.ImFontBaked:GetCharAdvance(c) if c < self.IndexAdvanceX.Size then + -- Missing glyphs fitting inside index will have stored FallbackAdvanceX already. local x = self.IndexAdvanceX.Data[c + 1] if x >= 0.0 then return x @@ -28216,10 +32478,12 @@ function MT.ImFontBaked:GetCharAdvance(c) return ImFontBaked_BuildLoadGlyphAdvanceX(self, c) end +-- The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b function BuildLoadGlyphGetAdvanceOrFallback(baked, codepoint) return ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint) end +-- Trim trailing space and find beginning of next line --- @param text ImString --- @param text_begin int --- @param text_end int @@ -28278,14 +32542,17 @@ function ImTextClassifierGet(_BITS, _CHAR_OFFSET) return bit32.band(bit32.rshift(_BITS[bit32.rshift(_CHAR_OFFSET, 4) + 1], bit32.lshift(bit32.band(_CHAR_OFFSET, 15), 1)), 0x03) end +-- 2-bit per character local g_CharClassifierIsSeparator_0000_007f = {} for i = 1, 128 / 16 do g_CharClassifierIsSeparator_0000_007f[i] = 0 end local g_CharClassifierIsSeparator_3000_300f = {} for i = 1, 16 / 16 do g_CharClassifierIsSeparator_3000_300f[i] = 0 end function ImTextInitClassifiers() - if (ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, 44) ~= 0) then + if (ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, 44) ~= 0) then -- ',' return end + -- List of hardcoded separators: .,;!?'" + -- Making this dynamic given known ranges is trivial BUT requires us to standardize where you pass them as parameters. (#3002, #8503) ImTextClassifierClear(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Other) ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Blank, " \t") ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Punct, ".,;!?\"") @@ -28296,6 +32563,9 @@ function ImTextInitClassifiers() ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass.Punct, 0x3002) end +-- 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. +-- Refer to imgui_test_suite's "drawlist_text_wordwrap_1" for tests. --- @param font ImFont --- @param size float --- @param text ImString @@ -28305,12 +32575,22 @@ end --- @param flags ImDrawTextFlags --- @return int function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_width, flags) + -- For references, possible wrap point marked with ^ + -- "aaa bbb, ccc,ddd. eee fff. ggg!" + -- ^ ^ ^ ^ ^__ ^ ^ + + -- Skip extra blanks after a line returns (that includes not counting them in width computation) + -- e.g. "Hello world" --> "Hello" "World" + + -- Cut words that cannot possibly fit within one line. + -- e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + local baked = font:GetFontBaked(size) local scale = size / baked.Size local line_width = 0.0 local blank_width = 0.0 - wrap_width = wrap_width / scale + wrap_width = wrap_width / scale -- We work with unscaled widths to avoid scaling every characters local s = pos IM_ASSERT(text_end ~= nil) @@ -28318,6 +32598,8 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt local prev_type = ImWcharClass.Other local keep_blanks = bit32.band(flags, ImDrawTextFlags.WrapKeepBlanks) ~= 0 + -- Find next wrapping point + --local span_begin = s local span_end = s local span_width = 0.0 @@ -28337,20 +32619,22 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt if c < 32 then if c == 10 then -- '\n' - return s + return s -- Direct return, skip "Wrap_width is too small to fit anything" path. end if c == 13 then -- '\r' - s = next_s + s = next_s -- Fast-skip break end end + -- Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' local char_width = (c < baked.IndexAdvanceX.Size) and baked.IndexAdvanceX.Data[c + 1] or -1.0 if char_width < 0.0 then char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c) end + -- Classify current character local curr_type if c < 128 then curr_type = ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, c) @@ -28361,6 +32645,7 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt end if curr_type == ImWcharClass.Blank then + -- End span: 'A ' or '. ' if (prev_type ~= ImWcharClass.Blank and not keep_blanks) then span_end = s line_width = line_width + span_width @@ -28369,11 +32654,13 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt blank_width = blank_width + char_width else - if (prev_type == ImWcharClass.Punct and curr_type ~= ImWcharClass.Punct and not (c >= 48 and c <= 57)) then + -- End span: '.X' unless X is a digit + if (prev_type == ImWcharClass.Punct and curr_type ~= ImWcharClass.Punct and not (c >= 48 and c <= 57)) then -- FIXME: Digit checks might be removed if allow custom separators (#8503) span_end = s line_width = line_width + (span_width + blank_width) blank_width = 0.0 span_width = 0.0 + -- End span: 'A ' or '. ' elseif (prev_type == ImWcharClass.Blank and keep_blanks) then span_end = s line_width = line_width + (span_width + blank_width) @@ -28388,7 +32675,10 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt if span_width + blank_width > wrap_width then stop = true; break end - + -- FIXME: Narrow wrapping e.g. "A quick brown" -> "Quic|k br|own", would require knowing if span is going to be longer than wrap_width. + --if (span_width > wrap_width and not is_blank and not was_blank) then + -- return s + --end return span_end end @@ -28399,6 +32689,8 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt if stop then break end end + -- 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 == pos and s < text_end then local bytes = ImStd.ImTextCountUtf8BytesFromChar(text, s, text_end) @@ -28441,7 +32733,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi cache_key = text end if not text_end then - text_end = #text + 1 + text_end = #text + 1 -- FIXME-OPT: Need to avoid this. end if not text_end_display then text_end_display = text_end @@ -28461,7 +32753,9 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi local stop = false while s < text_end_display do repeat + -- Word-wrapping if word_wrap_enabled then + -- 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 not word_wrap_eol then word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, text, s, text_end, wrap_width - line_width, flags) end @@ -28472,7 +32766,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end text_size.y = text_size.y + line_height line_width = 0.0 - s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) + s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then stop = true; break end @@ -28482,6 +32776,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end end + -- Decode and advance source local prev_s = s local c = ImStrByte(text, s) if c < 0x80 then @@ -28507,6 +32802,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi break end + -- Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' local char_width = (c < baked.IndexAdvanceX.Size) and baked.IndexAdvanceX.Data[c + 1] or -1.0 if (char_width < 0.0) then char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c) @@ -28528,12 +32824,12 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi text_size.x = line_width end - if out_offset then + if out_offset then -- offset allow for the possibility of sitting after a trailing \n out_offset.x = line_width out_offset.y = text_size.y + line_height end - if (line_width > 0 or text_size.y == 0.0) then + if (line_width > 0 or text_size.y == 0.0) then -- whereas size.y will ignore the trailing \n text_size.y = text_size.y + line_height end @@ -28615,6 +32911,7 @@ function MT.ImFont:RenderChar(draw_list, size, pos, col, c, cpu_fine_clip) end function MT.ImFontAtlas:AddFont(font_cfg_in) + -- Sanity Checks IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") IM_ASSERT((font_cfg_in.FontData ~= nil and font_cfg_in.FontDataSize > 0) or (font_cfg_in.FontLoader ~= nil)) IM_ASSERT(font_cfg_in.SizePixels > 0.0, "Is ImFontConfig struct correctly initialized?") @@ -28626,10 +32923,12 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) "Specifying glyph offset/advances requires a reference size to base it on.") end + -- Lazily create builder on the first call to AddFont if self.Builder == nil then ImFontAtlasBuildInit(self) end + -- Create new font local is_first_font = (self.Fonts.Size == 0) local font if not font_cfg_in.MergeMode then @@ -28641,11 +32940,12 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) font.CurrentRasterizerDensity = font_cfg_in.RasterizerDensity self.Fonts:push_back(font) else - IM_ASSERT(self.Fonts.Size > 0, "Cannot use MergeMode for the first font!") + IM_ASSERT(self.Fonts.Size > 0, "Cannot use MergeMode for the first font!") -- When using MergeMode make sure that a font has already been added before. font = (font_cfg_in.DstFont ~= nil) and font_cfg_in.DstFont or self.Fonts:back() - ImFontAtlasFontDiscardBakes(self, font, 0) + ImFontAtlasFontDiscardBakes(self, font, 0) -- Need to discard bakes if the font was already used, because baked->FontLoaderDatas[] will change size. (#9162) end + -- Add to list self.Sources:push_back(font_cfg_in) local font_cfg = self.Sources:back() if (font_cfg.DstFont == nil) then @@ -28654,6 +32954,8 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) font.Sources:push_back(font_cfg) ImFontAtlasBuildUpdatePointers(self) + -- Sanity check + -- We don't round cfg.SizePixels yet as relative size of merged fonts are used afterwards. if font_cfg.GlyphExcludeRanges ~= nil then local size = 0 for _, v in ipairs(font_cfg.GlyphExcludeRanges) do if v == 0 then break end size = size + 1 end @@ -28663,14 +32965,18 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) if font_cfg.FontLoader ~= nil then IM_ASSERT(font_cfg.FontLoader.FontBakedLoadGlyph ~= nil) - IM_ASSERT(font_cfg.FontLoader.LoaderInit == nil and font_cfg.FontLoader.LoaderShutdown == nil) + IM_ASSERT(font_cfg.FontLoader.LoaderInit == nil and font_cfg.FontLoader.LoaderShutdown == nil) -- FIXME-NEWATLAS: Unsupported yet. end + -- | Target w/ Implicit RefSize | Target w/ Explicit RefSize | + -- Adding w/ Implicit RefSize: | OK (same scale) | OK (same scale) | + -- Adding w/ Explicit RefSize: | KO | OK (custom scale) | if font_cfg_in.MergeMode and font_cfg_in.SizePixels > 0 then IM_ASSERT(bit32.band(font.Flags, ImFontFlags.ImplicitRefSize) == 0, "Cannot use MergeMode with an explicit reference size when the destination font used an implicit reference size!") end IM_ASSERT(font_cfg.FontLoaderData == nil) if not ImFontAtlasFontSourceInit(self, font_cfg) then + -- Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) ImFontAtlasFontDestroySourceData(self, font_cfg) self.Sources:pop_back() font.Sources:pop_back() @@ -28689,12 +32995,16 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) return font end +-- This duplicates some of the logic in UpdateFontsNewFrame() which is a bit chicken-and-eggy/tricky to extract due to variety of codepaths and possible initialization ordering. --- @param ctx ImGuiContext --- @return float local function GetExpectedContextFontSize(ctx) return ((ctx.Style.FontSizeBase > 0.0) and ctx.Style.FontSizeBase or 13.0) * ctx.Style.FontScaleMain * ctx.Style.FontScaleDpi end +-- Legacy function with heuristic to select Pixel or Vector font. +-- The selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold at the time of adding the default font. +-- Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() based on your own logic. --- @param font_cfg ImFontConfig function MT.ImFontAtlas:AddFontDefault(font_cfg) if self.OwnerContext == nil or GetExpectedContextFontSize(self.OwnerContext) >= 15.0 then @@ -28708,7 +33018,7 @@ function MT.ImFontAtlas:AddFontFromMemoryTTF(font_data, font_data_size, size_pix IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() IM_ASSERT(font_cfg.FontData == nil) - IM_ASSERT(font_data_size > 100, "Incorrect value for font_data_size!") + IM_ASSERT(font_data_size > 100, "Incorrect value for font_data_size!") -- Heuristic to prevent accidentally passing a wrong value to font_data_size. font_cfg.FontData = font_data font_cfg.FontDataSize = font_data_size font_cfg.SizePixels = (size_pixels > 0.0) and size_pixels or font_cfg.SizePixels @@ -28738,6 +33048,7 @@ function MT.ImFontAtlas:AddFontFromFileTTF(filename, size_pixels, font_cfg_templ local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() if not font_cfg.Name or font_cfg.Name == "" then + -- Store a short copy of filename into the font name for convenience for i = #filename, 1, -1 do local c = string.byte(filename, i, i) if (c == 47 or c == 92) then -- '/' or '\\' @@ -28759,31 +33070,35 @@ function GetDefaultFontDataProggyForever() end -- TODO: IMGUI_DISABLE_DEFAULT_FONT, IMGUI_DISABLE_DEFAULT_FONT_BITMAP +-- Load ProggyClean.ttf. Default size 13, disable oversampling. +-- If you want a similar font which may be better scaled, consider using AddFontDefaultVector(). --- @param font_cfg_template ImFontConfig function MT.ImFontAtlas:AddFontDefaultBitmap(font_cfg_template) local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() if not font_cfg_template then - font_cfg.PixelSnapH = true + font_cfg.PixelSnapH = true -- Prevents sub-integer scaling factors at lower-level layers. end if font_cfg.SizePixels <= 0.0 then - font_cfg.SizePixels = 13.0 + font_cfg.SizePixels = 13.0 -- This only serves (1) as a reference for GlyphOffset.y setting and (2) as a default for pre-1.92 backend. font_cfg.Flags = bit32.bor(font_cfg.Flags, ImFontFlags.ImplicitRefSize) end if not font_cfg.Name or font_cfg.Name == "" then font_cfg.Name = "ProggyClean.ttf" end font_cfg.EllipsisChar = 0x0085 - font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 1.0 * (font_cfg.SizePixels / 13.0) + font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 1.0 * (font_cfg.SizePixels / 13.0) -- Add +1 offset per 13 units local ttf_data, ttf_data_size = GetDefaultFontDataProggyClean() return self:AddFontFromMemoryTTF(ttf_data, ttf_data_size, font_cfg.SizePixels, font_cfg) end +-- Load a minimal version of ProggyForever, designed to match our good old ProggyClean, but nicely scalable. +-- (See build script in https://github.com/ocornut/proggyforever for details) --- @param font_cfg_template ImFontConfig function MT.ImFontAtlas:AddFontDefaultVector(font_cfg_template) local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() if not font_cfg_template then - font_cfg.PixelSnapH = true + font_cfg.PixelSnapH = true -- Precisely match ProggyClean, but prevents sub-integer scaling factors at lower-level layers. end if font_cfg.SizePixels <= 0.0 then font_cfg.SizePixels = 13.0 @@ -28792,8 +33107,8 @@ function MT.ImFontAtlas:AddFontDefaultVector(font_cfg_template) if not font_cfg.Name or font_cfg.Name == "" then font_cfg.Name = "ProggyForever.ttf" end - font_cfg.ExtraSizeScale = font_cfg.ExtraSizeScale * 1.015 - font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 0.5 * (font_cfg.SizePixels / 16.0) + font_cfg.ExtraSizeScale = font_cfg.ExtraSizeScale * 1.015 -- Match ProggyClean + font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 0.5 * (font_cfg.SizePixels / 16.0) -- Closer match ProggyClean + avoid descenders going too high (with current code). local ttf_data, ttf_data_size = GetDefaultFontDataProggyForever() return self:AddFontFromMemoryTTF(ttf_data, ttf_data_size, font_cfg.SizePixels, font_cfg) @@ -28804,7 +33119,7 @@ function MT.ImFontAtlas:GetCustomRect(id, out_r) if r == nil then return false end - IM_ASSERT(self.TexData.Width > 0 and self.TexData.Height > 0) + IM_ASSERT(self.TexData.Width > 0 and self.TexData.Height > 0) -- Font atlas needs to be built before we can calculate UV coordinates if out_r == nil then return true end @@ -28846,6 +33161,7 @@ function ImFontAtlasGetMouseCursorTexData(atlas, cursor_type, out_offset, out_si return true end +-- At it is common to do an AddCustomRect() followed by a GetCustomRect(), we provide an optional 'out_r' argument to retrieve the info straight away. function MT.ImFontAtlas:AddCustomRect(width, height, out_r) IM_ASSERT(width > 0 and width <= 0xFFFF) IM_ASSERT(height > 0 and height <= 0xFFFF) @@ -28881,7 +33197,7 @@ local function IM_NORMALIZE2F_OVER_ZERO(VX, VY) end local function IM_FIXNORMAL2F(VX, VY) - local IM_FIXNORMAL2F_MAX_INVLEN2 = 100 + local IM_FIXNORMAL2F_MAX_INVLEN2 = 100 -- 500.0f (see #4053, #3366) local d2 = VX * VX + VY * VY if d2 > 0.000001 then @@ -28895,10 +33211,14 @@ local function IM_FIXNORMAL2F(VX, VY) return VX, VY end +------------------------------------------------------------------------------- +-- [SECTION] ImDrawData +------------------------------------------------------------------------------- + function MT.ImDrawData:Clear() self.Valid = false self.FrameCount = 0; self.TotalIdxCount = 0; self.TotalVtxCount = 0 - self.CmdLists:resize(0) + self.CmdLists:resize(0) -- The ImDrawList are NOT owned by ImDrawData but e.g. by ImGuiContext, so we don't clear them. self.DisplayPos = ImVec2(0.0, 0.0) self.DisplaySize = ImVec2(0.0, 0.0) self.FramebufferScale = ImVec2(0.0, 0.0) @@ -28906,6 +33226,8 @@ function MT.ImDrawData:Clear() self.Textures = nil end +-- Important: 'out_list' is generally going to be draw_data.CmdLists, but may be another temporary list +-- as long at it is expected that the result will be later merged into draw_data.CmdLists[]. function ImGui.AddDrawListToDrawDataEx(draw_data, out_list, draw_list) if draw_list.CmdBuffer.Size == 0 then return @@ -28914,12 +33236,15 @@ function ImGui.AddDrawListToDrawDataEx(draw_data, out_list, draw_list) return end + -- Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. + -- May trigger for you if you are using PrimXXX functions incorrectly. IM_ASSERT(draw_list.VtxBuffer.Size == 0 or draw_list._VtxWritePtr == draw_list.VtxBuffer.Size + 1) IM_ASSERT(draw_list.IdxBuffer.Size == 0 or draw_list._IdxWritePtr == draw_list.IdxBuffer.Size + 1) if (bit32.band(draw_list.Flags, ImDrawListFlags.AllowVtxOffset) == 0) then IM_ASSERT(draw_list._VtxCurrentIdx == draw_list.VtxBuffer.Size + 1) end + -- Add to output list + records state in ImDrawData out_list:push_back(draw_list) draw_data.TotalVtxCount = draw_data.TotalVtxCount + draw_list.VtxBuffer.Size draw_data.TotalIdxCount = draw_data.TotalIdxCount + draw_list.IdxBuffer.Size @@ -28937,6 +33262,10 @@ local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD, _MAXERROR) return ImCl local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N, _MAXERROR) return (_MAXERROR / (1 - ImCos(IM_PI / ImMax(_N, IM_PI)))) end local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N, _RAD) return ((1 - ImCos(IM_PI / ImMax(_N, IM_PI))) / _RAD) end +------------------------------------------------------------------------------- +-- [SECTION] ImDrawList +------------------------------------------------------------------------------- + function MT.ImDrawListSharedData:SetCircleTessellationMaxError(max_error) if self.CircleTessellationMaxError == max_error then return @@ -28964,6 +33293,8 @@ function MT.ImDrawList:_SetDrawListSharedData(data) end end +-- 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 PushTexture() after this. -- TODO: function MT.ImDrawList:_ResetForNewFrame() self._ContentClipX0 = nil -- set again by Begin() (Roblox backend scroll reuse) @@ -29013,7 +33344,7 @@ end function MT.ImDrawList:AddDrawCmd() local draw_cmd = ImDrawCmd() - ImVec4_Copy(draw_cmd.ClipRect, self._CmdHeader.ClipRect) -- Same as calling ImDrawCmd_HeaderCopy()? + ImVec4_Copy(draw_cmd.ClipRect, self._CmdHeader.ClipRect) -- Same as calling ImDrawCmd_HeaderCopy() draw_cmd.TexRef = self._CmdHeader.TexRef draw_cmd.VtxOffset = self._CmdHeader.VtxOffset draw_cmd.IdxOffset = self.IdxBuffer.Size @@ -29022,11 +33353,13 @@ function MT.ImDrawList:AddDrawCmd() self.CmdBuffer:push_back(draw_cmd) end +-- Pop trailing draw command (used before merging or presenting to user) +-- Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == nil function MT.ImDrawList:_PopUnusedDrawCmd() while self.CmdBuffer.Size > 0 do local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] if curr_cmd.ElemCount ~= 0 or curr_cmd.UserCallback ~= nil then - break + break -- return;// break; end self.CmdBuffer:pop_back() @@ -29051,6 +33384,7 @@ function MT.ImDrawList:AddCallback(callback, userdata, userdata_size) curr_cmd.UserCallback = callback -- TODO: _CallbacksDataBuf? if userdata_size == 0 then + -- Store user data directly in command (no indirection) curr_cmd.UserCallbackData = userdata else @@ -29059,7 +33393,7 @@ function MT.ImDrawList:AddCallback(callback, userdata, userdata_size) end - self:AddDrawCmd() + self:AddDrawCmd() -- Force a new command after us (see comment below) end --- Compare ClipRect, TexRef, VtxOffset @@ -29107,6 +33441,7 @@ local function ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1) return CMD_0.IdxOffset + CMD_0.ElemCount == CMD_1.IdxOffset end +-- Try to merge two last draw commands function MT.ImDrawList:_TryMergeDrawCmds() IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] @@ -29117,7 +33452,10 @@ function MT.ImDrawList:_TryMergeDrawCmds() end end +-- Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. +-- The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. function MT.ImDrawList:_OnChangedClipRect() + -- If current command is used with different settings we need to add a new command IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] if (curr_cmd.ElemCount ~= 0 and self._CmdHeader.ClipRect ~= curr_cmd.ClipRect) then @@ -29128,6 +33466,7 @@ function MT.ImDrawList:_OnChangedClipRect() IM_ASSERT(curr_cmd.UserCallback == nil) + -- Try to merge with previous command if it matches, else use current command local prev_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size - 1] if (curr_cmd.ElemCount == 0 and self.CmdBuffer.Size > 1 and ImDrawCmd_HeaderCompare(self._CmdHeader, prev_cmd) and ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) and prev_cmd.UserCallback == nil) then self.CmdBuffer:pop_back() @@ -29139,6 +33478,7 @@ function MT.ImDrawList:_OnChangedClipRect() end function MT.ImDrawList:_OnChangedTexture() + -- If current command is used with different settings we need to add a new command IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] if curr_cmd.ElemCount ~= 0 and curr_cmd.TexRef ~= self._CmdHeader.TexRef then @@ -29147,10 +33487,12 @@ function MT.ImDrawList:_OnChangedTexture() return end + -- Unlike other _OnChangedXXX functions this may be called by ImFontAtlasUpdateDrawListsTextures() in more locations so we need to handle this case. if curr_cmd.UserCallback ~= nil then return end + -- Try to merge with previous command if it matches, else use current command local prev_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size - 1] if curr_cmd.ElemCount == 0 and self.CmdBuffer.Size > 1 and ImDrawCmd_HeaderCompare(self._CmdHeader, prev_cmd) and ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) and prev_cmd.UserCallback == nil then self.CmdBuffer:pop_back() @@ -29162,10 +33504,12 @@ function MT.ImDrawList:_OnChangedTexture() end function MT.ImDrawList:_OnChangedVtxOffset() + -- We don't need to compare curr_cmd.VtxOffset ~= _CmdHeader.VtxOffset because we know it'll be different at the time we call this. self._VtxCurrentIdx = 1 IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] + --IM_ASSERT(curr_cmd.VtxOffset ~= self._CmdHeader.VtxOffset) -- See #3349 if curr_cmd.ElemCount ~= 0 then self:AddDrawCmd() return @@ -29174,9 +33518,11 @@ function MT.ImDrawList:_OnChangedVtxOffset() curr_cmd.VtxOffset = self._CmdHeader.VtxOffset end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] ImDrawListSplitter ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. +------------------------------------------------------------------------------- -- Lua: channels swap ImVector objects with the draw list (C++ memcpy of the vector headers). -- Channel 0 holds nothing while it is the current channel (its buffers live in the draw list). @@ -29214,11 +33560,14 @@ function MT.ImDrawListSplitter:Split(draw_list, channels_count) IM_ASSERT(self._Current == 0 and self._Count <= 1, "Nested channel splitting is not supported. Please use separate instances of ImDrawListSplitter.") local old_channels_count = self._Channels.Size if old_channels_count < channels_count then - self._Channels:reserve(channels_count) + self._Channels:reserve(channels_count) -- Avoid over reserving since this is likely to stay stable self._Channels:resize(channels_count) end self._Count = channels_count + -- Channels[] hold storage that we'll swap with draw_list._CmdBuffer/_IdxBuffer + -- The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + -- When we switch to the next channel, we'll copy draw_list._CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list.CmdBuffer/_IdxBuffer -- Channel 0 is the draw list itself (memset to 0 in C++) local channels = self._Channels.Data channels[1] = { _CmdBuffer = nil, _IdxBuffer = nil } @@ -29353,6 +33702,8 @@ function MT.ImDrawList:ChannelsMerge() self._Splitter:Merge(self) end --- @param n int # 0-based function MT.ImDrawList:ChannelsSetCurrent(n) self._Splitter:SetCurrentChannel(self, n) end +-- - We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds. +-- - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. --- @param points ImVec2[] --- @param points_count int --- @param col ImU32 @@ -29380,6 +33731,7 @@ function MT.ImDrawList:AddConvexPolyFilled(points, points_count, col) self._IdxWritePtr = idx_write_ptr + 3 end + -- Compute normals self._Data.TempBuffer:reserve_discard(points_count) local temp_normals = self._Data.TempBuffer.Data @@ -29456,6 +33808,7 @@ function MT.ImDrawList:PopTexture() self:_OnChangedTexture() end +-- This is used by ImGui.PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTexture()/PopTexture(). function MT.ImDrawList:_SetTexture(tex_ref) if (self._CmdHeader.TexRef == tex_ref) then return @@ -29465,11 +33818,18 @@ function MT.ImDrawList:_SetTexture(tex_ref) self:_OnChangedTexture() end +-- Reserve space for a number of vertices and indices. +-- You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or +-- submit the intermediate results. PrimUnreserve() can be used to release unused allocations. @native function MT.ImDrawList:PrimReserve(idx_count, vtx_count) + -- Large mesh support (when enabled) IM_ASSERT_PARANOID(idx_count >= 0 and vtx_count >= 0) if (self._VtxCurrentIdx + vtx_count >= bit32.lshift(1, 16)) and (bit32.band(self.Flags, ImDrawListFlags.AllowVtxOffset) ~= 0) then + -- FIXME: In theory we should be testing that vtx_count <64k here. + -- In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us + -- to not make that check until we rework the text functions to handle clipping and large horizontal lines better. self._CmdHeader.VtxOffset = self.VtxBuffer.Size + 1 self:_OnChangedVtxOffset() end @@ -29486,6 +33846,7 @@ function MT.ImDrawList:PrimReserve(idx_count, vtx_count) self._IdxWritePtr = idx_buffer_old_size + 1 end +-- Release the number of reserved vertices/indices from the end of the last reservation made with PrimReserve(). function MT.ImDrawList:PrimUnreserve(idx_count, vtx_count) IM_ASSERT_PARANOID(idx_count >= 0 and vtx_count >= 0) @@ -29499,6 +33860,7 @@ function MT.ImDrawList:PrimUnreserve(idx_count, vtx_count) self._IdxWritePtr = self.IdxBuffer.Size + 1 end +-- Fully unrolled with inline call to keep our debug builds decently fast. --- @param a ImVec2 --- @param c ImVec2 --- @param col ImU32 @@ -29576,6 +33938,10 @@ function MT.ImDrawList:AddPolyline(points, points_count, col, thickness, flags) local opaque_uv = self._Data.TexUvWhitePixel local count = closed and points_count or points_count - 1 -- Number of line segments local thick_line = thickness > self._FringeScale + -- If this assert triggers on legacy code: + -- - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. + -- - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. + -- Read more details near AddRect() + see "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?") if bit32.band(self.Flags, ImDrawListFlags.AntiAliasedLines) ~= 0 then @@ -29841,6 +34207,8 @@ function MT.ImDrawList:AddRectFilled(p_min, p_max, col, rounding, flags) end end +-- p_min = upper-left, p_max = lower-right +-- Note: this does not support anti-aliasing when provided non-integer vertices. --- @param p_min ImVec2 --- @param p_max ImVec2 --- @param col_upr_left ImU32 @@ -29862,6 +34230,7 @@ function MT.ImDrawList:AddRectFilledMultiColor(p_min, p_max, col_upr_left, col_u self:PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left) end +-- p_min = upper-left, p_max = lower-right --- @param p_min ImVec2 --- @param p_max ImVec2 --- @param col ImU32 @@ -29873,7 +34242,16 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) if thickness == nil then thickness = 1.0 end if flags == nil then flags = 0 end - IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?") + -- If this assert triggers on legacy code: + -- - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. + -- - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. + -- - 1.82.0 (2021/03): changed ImDrawCornerFlags to ImDrawFlags_RoundXXX values. + -- If you used hard-coded 1 to 15 or ~0 in flags to configure corner rounding use the new flags! + -- - Hard coded support for ~0 == ImDrawFlags_RoundAll. + -- - Hard coded support for values 0x01 to 0x0F (matching 15 out of 16 old flags combinations) --> see FixRectCornerFlags() in <1.90 code. + -- - Hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundNone or use 'float rounding = 0.0f'. + -- See "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. + IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?") -- Or misuse of legacy hard-coded ImDrawCornerFlags values if bit32.band(col, IM_COL32_A_MASK) == 0 then return @@ -29892,7 +34270,7 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) if bit32.band(self.Flags, ImDrawListFlags.AntiAliasedLines) ~= 0 then self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.50, 0.50), rounding, flags) else - self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.49, 0.49), rounding, flags) + self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.49, 0.49), rounding, flags) -- Better looking lower-right corner and rounded non-AA shapes. end self:PathStroke(col, thickness, ImDrawFlags.Closed) @@ -30055,10 +34433,13 @@ function MT.ImDrawList:AddText(font, font_size, pos, col, text, text_begin, text if bit32.band(col, IM_COL32_A_MASK) == 0 then return end + -- Accept null ranges if text_begin == text_end then return end + -- 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 == nil then font = self._Data.Font end @@ -30119,7 +34500,7 @@ function MT.ImDrawList:AddImageRounded(tex_ref, p_min, p_max, uv_min, uv_max, co return end - IM_ASSERT(bit32.band(flags, 0x0F) == 0, "Misuse of legacy hardcoded ImDrawCornerFlags values!") + IM_ASSERT(bit32.band(flags, 0x0F) == 0, "Misuse of legacy hardcoded ImDrawCornerFlags values!") -- If this assert triggers on legacy code: see comments in ImDrawList:PathRect(). if bit32.band(flags, ImDrawFlags.RoundCornersMask_) == 0 then flags = bit32.bor(flags, ImDrawFlags.RoundCornersAll) end @@ -30147,22 +34528,24 @@ end --- @param radius float function MT.ImDrawList:_CalcCircleAutoSegmentCount(radius) - local radius_idx = ImFloor(radius + 0.999) + 1 + -- Automatic segment count + local radius_idx = ImFloor(radius + 0.999) + 1 -- ceil to never reduce accuracy if radius_idx >= 1 and radius_idx <= 64 then -- IM_COUNTOF(_Data->CircleSegmentCounts) - return self._Data.CircleSegmentCounts[radius_idx] + return self._Data.CircleSegmentCounts[radius_idx] -- Use cached value else return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self._Data.CircleTessellationMaxError) end end +-- 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) function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_rect) local cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y) if intersect_with_current_clip_rect then local current = self._CmdHeader.ClipRect - if cr.x < current.x then cr.x = current.x end + if cr.x < current.x then cr.x = current.x end -- = ClipWith(). Note that passing inverted range wouldn't be fixed here. if cr.y < current.y then cr.y = current.y end if cr.z > current.z then cr.z = current.z end if cr.w > current.w then cr.w = current.w end @@ -30198,10 +34581,12 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp return end + -- Calculate arc auto segment step size if a_step <= 0 then a_step = math.floor(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / self:_CalcCircleAutoSegmentCount(radius)) end + -- Make sure we never do steps larger than one quarter of the circle a_step = ImClamp(a_step, 1, math.floor(IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4)) local sample_range = ImAbs(a_max_sample - a_min_sample) @@ -30217,6 +34602,8 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp extra_max_sample = true samples = samples + 1 + -- When we have overstep to avoid awkwardly looking one long line and one tiny one at the end, + -- distribute first step range evenly between them by reducing first step size. if sample_range > 0 then a_step = a_step - math.floor((a_step - overstep) / 2) end @@ -30237,6 +34624,7 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp if a_max_sample >= a_min_sample then local a = a_min_sample while a <= a_max_sample do + -- a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more if sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX then sample_index = sample_index - IM_DRAWLIST_ARCFAST_SAMPLE_MAX end @@ -30252,6 +34640,7 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp else local a = a_min_sample while a >= a_max_sample do + -- a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more if sample_index < 0 then sample_index = sample_index + IM_DRAWLIST_ARCFAST_SAMPLE_MAX end @@ -30280,6 +34669,7 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp IM_ASSERT_PARANOID(self._Path.Size == out_ptr - 1) end +-- 0: East, 3: South, 6: West, 9: North, 12: East @native function MT.ImDrawList:PathArcToFast(center, radius, a_min_of_12, a_max_of_12) if radius < 0.5 then @@ -30328,9 +34718,12 @@ function MT.ImDrawList:PathArcTo(center, radius, a_min, a_max, num_segments) return end + -- Automatic segment count if radius <= self._Data.ArcFastRadiusCutoff then local a_is_reverse = a_max < a_min + -- We are going to use precomputed values for mid samples. + -- Determine first and last sample in lookup table that belong to the arc. local a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0) local a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0) @@ -30357,7 +34750,8 @@ function MT.ImDrawList:PathArcTo(center, radius, a_min, a_max, num_segments) end end --- Not recommended to call this directly! +-- Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. +-- DO NOT CALL DIRECTLY THIS WILL CHANGE WILDLY IN 2026. Use ImDrawList:AddText(). --- @param draw_list ImDrawList --- @param size float --- @param pos ImVec2 @@ -30373,6 +34767,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b if wrap_width == nil then wrap_width = .0 end if flags == nil then flags = 0 end + -- Align to be pixel perfect local x = pos.x local y = pos.y if y > clip_rect.w then @@ -30393,11 +34788,15 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b local origin_x = x local word_wrap_enabled = (wrap_width > 0.0) + -- Fast-forward to first visible line local s = text_begin if y + line_height < clip_rect.y then while y + line_height < clip_rect.y and s < text_end do local line_end = ImMemchr(text, '\n', s) if word_wrap_enabled then + -- 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 = ImFontCalcWordWrapPositionEx(self, size, text, s, (line_end ~= nil) and line_end or text_end, wrap_width, flags) s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) else @@ -30408,6 +34807,8 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b end end + -- For large text, scan for the last visible line in order to avoid over-reserving in the call to PrimReserve() + -- Note that very large horizontal line will still be affected by the issue (e.g. a one megabyte string buffer without a newline will likely crash atm) if text_end - s > 1e4 and not word_wrap_enabled then local s_end = s local y_end = y @@ -30424,6 +34825,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b return end + -- Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) local vtx_count_max = (text_end - s) * 4 local idx_count_max = (text_end - s) * 6 local idx_expected_size = draw_list.IdxBuffer.Size + idx_count_max @@ -30446,6 +34848,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b while s < text_end do repeat if word_wrap_enabled then + -- 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 not word_wrap_eol then word_wrap_eol = ImFontCalcWordWrapPositionEx(self, size, text, s, text_end, wrap_width - (x - origin_x), flags) end @@ -30454,15 +34857,16 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b x = origin_x y = y + line_height if y > clip_rect.w then - stop = true; break + stop = true; break -- break out of main loop end word_wrap_eol = nil - s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) + s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks break end end + -- Decode and advance source local c if text_is_str then c = string.byte(text, s) else c = text[s] end if c < 0x80 then @@ -30478,7 +34882,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b x = origin_x y = y + line_height if y > clip_rect.w then - stop = true; break + stop = true; break -- break out of main loop end break @@ -30500,16 +34904,19 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b local char_width = glyph.AdvanceX * scale if glyph.Visible then + -- We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w local x1 = x + glyph.X0 * scale local x2 = x + glyph.X1 * scale local y1 = y + glyph.Y0 * scale local y2 = y + glyph.Y1 * scale if x1 <= clip_rect.z and x2 >= clip_rect.x then + -- Render a character local u1 = glyph.U0 local v1 = glyph.V0 local u2 = glyph.U1 local v2 = glyph.V1 + -- CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. if (cpu_fine_clip) then if (x1 < clip_rect.x) then u1 = u1 + (1.0 - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1) @@ -30534,8 +34941,10 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b end end + -- Support for untinted glyphs local glyph_col = glyph.Colored and color_untinted or col + -- We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here: do local o = (vtx_write - 1) * 36 writef64(vtx_data, o, x1); writef64(vtx_data, o + 8, y1); writef64(vtx_data, o + 16, u1); writef64(vtx_data, o + 24, v1); writeu32(vtx_data, o + 32, glyph_col) @@ -30557,7 +34966,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b if stop then break end end - -- Edge case: calling RenderText() with unloaded glyphs triggering texture change. It doesn't happen via ImGui.* calls because CalcTextSize() is always used + -- 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 then IM_ASSERT(draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount == 0) draw_list.CmdBuffer:pop_back() @@ -30567,7 +34976,8 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b return self:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags) -- was `goto begin` end - draw_list.VtxBuffer.Size = vtx_write - 1 + -- Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. + draw_list.VtxBuffer.Size = vtx_write - 1 -- Same as calling shrink() draw_list.IdxBuffer.Size = idx_write - 1 draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount = draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount - (idx_expected_size - draw_list.IdxBuffer.Size) draw_list._VtxWritePtr = vtx_write @@ -30575,6 +34985,22 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b draw_list._VtxCurrentIdx = vtx_index end +------------------------------------------------------------------------------- +-- [SECTION] ImGui Internal Render Helpers +------------------------------------------------------------------------------- +-- Vaguely redesigned to stop accessing ImGui global state: +-- - RenderArrow() +-- - RenderBullet() +-- - RenderCheckMark() +-- - RenderArrowPointingAt() +-- - RenderRectFilledInRangeH() +-- - RenderRectFilledWithHole() +------------------------------------------------------------------------------- +-- Function in need of a redesign (legacy mess) +-- - RenderColorRectWithAlphaCheckerboard() +------------------------------------------------------------------------------- + +-- Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state --- @param draw_list ImDrawList --- @param pos ImVec2 --- @param color ImU32 @@ -30615,7 +35041,7 @@ end --- @param pos ImVec2 --- @param col ImU32 function ImGui.RenderBullet(draw_list, pos, col) - -- FIXME-OPT: This should be baked in font now that it's easier + -- FIXME-OPT: This should be baked in font now that it's easier. local font_size = draw_list._Data.FontSize draw_list:AddCircleFilled(pos, font_size * 0.20, col, (font_size < 22) and 8 or ((font_size < 40) and 12 or 0)) -- Hardcode optimal/nice tessellation threshold end @@ -30639,7 +35065,7 @@ function ImGui.RenderCheckMark(draw_list, pos, col, sz) draw_list:PathStroke(col, thickness) end --- Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side +-- Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. --- @param draw_list ImDrawList --- @param pos ImVec2 --- @param half_sz ImVec2 @@ -30654,7 +35080,7 @@ function ImGui.RenderArrowPointingAt(draw_list, pos, half_sz, direction, col) draw_list:AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col) elseif direction == ImGuiDir.Down then draw_list:AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col) - elseif direction == ImGuiDir.None or direction == ImGuiDir.COUNT then + elseif direction == ImGuiDir.None or direction == ImGuiDir.COUNT then -- Fix warnings end end @@ -30662,9 +35088,12 @@ local function ImAcos01(x) if x <= 0.0 then return IM_PI * 0.5 end if x >= 1.0 then return 0.0 end return ImAcos(x) + --return (-0.69813170079773212 * x * x - 0.87266462599716477) * x + 1.5707963267948966 -- Cheap approximation, may be enough for what we do. end --- FIXME: Cleanup and move code to ImDrawList +-- FIXME: Cleanup and move code to ImDrawList. +-- - Before 2025-12-04: RenderRectFilledRangeH() with 'float x_start_norm, float x_end_norm` <- normalized +-- - After 2025-12-04: RenderRectFilledInRangeH() with 'float x1, float x2' <- absolute coords!! --- @param draw_list ImDrawList --- @param rect ImRect --- @param col ImU32 @@ -30800,7 +35229,7 @@ function ImGui.RenderColorRectWithAlphaCheckerboard(draw_list, p_min, p_max, col break end - cell_flags = ImDrawFlags.RoundCornersNone + cell_flags = ImDrawFlags.RoundCornersNone -- FIXME: Could use CalcRoundingFlagsForRectInRect() if y1 <= p_min.y then if x1 <= p_min.x then cell_flags = bit32.bor(cell_flags, ImDrawFlags.RoundCornersTopLeft) end if x2 >= p_max.x then cell_flags = bit32.bor(cell_flags, ImDrawFlags.RoundCornersTopRight) end @@ -30853,14 +35282,14 @@ function ImGui.RenderRectFilledWithHole(draw_list, outer, inner, col, rounding) if fill_R and fill_D then draw_list:AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, D.RoundCornersBottomRight) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- Extra primitives (Ngon, Ellipse, Bezier, concave fill) ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [port] These follow the 1.92 stroker this port uses (no ImDrawFlags_StrokeXXX placement flags). function MT.ImDrawList:PathEllipticalArcTo(center, radius, rot, a_min, a_max, num_segments) if num_segments == nil or num_segments <= 0 then - num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) + num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) -- A bit pessimistic, maybe there's a better computation to do here. end local cos_rot, sin_rot = ImCos(rot), ImSin(rot) for i = 0, num_segments do @@ -30882,6 +35311,7 @@ function ImBezierQuadraticCalc(p1, p2, p3, t) return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x, w1 * p1.y + w2 * p2.y + w3 * p3.y) end +-- Closely mimics ImBezierCubicClosestPointCasteljau() in imgui.cpp local function PathBezierCubicCurveToCasteljau(path, x1, y1, x2, y2, x3, y3, x4, y4, tess_tol, level) local dx, dy = x4 - x1, y4 - y1 local d2 = math.abs((x2 - x4) * dy - (y2 - y4) * dx) @@ -30917,7 +35347,7 @@ end function MT.ImDrawList:PathBezierCubicCurveTo(p2, p3, p4, num_segments) local p1 = self._Path:back() if num_segments == nil or num_segments == 0 then - PathBezierCubicCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, self._Data.CurveTessellationTol, 0) + PathBezierCubicCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, self._Data.CurveTessellationTol, 0) -- Auto-tessellated else local t_step = 1.0 / num_segments for i_step = 1, num_segments do self._Path:push_back(ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step)) end @@ -30927,33 +35357,39 @@ end function MT.ImDrawList:PathBezierQuadraticCurveTo(p2, p3, num_segments) local p1 = self._Path:back() if num_segments == nil or num_segments == 0 then - PathBezierQuadraticCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, self._Data.CurveTessellationTol, 0) + PathBezierQuadraticCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, self._Data.CurveTessellationTol, 0) -- Auto-tessellated else local t_step = 1.0 / num_segments for i_step = 1, num_segments do self._Path:push_back(ImBezierQuadraticCalc(p1, p2, p3, t_step * i_step)) end end end +-- Guaranteed to honor 'num_segments' function MT.ImDrawList:AddNgon(center, radius, col, num_segments, thickness) if thickness == nil then thickness = 1.0 end if bit32.band(col, IM_COL32_A_MASK) == 0 or num_segments <= 2 then return end + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = (IM_PI * 2.0) * (num_segments - 1.0) / num_segments self:PathArcTo(center, radius - 0.5, 0.0, a_max, num_segments - 1) self:PathStroke(col, thickness, ImDrawFlags.Closed) end +-- Guaranteed to honor 'num_segments' function MT.ImDrawList:AddNgonFilled(center, radius, col, num_segments) if bit32.band(col, IM_COL32_A_MASK) == 0 or num_segments <= 2 then return end + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = (IM_PI * 2.0) * (num_segments - 1.0) / num_segments self:PathArcTo(center, radius, 0.0, a_max, num_segments - 1) self:PathFillConvex(col) end +-- Ellipse function MT.ImDrawList:AddEllipse(center, radius, col, rot, num_segments, thickness) if rot == nil then rot = 0.0 end if thickness == nil then thickness = 1.0 end if bit32.band(col, IM_COL32_A_MASK) == 0 then return end - if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end + if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end -- A bit pessimistic, maybe there's a better computation to do here. + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = IM_PI * 2.0 * (num_segments - 1.0) / num_segments self:PathEllipticalArcTo(center, radius, rot, 0.0, a_max, num_segments - 1) self:PathStroke(col, thickness, ImDrawFlags.Closed) @@ -30962,12 +35398,14 @@ end function MT.ImDrawList:AddEllipseFilled(center, radius, col, rot, num_segments) if rot == nil then rot = 0.0 end if bit32.band(col, IM_COL32_A_MASK) == 0 then return end - if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end + if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end -- A bit pessimistic, maybe there's a better computation to do here. + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = IM_PI * 2.0 * (num_segments - 1.0) / num_segments self:PathEllipticalArcTo(center, radius, rot, 0.0, a_max, num_segments - 1) self:PathFillConvex(col) end +-- Cubic Bezier takes 4 controls points function MT.ImDrawList:AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments) if bit32.band(col, IM_COL32_A_MASK) == 0 then return end self:PathLineTo(p1) @@ -30975,6 +35413,7 @@ function MT.ImDrawList:AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segmen self:PathStroke(col, thickness or 1.0) end +-- Quadratic Bezier takes 3 controls points function MT.ImDrawList:AddBezierQuadratic(p1, p2, p3, col, thickness, num_segments) if bit32.band(col, IM_COL32_A_MASK) == 0 then return end self:PathLineTo(p1) @@ -31034,8 +35473,35 @@ return true -- [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_h.lua'] = function() ---- Dear ImGui WIP --- (Definitions) +-- dear imgui, v1.93.0 WIP +-- (headers) + +-- Help: +-- - Call and read ImGui.ShowDemoWindow() in imgui_demo.lua. All applications in examples/ are doing that. +-- - Read top of imgui.lua for more details, links and comments. + +-- Resources: +-- - FAQ ........................ https://dearimgui.com/faq +-- - Homepage ................... https://github.com/ocornut/imgui +-- - Releases & Changelog ....... https://github.com/ocornut/imgui/releases +-- - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) +-- - Issues & support ........... https://github.com/ocornut/imgui/issues + +-- Index of this file: +-- [SECTION] Forward declarations and basic types +-- [SECTION] METATABLE MANAGEMENT +-- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> +-- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) +-- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +-- [SECTION] Texture identifiers (ImTextureID, ImTextureRef) +-- [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) +-- [SECTION] ImGuiIO +-- [SECTION] Viewports +-- [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) +-- [SECTION] Flags & Enumerations +-- [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) +-- [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +-- [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) --- @meta @@ -31046,6 +35512,11 @@ local rawget = rawget; local rawset = rawset local bitAnd = bit32.band; local bitOr = bit32.bor local bitLShift = bit32.lshift +------------------------------------------------------------------------------- +-- [SECTION] Forward declarations and basic types +------------------------------------------------------------------------------- + +-- Scalar data types --- @class char : integer --- @class unsigned_char : integer @@ -31090,25 +35561,42 @@ function ImS32(val) return bitAnd(val, 0xFFFFFFFF) end --- @alias size_t unsigned_int +-- 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) --- @alias ImWchar16 unsigned_short --- @alias ImWchar ImWchar16 --- @alias bool boolean +-- A unique ID used by widgets (typically the result of hashing a stack of string) --- @alias ImGuiID unsigned_int +-- 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. --- @alias ImTextureID integer +-- ImGuiKey | ImGuiMod_XXX: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. --- @alias ImGuiKeyChord int +-- ImDrawIdx: vertex index. [Compile-time configurable type] --- @alias ImDrawIdx unsigned_int +-- Library Version +-- (Integer encoded as XYYZZ for use in conditionals, e.g. 'if IMGUI_VERSION_NUM >= 12345') IMGUI_VERSION = "1.93.0 WIP" IMGUI_VERSION_NUM = 19298 -IM_UNICODE_CODEPOINT_INVALID = 0xFFFD -IM_UNICODE_CODEPOINT_MAX = 0xFFFF +-- Helper: Unicode defines +IM_UNICODE_CODEPOINT_INVALID = 0xFFFD -- Invalid Unicode code point (standard value). +IM_UNICODE_CODEPOINT_MAX = 0xFFFF -- Maximum Unicode code point supported by this build. +-- IM_ALLOC(), IM_FREE(), IM_DELETE() IM_ALLOC = ImGui.MemAlloc IM_FREE = ImGui.MemFree @@ -31116,9 +35604,9 @@ IM_FREE = ImGui.MemFree --- @param field string|int IM_DELETE = function(owner, field) if owner[field] ~= nil then owner[field] = nil; ImGui.MemFree(owner, field); end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] METATABLE MANAGEMENT ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- File-scope metatable storage local MT = {} @@ -31131,11 +35619,12 @@ function IM_ASSERT(_EXPR, _MSG) assert((_EXPR), _MSG) end IM_ASSERT_PARANOID = IM_ASSERT +-- A primary data type --- Note that `S64` and `U64` are not supported --- @enum ImGuiDataType ImGuiDataType = { - S8 = 0, -- signed char / char + S8 = 0, -- signed char / char (with sensible compilers) U8 = 1, -- unsigned char S16 = 2, -- short U16 = 3, -- unsigned short @@ -31147,37 +35636,43 @@ ImGuiDataType = String = 9, -- string (provided for user convenience, not supported by scalar widgets) COUNT = 10 } +-- Extend ImGuiDataType_ ImGuiDataType.Pointer = 11 -- [internal] ImGuiDataType.ID = 12 -- [internal] ImTextureID_Invalid = -1 +-- 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 = 0, - Alpha8 = 1, + RGBA32 = 0, -- 4 components per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + Alpha8 = 1, -- 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 = 0, - Destroyed = 1, - WantCreate = 2, - WantUpdates = 3, - WantDestroy = 4, + Destroyed = 1, -- Backend destroyed the texture. + WantCreate = 2, -- Requesting backend to create the texture. Set status OK when done. + WantUpdates = 3, -- Requesting backend to update specific blocks of pixels (write to texture portions which have never been used before). Set status OK when done. + WantDestroy = 4, -- Requesting backend to destroy the texture. Set status to Destroyed when done. } +-- Flags for ImFontAtlas build --- @enum ImFontAtlasFlags ImFontAtlasFlags = { None = 0, - NoPowerOfTwoHeight = bitLShift(1, 0), - NoMouseCursors = bitLShift(1, 1), - NoBakedLines = bitLShift(1, 2) + NoPowerOfTwoHeight = bitLShift(1, 0), -- Don't round the height to next power of two + NoMouseCursors = bitLShift(1, 1), -- Don't build software mouse cursors into the atlas (save a little texture memory) + NoBakedLines = bitLShift(1, 2) -- Don't build anti-aliased line textures into the atlas (save a little texture memory). SINCE 1.93.0 THIS PREVENTS ANTI-ALIASED LINES FROM WORKING AND WILL DISABLE THEM. } +-- A cardinal direction --- @enum ImGuiDir ImGuiDir = { @@ -31189,6 +35684,8 @@ ImGuiDir = COUNT = 4 } +-- Identify a mouse button. +-- Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. --- @enum ImGuiMouseButton ImGuiMouseButton = { @@ -31198,24 +35695,29 @@ ImGuiMouseButton = COUNT = 5 } +-- Enumeration for GetMouseCursor() +-- User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here --- @enum ImGuiMouseCursor ImGuiMouseCursor = { None = -1, Arrow = 0, - TextInput = 1, - ResizeAll = 2, - ResizeNS = 3, - ResizeEW = 4, - ResizeNESW = 5, - ResizeNWSE = 6, - Hand = 7, - Wait = 8, - Progress = 9, - NotAllowed = 10, + TextInput = 1, -- When hovering over InputText, etc. + ResizeAll = 2, -- (Unused by Dear ImGui functions) + ResizeNS = 3, -- When hovering over a horizontal border + ResizeEW = 4, -- When hovering over a vertical border or a column + ResizeNESW = 5, -- When hovering over the bottom-left corner of a window + ResizeNWSE = 6, -- When hovering over the bottom-right corner of a window + Hand = 7, -- (Unused by Dear ImGui functions. Use for e.g. hyperlinks) + Wait = 8, -- When waiting for something to process/load. + Progress = 9, -- When waiting for something to process/load, but application is still interactive. + NotAllowed = 10, -- When hovering something with disallowed interaction. Usually a crossed circle. COUNT = 11 } +-- 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. --- @class ImTextureRect --- @field x unsigned_short --- @field y unsigned_short @@ -31229,6 +35731,7 @@ ImGuiMouseCursor = --- @return ImTextureRect function ImTextureRect(x, y, w, h) return { x = x, y = y, w = w, h = h } end +-- ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type] -- [Luau] Stored as named fields {x=, y=} so the common `.x`/`.y` access is a plain table read (no metamethod call). -- Numeric keys 1, 2 still work through the metatable, but are slower: prefer .x/.y in hot code. --- @class ImVec2 @@ -31298,6 +35801,7 @@ function ImVec2_MulVX(a, scalar) return a.x * scalar, a.y * scalar end --- An inlined version of `ImVec2_Copy` currently for use in certain ImVector `push_back` local function ImVec2_TCopy(t, k, v) local dest = t[k]; dest.x = v.x; dest.y = v.y; end +-- ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] -- [Luau] Same layout as ImVec2: named fields x, y, z, w; numeric keys 1..4 go through the metatable. --- @class ImVec4 --- @operator add(ImVec4): ImVec4 @@ -31338,6 +35842,11 @@ function IM_VEC4:__tostring() return string.format("ImVec4(%g, %g, %g, %g)", sel @native function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z; dest.w = src.w end +------------------------------------------------------------------------------- +-- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> +------------------------------------------------------------------------------- + +-- ImVector<> --- A compact ImVector clone --- @class ImVector --- @field Data T[] # 1-based table @@ -31444,6 +35953,16 @@ function IM_VECTOR:index_from_ptr(p) IM_ASSERT(false, "index_from_ptr failed!") end +------------------------------------------------------------------------------- +-- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) +------------------------------------------------------------------------------- + +-- Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. + +-- Typically, 1 command = 1 GPU draw call (unless command is a callback) +-- - 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. --- @class ImDrawCmd --- @field ClipRect ImVec4 --- @field TexRef ImTextureRef @@ -31461,15 +35980,15 @@ IM_DRAWCMD.__index = IM_DRAWCMD --- @nodiscard function ImDrawCmd() return setmetatable({ - ClipRect = ImVec4(), - TexRef = nil, - VtxOffset = 0, - IdxOffset = 0, - ElemCount = 0, - UserCallback = nil, - UserCallbackData = nil, - UserCallbackDataSize = 0, - UserCallbackDataOffset = 0 + ClipRect = ImVec4(), -- 4*4 -- Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates + TexRef = nil, -- 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. + VtxOffset = 0, -- 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. + IdxOffset = 0, -- 4 -- Start offset in index buffer. + ElemCount = 0, -- 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[]. + UserCallback = nil, -- 4-8 -- If != nil, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + UserCallbackData = nil, -- 4-8 -- Callback user data (when UserCallback != nil). If called AddCallback() with size == 0, this is a copy of the AddCallback() argument. If called AddCallback() with size > 0, this is pointing to a buffer where data is stored. + UserCallbackDataSize = 0, -- 4 -- Size of callback user data when using storage, otherwise 0. + UserCallbackDataOffset = 0 -- 4 -- [Internal] Offset of callback user data when using storage, otherwise -1. }, IM_DRAWCMD) end @@ -31482,6 +36001,7 @@ function IM_DRAWCMD:GetTexID() return tex_id end +-- Vertex layout --- @class ImDrawVert --- @field [1] ImVec2 # pos --- @field [2] ImVec2 # uv @@ -31515,6 +36035,7 @@ function IM_VTXBUF:clear() self.Size = 0; self.Capacity = 0; self.Buf = buffer.c function ImDrawVtx_Pos(b, i) local o = (i - 1) * VTX_STRIDE; return buffer.readf64(b, o), buffer.readf64(b, o + 8) end function ImDrawVtx_Col(b, i) return buffer.readu32(b, (i - 1) * VTX_STRIDE + 32) end +-- [Internal] For use by ImDrawList --- @class ImDrawCmdHeader --- @field ClipRect ImVec4 --- @field TexRef ImTextureRef @@ -31524,6 +36045,7 @@ function ImDrawVtx_Col(b, i) return buffer.readu32(b, (i - 1) * VTX_STRIDE + 32) --- @nodiscard function ImDrawCmdHeader() return { ClipRect = ImVec4(), TexRef = nil, VtxOffset = 0 } end +-- [Internal] For use by ImDrawListSplitter --- @class ImDrawChannel --- @field _CmdBuffer ImVector --- @field _IdxBuffer ImVector @@ -31532,6 +36054,8 @@ function ImDrawCmdHeader() return { ClipRect = ImVec4(), TexRef = nil, VtxOffset --- @nodiscard function ImDrawChannel() return { _CmdBuffer = ImVector(), _IdxBuffer = ImVector() } end +-- 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. --- @class ImDrawListSplitter --- @field _Current int --- @field _Count int @@ -31543,6 +36067,15 @@ MT.ImDrawListSplitter = {} -- methods in imgui_draw.lua MT.ImDrawListSplitter.__index = MT.ImDrawListSplitter function ImDrawListSplitter() return setmetatable({ _Current = 0, _Count = 0, _Channels = ImVector() }, MT.ImDrawListSplitter) end +-- Draw command list +-- This is the low-level list of polygons that ImGui.* functions are filling. At the end of the frame, +-- all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +-- Each dear imgui window contains its own ImDrawList. You can use ImGui.GetWindowDrawList() to +-- access the current window draw list and draw custom primitives. +-- You can interleave normal ImGui.* calls and adding primitives to the current draw list. +-- 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 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. --- @class ImDrawList --- @field CmdBuffer ImVector --- @field IdxBuffer ImVector @@ -31595,24 +36128,26 @@ end function ImDrawList(data) --- @type ImDrawList local this = setmetatable({ - CmdBuffer = ImVector(), - IdxBuffer = ImVector(), - VtxBuffer = ImDrawVtxBuffer(), - Flags = 0, + -- This is what you have to render + CmdBuffer = ImVector(), -- Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. + IdxBuffer = ImVector(), -- Index buffer. Each command consume ImDrawCmd::ElemCount of those + VtxBuffer = ImDrawVtxBuffer(), -- Vertex buffer. + Flags = 0, -- Current flags for drawing primitives. Alter with PushDrawFlag()/PopDrawFlags() to adjust defaults to a given scope. - _VtxCurrentIdx = 1, - _Data = nil, - _VtxWritePtr = 1, - _IdxWritePtr = 1, - _Path = ImVector(ImVec2, ImVec2_TCopy), - _CmdHeader = ImDrawCmdHeader(), - _Splitter = ImDrawListSplitter(), - _ClipRectStack = ImVector(), - _TextureStack = ImVector(), - _CallbacksDataBuf = nil, + -- [Internal, used while building lists] + _VtxCurrentIdx = 1, -- [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. + _Data = nil, -- Pointer to shared draw data (you can use ImGui.GetDrawListSharedData() to get the one from current ImGui context) + _VtxWritePtr = 1, -- [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + _IdxWritePtr = 1, -- [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + _Path = ImVector(ImVec2, ImVec2_TCopy), -- [Internal] current path building + _CmdHeader = ImDrawCmdHeader(), -- [Internal] template of active commands. Fields should match those of CmdBuffer.back(). + _Splitter = ImDrawListSplitter(), -- [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) + _ClipRectStack = ImVector(), -- [Internal] + _TextureStack = ImVector(), -- [Internal] + _CallbacksDataBuf = nil, -- [Internal] - _FringeScale = 0, - _OwnerName = nil + _FringeScale = 0, -- [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content + _OwnerName = nil -- Pointer to owner window's name for debugging }, MT.ImDrawList) this:_SetDrawListSharedData(data) @@ -31620,6 +36155,9 @@ function ImDrawList(data) return this end +-- All draw data to render a Dear ImGui frame +-- (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, +-- as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) --- @class ImDrawData --- @field Valid bool --- @field FrameCount int @@ -31639,12 +36177,23 @@ function ImDrawData() --- @type ImDrawData local this = setmetatable({}, MT.ImDrawData) - this.CmdLists = ImVector() + this.CmdLists = ImVector() -- Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. this:Clear() return this end +------------------------------------------------------------------------------- +-- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +------------------------------------------------------------------------------- + +-- 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 --- @class ImTextureData --- @field UniqueID int --- @field Status ImTextureStatus @@ -31672,22 +36221,23 @@ function ImTextureData() --- @type ImTextureData local this = setmetatable({}, MT.ImTextureData) - this.UniqueID = 0 - this.Status = ImTextureStatus.Destroyed - this.BackendUserData = nil - this.TexID = ImTextureID_Invalid - this.Format = 0 - this.Width = 0 - this.Height = 0 - this.BytesPerPixel = 0 - this.Pixels = nil - this.UsedRect = ImTextureRect() - this.UpdateRect = ImTextureRect() - this.Updates = ImVector() - this.UnusedFrames = 0 - this.RefCount = 0 - this.UseColors = false - this.WantDestroyNextFrame = false + -------------------------------------------- core / backend --------------------------------------- + this.UniqueID = 0 -- w - -- [DEBUG] Sequential index to facilitate identifying a texture when debugging/printing. Unique per atlas. + this.Status = ImTextureStatus.Destroyed -- rw rw -- ImTextureStatus.OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! + this.BackendUserData = nil -- - rw -- Convenience storage for backend. Some backends may have enough with TexID. + this.TexID = ImTextureID_Invalid -- 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. + this.Format = 0 -- w r -- ImTextureFormat.RGBA32 (default) or ImTextureFormat.Alpha8 + this.Width = 0 -- w r -- Texture width + this.Height = 0 -- w r -- Texture height + this.BytesPerPixel = 0 -- w r -- 4 or 1 + this.Pixels = nil -- w r -- Pointer to whole texture buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. + this.UsedRect = ImTextureRect() -- w r -- Bounding box encompassing all past and queued Updates[]. + this.UpdateRect = ImTextureRect() -- w r -- Bounding box encompassing all queued Updates[]. + this.Updates = ImVector() -- w r -- Array of individual updates. + this.UnusedFrames = 0 -- 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. + this.RefCount = 0 -- w r -- Number of contexts using this texture. Used during backend shutdown. + this.UseColors = false -- w r -- Tell whether our texture data is known to use colors (rather than just white + alpha). + this.WantDestroyNextFrame = false -- rw - -- [Internal] Queued to set ImTextureStatus.WantDestroy next frame. May still be used in the current frame. return this end @@ -31707,6 +36257,14 @@ function MT.ImTextureData:SetTexID(tex_id) self.TexID = tex_id end --- @param status ImTextureStatus function MT.ImTextureData:SetStatus(status) self.Status = status if (status == ImTextureStatus.Destroyed and not self.WantDestroyNextFrame and self.Pixels ~= nil) then self.Status = ImTextureStatus.WantCreate end end +------------------------------------------------------------------------------- +-- [SECTION] Texture identifiers (ImTextureID, ImTextureRef) +------------------------------------------------------------------------------- + +-- 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. --- @class ImTextureRef --- @field _TexData? ImTextureData --- @field _TexID ImTextureID @@ -31717,11 +36275,18 @@ IM_TEXTURE_REF.__index = IM_TEXTURE_REF --- @nodiscard function ImTextureRef(tex_id) return setmetatable({ - _TexData = nil, - _TexID = tex_id or ImTextureID_Invalid + -- Members (either are set, never both!) + _TexData = nil, -- A texture, generally owned by a ImFontAtlas. Will convert to ImTextureID during render loop, after texture has been uploaded. + _TexID = tex_id or ImTextureID_Invalid -- _OR_ Low-level backend texture identifier, if already uploaded or created by user/app. Generally provided to e.g. ImGui.Image() calls. }, IM_TEXTURE_REF) end +------------------------------------------------------------------------------- +-- [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) +------------------------------------------------------------------------------- + +-- Font runtime data for a given size +-- Important: pointers to ImFontBaked are only valid for the current frame. --- @class ImFontBaked --- @field IndexAdvanceX ImVector # Glyphs->AdvanceX in a directly indexable way. Note that codepoint starts from 0, so IndexAdvanceX.Data[0 + 1] holds the advanceX of glyph at codepoint 0 --- @field FallbackAdvanceX float @@ -31749,29 +36314,37 @@ function ImFontBaked() --- @type ImFontBaked local this = setmetatable({}, MT.ImFontBaked) - this.IndexAdvanceX = ImVector() - this.FallbackAdvanceX = 0 - this.Size = 0 - this.RasterizerDensity = 0 + -- [Internal] Members: Hot ~20/24 bytes (for CalcTextSize) + this.IndexAdvanceX = ImVector() -- 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). + this.FallbackAdvanceX = 0 -- 4 -- out -- FindGlyph(FallbackChar)->AdvanceX + this.Size = 0 -- 4 -- in -- Height of characters/line, set during loading (doesn't change after loading) + this.RasterizerDensity = 0 -- 4 -- in -- Density this is baked at - this.IndexLookup = ImVector() - this.Glyphs = ImVector() - this.FallbackGlyphIndex = -1 + -- [Internal] Members: Hot ~28/36 bytes (for RenderText loop) + this.IndexLookup = ImVector() -- 12-16 -- out -- Sparse. Index glyphs by Unicode code-point. + this.Glyphs = ImVector() -- 12-16 -- out -- All glyphs. + this.FallbackGlyphIndex = -1 -- 4 -- out -- Index of FontFallbackChar - this.Ascent = 0 + -- [Internal] Members: Cold + this.Ascent = 0 -- 4+4 -- out -- Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) this.Descent = 0 this.MetricsTotalSurface = 0 this.WantDestroy = false this.LoadNoFallback = false this.LoadNoRenderOnLayout = false - this.LastUsedFrame = 0 - this.BakedId = 0 - this.OwnerFont = nil - this.FontLoaderDatas = nil + this.LastUsedFrame = 0 -- 4 -- -- Record of that time this was bounds + this.BakedId = 0 -- 4 -- -- Unique ID for this baked storage + this.OwnerFont = nil -- 4-8 -- in -- Parent font + this.FontLoaderDatas = nil -- 4-8 -- -- Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader. return this end +-- Font runtime data and rendering +-- - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually. +-- - Since 1.92.0 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). --- @class ImFont --- @field LastBaked ImFontBaked --- @field OwnerAtlas ImFontAtlas @@ -31798,23 +36371,27 @@ function ImFont() --- @type ImFont local this = setmetatable({}, MT.ImFont) - this.LastBaked = nil - this.OwnerAtlas = nil - this.Flags = 0 - this.CurrentRasterizerDensity = 0 - this.FontId = 0 - this.LegacySize = 0 - this.Sources = ImVector() - this.EllipsisChar = 0 - this.FallbackChar = 0 + -- [Internal] Members: Hot ~12-20 bytes + this.LastBaked = nil -- 4-8 -- Cache last bound baked. NEVER USE DIRECTLY. Use GetFontBaked(). + this.OwnerAtlas = nil -- 4-8 -- What we have been loaded into. + this.Flags = 0 -- 4 -- Font flags. + this.CurrentRasterizerDensity = 0 -- 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. + this.FontId = 0 -- Unique identifier for the font + this.LegacySize = 0 -- 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). + this.Sources = ImVector() -- 16 -- in -- List of sources. Pointers within OwnerAtlas->Sources[] + this.EllipsisChar = 0 -- 2-4 -- out -- Character used for ellipsis rendering ('...'). If you ever want to temporarily swap this for an alternative/dummy char, make sure to clear EllipsisAutoBake. + this.FallbackChar = 0 -- 2-4 -- out -- Character used if a glyph isn't found (U+FFFD, '?') this.Used8kPagesMap = {} - this.EllipsisAutoBake = false - this.RemapPairs = {} + this.EllipsisAutoBake = false -- 1 -- -- Mark when the "..." glyph (== EllipsisChar) needs to be generated by combining multiple '.'. + this.RemapPairs = {} -- 16 -- -- Remapping pairs when using AddRemapCodepointXXX(). this.Scale = 0 return this end +-- A font input/source (we may rename this to ImFontSource in the future) --- @class ImFontConfig --- @field Name string --- @field FontData table @@ -31850,37 +36427,49 @@ function ImFontConfig() --- @type ImFontConfig local this = setmetatable({}, IM_FONT_CONFIG) - this.Name = nil - this.FontData = nil - this.FontDataSize = 0 - this.FontDataOwnedByAtlas = true + -- Data Source + this.Name = nil -- -- Name (strictly to ease debugging, hence limited size buffer) + this.FontData = nil -- TTF/OTF data + this.FontDataSize = 0 -- TTF/OTF data size + this.FontDataOwnedByAtlas = true -- true -- TTF/OTF data ownership taken by the owner ImFontAtlas (will delete memory itself). SINCE 1.92, THE DATA NEEDS TO PERSIST FOR WHOLE DURATION OF ATLAS. - this.MergeMode = false - this.PixelSnapH = false - this.OversampleH = 0 - this.OversampleV = 0 - this.EllipsisChar = 0 - this.SizePixels = 0 - this.GlyphRanges = nil - this.GlyphExcludeRanges = nil - this.GlyphOffset = ImVec2() - this.GlyphMinAdvanceX = 0 - this.GlyphMaxAdvanceX = FLT_MAX - this.GlyphExtraAdvanceX = 0 - this.FontNo = 0 - this.FontLoaderFlags = 0 - this.RasterizerMultiply = 1.0 - this.RasterizerDensity = 1.0 - this.ExtraSizeScale = 1.0 + -- Options + this.MergeMode = false -- 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. + this.PixelSnapH = false -- false -- Align every glyph AdvanceX to pixel boundaries. Prevents fractional font size from working correctly! Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, OversampleH/V will default to 1. + this.OversampleH = 0 -- 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. + this.OversampleV = 0 -- 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. + this.EllipsisChar = 0 -- 0 -- Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. + this.SizePixels = 0 -- Output size in pixels for rasterizer (more or less maps to the resulting font height). + this.GlyphRanges = nil -- nil -- *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). + this.GlyphExcludeRanges = nil -- nil -- 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. + this.GlyphOffset = ImVec2() -- 0, 0 -- Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. + this.GlyphMinAdvanceX = 0 -- 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. + this.GlyphMaxAdvanceX = FLT_MAX -- FLT_MAX -- Maximum AdvanceX for glyphs + this.GlyphExtraAdvanceX = 0 -- 0 -- Extra spacing (in pixels) between glyphs. Please contact us if you are using this. -- FIXME-NEWATLAS: Intentionally unscaled + this.FontNo = 0 -- 0 -- Index of font within TTF/OTF file + this.FontLoaderFlags = 0 -- 0 -- Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. + this.RasterizerMultiply = 1.0 -- 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. + this.RasterizerDensity = 1.0 -- 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. + this.ExtraSizeScale = 1.0 -- 1.0f -- Extra rasterizer scale over SizePixels. - this.Flags = 0 - this.DstFont = nil - this.FontLoader = nil - this.FontLoaderData = nil + -- [Internal] + this.Flags = 0 -- Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates) + this.DstFont = nil -- Target font (as we merging fonts, multiple ImFontConfig may target the same font) + this.FontLoader = nil -- Custom font backend for this source (default source is the one stored in ImFontAtlas) + this.FontLoaderData = nil -- Font loader opaque storage (per font config) return this end +-- Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: +-- - 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). +-- - 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. --- @class ImFontAtlas --- @field Flags ImFontAtlasFlags --- @field TexDesiredFormat ImTextureFormat @@ -31919,41 +36508,46 @@ function ImFontAtlas() --- @type ImFontAtlas local this = setmetatable({}, MT.ImFontAtlas) - this.Flags = 0 - this.TexDesiredFormat = ImTextureFormat.RGBA32 - this.TexGlyphPadding = 1 - this.TexMinWidth = 512 - this.TexMinHeight = 128 - this.TexMaxWidth = 8192 - this.TexMaxHeight = 8192 + -- Input + this.Flags = 0 -- Build flags (see ImFontAtlasFlags_) + this.TexDesiredFormat = ImTextureFormat.RGBA32 -- Desired texture format (default to ImTextureFormat.RGBA32 but may be changed to ImTextureFormat.Alpha8). + this.TexGlyphPadding = 1 -- FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method never relies on bilinear filtering you may set this to 0. + this.TexMinWidth = 512 -- Minimum desired texture width. Must be a power of two. Default to 512. + this.TexMinHeight = 128 -- Minimum desired texture height. Must be a power of two. Default to 128. + this.TexMaxWidth = 8192 -- Maximum desired texture width. Must be a power of two. Default to 8192. + this.TexMaxHeight = 8192 -- Maximum desired texture height. Must be a power of two. Default to 8192. this.TexRef = ImTextureRef() - this.TexData = nil + this.TexData = nil -- Latest texture. - this.TexList = ImVector() - this.Locked = false - this.RendererHasTextures = false - this.TexPixelsUseColors = nil - this.TexUvScale = nil - this.TexUvWhitePixel = nil - this.Fonts = ImVector() - this.Sources = ImVector() + -- [Internal] + this.TexList = ImVector() -- Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! + this.Locked = false -- Marked as locked during ImGui.NewFrame()..EndFrame() scope if TexUpdates are not supported. Any attempt to modify the atlas will assert. + this.RendererHasTextures = false -- Copy of (BackendFlags & ImGuiBackendFlags.RendererHasTextures) from supporting context. + this.TexPixelsUseColors = nil -- 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. + this.TexUvScale = nil -- = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight). May change as new texture gets created. + this.TexUvWhitePixel = nil -- Texture coordinates to a white pixel. May change as new texture gets created. + this.Fonts = ImVector() -- 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. + this.Sources = ImVector() -- Source/configuration data this.TexUvLines = {} - this.TexNextUniqueID = 1 - this.FontNextUniqueID = 1 - this.DrawListSharedDatas = ImVector() - this.Builder = nil - this.FontLoader = nil - this.FontLoaderName = nil - this.FontLoaderData = nil - this.FontLoaderFlags = nil - this.RefCount = 0 - this.OwnerContext = nil + this.TexNextUniqueID = 1 -- Next value to be stored in TexData->UniqueID + this.FontNextUniqueID = 1 -- Next value to be stored in ImFont->FontID + this.DrawListSharedDatas = ImVector() -- List of users for this atlas. Typically one per Dear ImGui context. + this.Builder = nil -- Opaque interface to our data that doesn't need to be public and may be discarded when rebuilding. + this.FontLoader = nil -- 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. + this.FontLoaderName = nil -- Font loader name (for display e.g. in About box) == FontLoader->Name + this.FontLoaderData = nil -- Font backend opaque storage + this.FontLoaderFlags = nil -- Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. Per-font override is also available in ImFontConfig). + this.RefCount = 0 -- Number of contexts using this atlas + this.OwnerContext = nil -- Context which own the atlas will be in charge of updating and destroying it. return this end +-- 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) --- @class ImFontAtlasRect --- @field x unsigned_short --- @field y unsigned_short @@ -31962,6 +36556,8 @@ end --- @field uv0 ImVec2 --- @field uv1 ImVec2 +-- 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. --- @alias ImFontAtlasRectId int ImFontAtlasRectId_Invalid = -1 @@ -31970,13 +36566,14 @@ ImFontAtlasRectId_Invalid = -1 --- @nodiscard function ImFontAtlasRect() return { - x = nil, y = nil, - w = nil, h = nil, - uv0 = ImVec2(), + x = nil, y = nil, -- Position (in current texture) + w = nil, h = nil, -- Size + uv0 = ImVec2(), -- UV coordinates (in current texture) uv1 = ImVec2() } end +-- Hold rendering data for one glyph. --- @class ImFontGlyph --- @field Colored boolean --- @field Visible boolean @@ -32001,15 +36598,30 @@ function ImFontGlyph() Visible = false, SourceIdx = 0, Codepoint = 0, - AdvanceX = 0, + AdvanceX = 0, -- Horizontal distance to advance cursor/layout position. - X0 = 0, Y0 = 0, X1 = 0, Y1 = 0, - U0 = 0, V0 = 0, U1 = 0, V1 = 0, + X0 = 0, Y0 = 0, X1 = 0, Y1 = 0, -- Glyph corners. Offsets from current cursor/layout position. + U0 = 0, V0 = 0, U1 = 0, V1 = 0, -- Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRect() with PackId. - PackId = -1 + PackId = -1 -- [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?) } end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiIO +------------------------------------------------------------------------------- + +-- Communicate most settings and inputs/outputs to Dear ImGui using this structure. +-- Access via ImGui.GetIO(). Read 'Programmer guide' section in .cpp file for general usage. +-- It is generally expected that: +-- - initialization: backends and user code writes to ImGuiIO. +-- - main loop: backends writes to ImGuiIO, user code and imgui code reads from ImGuiIO. +------------------------------------------------------------------------------- +-- Also see ImGui.GetPlatformIO() and ImGuiPlatformIO struct for OS/platform related functions: clipboard, IME etc. +------------------------------------------------------------------------------- + +-- [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions. +-- If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and *NOT* io.KeysData[key]->DownDuration. --- @class ImGuiKeyData --- @field Down bool --- @field DownDuration float @@ -32020,6 +36632,8 @@ end --- @nodiscard function ImGuiKeyData() return { Down = false, DownDuration = 0.0, DownDurationPrev = 0.0, AnalogValue = 0.0 } end +-- Configuration flags stored in io.ConfigFlags. Set by user/application. +-- Note that nowadays most of our configuration options are in other ImGuiIO fields, e.g. io.ConfigWindowsMoveFromTitleBarOnly. --- @enum ImGuiConfigFlags ImGuiConfigFlags = { None = 0, @@ -32041,126 +36655,157 @@ MT.ImGuiIO.__index = MT.ImGuiIO --- @return ImGuiIO function ImGuiIO() local this = { - Ctx = nil, + Ctx = nil, -- Parent UI context (needs to be set explicitly by parent). - KeyCtrl = false, - KeyShift = false, - KeyAlt = false, - KeySuper = false, + KeyCtrl = false, -- Keyboard modifier down: Ctrl (non-macOS), Cmd (macOS) + KeyShift = false, -- Keyboard modifier down: Shift + KeyAlt = false, -- Keyboard modifier down: Alt + KeySuper = false, -- Keyboard modifier down: Windows/Super (non-macOS), Ctrl (macOS) - KeyMods = nil, + -- Other state maintained from data above + IO function calls + KeyMods = nil, -- 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() - BackendFlags = ImGuiBackendFlags.None, - ConfigFlags = ImGuiConfigFlags.None, - DisplaySize = ImVec2(-1.0, -1.0), + BackendFlags = ImGuiBackendFlags.None, -- = 0 -- See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. + ConfigFlags = ImGuiConfigFlags.None, -- = 0 -- See ImGuiConfigFlags_ enum. Set by user/application. Keyboard/Gamepad navigation options, etc. + DisplaySize = ImVec2(-1.0, -1.0), -- -- Main display size, in pixels (== GetMainViewport()->Size). May change every frame. - DeltaTime = 1.0 / 60.0, + DeltaTime = 1.0 / 60.0, -- = 1.0f/60.0f -- Time elapsed since last frame, in seconds. May change every frame. - DisplayFramebufferScale = ImVec2(1.0, 1.0), + DisplayFramebufferScale = ImVec2(1.0, 1.0), -- = (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. - MousePos = ImVec2(), - MousePosPrev = ImVec2(), + -- Main Input State + -- (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead) + -- (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere) + MousePos = ImVec2(), -- Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) + MousePosPrev = ImVec2(), -- Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) - WantSetMousePos = false, + WantSetMousePos = false, -- MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when io.ConfigNavMoveSetMousePos is enabled. - MouseDelta = ImVec2(), + MouseDelta = ImVec2(), -- Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. - MouseDown = {[0] = false, [1] = false, [2] = false}, + MouseDown = {[0] = false, [1] = false, [2] = false}, -- Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton.COUNT == 5). Dear ImGui mostly uses left and right buttons. Other buttons allow us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. - MouseWheel = 0, - MouseWheelH = 0, + MouseWheel = 0, -- Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold Shift to turn vertical scroll into horizontal scroll. + MouseWheelH = 0, -- 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. - MouseCtrlLeftAsRightClick = false, + MouseCtrlLeftAsRightClick = false, -- (OSX) Set to true when the current click was a Ctrl+Click that spawned a simulated right click - MouseWheelRequestAxisSwap = false, + MouseWheelRequestAxisSwap = false, -- 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. - ConfigColorEditFlags = ImGuiColorEditFlags.DefaultOptions_, + ConfigColorEditFlags = ImGuiColorEditFlags.DefaultOptions_, -- = -- Current settings for ColorEdit/ColorPicker widgets. Must have one bit of ImGuiColorEditFlags.DisplayMask_, one bit of ImGuiColorEditFlags.DataTypeMask_, one bit of ImGuiColorEditFlags.PickerMask_, one bit of ImGuiColorEditFlags.InputMask_. Defaults to ImGuiColorEditFlags.DefaultOptions_. May be further edited by users, unless you also set ImGuiColorEditFlags.NoOptions. - ConfigMacOSXBehaviors = false, - ConfigNavCursorVisibleAuto = true, - ConfigNavCursorVisibleAlways = false, - ConfigInputTrickleEventQueue = true, - ConfigWindowsResizeFromEdges = true, + -- Widget options + ConfigMacOSXBehaviors = false, -- Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl. + ConfigNavCursorVisibleAuto = true, -- = true -- Using directional navigation key makes the cursor visible. Mouse click hides the cursor. + ConfigNavCursorVisibleAlways = false, -- = false -- Navigation cursor is always visible. + ConfigInputTrickleEventQueue = true, -- = true -- Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates. + ConfigWindowsResizeFromEdges = true, -- = 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) - ConfigDebugIniSettings = false, - ConfigWindowsCopyContentsWithCtrlC = false, - ConfigWindowsMoveFromTitleBarOnly = false, - ConfigErrorRecovery = true, - ConfigErrorRecoveryEnableAssert = true, - ConfigErrorRecoveryEnableDebugLog = true, - ConfigErrorRecoveryEnableTooltip = true, - ConfigDebugHighlightIdConflicts = false, - ConfigDebugHighlightIdConflictsShowItemPicker = true, + ConfigDebugIniSettings = false, -- = false -- Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower) + ConfigWindowsCopyContentsWithCtrlC = false, -- = 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. + ConfigWindowsMoveFromTitleBarOnly = false, -- = false -- Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar. + -- Options to configure Error Handling and how we handle recoverable errors [EXPERIMENTAL] + -- - Error recovery is provided as a way to facilitate: + -- - Recovery after a programming error (native code or scripting language - the latter tends to facilitate iterating on code while running). + -- - Recovery after running an exception handler or any error processing which may skip code after an error has been detected. + -- - Error recovery is not perfect nor guaranteed! It is a feature to ease development. + -- You not are not supposed to rely on it in the course of a normal application run. + -- - Functions that support error recovery are using IM_ASSERT_USER_ERROR() instead of IM_ASSERT(). + -- - By design, we do NOT allow error recovery to be 100% silent. One of the three options needs to be checked! + -- - Always ensure that on programmers seats you have at minimum Asserts or Tooltips enabled when making direct imgui API calls! + -- Otherwise it would severely hinder your ability to catch and correct mistakes! + -- Read https://github.com/ocornut/imgui/wiki/Error-Handling for details. + -- - Programmer seats: keep asserts (default), or disable asserts and keep error tooltips (new and nice!) + -- - Non-programmer seats: maybe disable asserts, but make sure errors are resurfaced (tooltips, visible log entries, use callback etc.) + -- - Recovery after error/exception: record stack sizes with ErrorRecoveryStoreState(), disable assert, set log callback (to e.g. trigger high-level breakpoint), recover with ErrorRecoveryTryToRecoverState(), restore settings. + ConfigErrorRecovery = true, -- = true -- Enable error recovery support. Some errors won't be detected and lead to direct crashes if recovery is disabled. + ConfigErrorRecoveryEnableAssert = true, -- = true -- Enable asserts on recoverable error. By default call IM_ASSERT() when returning from a failing IM_ASSERT_USER_ERROR() + ConfigErrorRecoveryEnableDebugLog = true, -- = true -- Enable debug log output on recoverable errors. + ConfigErrorRecoveryEnableTooltip = true, -- = true -- Enable tooltip on recoverable errors. The tooltip include a way to enable asserts if they were disabled. + -- 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 + ConfigDebugHighlightIdConflicts = false, -- Highlight and show an error message popup when multiple items have conflicting identifiers. + ConfigDebugHighlightIdConflictsShowItemPicker = true, -- =true -- Show "Item Picker" button in aforementioned popup. IniFilename = "imgui.ini", -- Roblox: no disk access, only used as a flag (nil disables .ini handling) - IniSavingRate = 5.0, - LogFilename = "imgui_log.txt", - WantSaveIniSettings = false, + IniSavingRate = 5.0, -- = 5.0f -- Minimum time between saving positions/sizes to .ini file, in seconds. + LogFilename = "imgui_log.txt", -- = "imgui_log.txt"-- Path to .log file (default parameter to ImGui.LogToFile when no file is specified). + WantSaveIniSettings = false, -- When manual .ini load/save is active (io.IniFilename == nil), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! - ConfigDockingNoSplit = false, - ConfigDockingNoDockingOver = false, - ConfigDockingWithShift = false, - ConfigDockingAlwaysTabBar = false, - ConfigDockingTransparentPayload = false, - ConfigViewportsNoAutoMerge = false, - ConfigViewportsNoTaskBarIcon = false, - ConfigViewportsNoDecoration = true, - ConfigViewportsNoDefaultParent = true, - ConfigViewportsPlatformFocusSetsImGuiFocus = true, + -- Docking options (when ImGuiConfigFlags.DockingEnable is set) + ConfigDockingNoSplit = false, -- = false -- Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars. + ConfigDockingNoDockingOver = false, -- = false -- Simplified docking mode: disable window merging into a same tab-bar, so docking is limited to splitting windows. + ConfigDockingWithShift = false, -- = false -- Enable docking with holding Shift key (reduce visual noise, allows dropping in wider space) + ConfigDockingAlwaysTabBar = false, -- = false -- [BETA] [FIXME: This currently creates regression with auto-sizing and general overhead] Make every single floating window display within a docking node. + ConfigDockingTransparentPayload = false, -- = false -- [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge. + -- Viewport options (when ImGuiConfigFlags.ViewportsEnable is set) + -- (sorry for the amount of "NoXXXX" flags, which may be harder to reason about! may rework someday) + ConfigViewportsNoAutoMerge = false, -- = false; -- Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set ImGuiViewportFlags.NoAutoMerge on individual viewport. + ConfigViewportsNoTaskBarIcon = false, -- = 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. + ConfigViewportsNoDecoration = true, -- = 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). + ConfigViewportsNoDefaultParent = true, -- = true -- Disable setting OS window parent to main viewport by default. The platform backend is expected to honor `viewport->ParentViewportID` to setup a parent/child relationship between the OS windows (supported if ImGuiBackendFlags.HasParentViewport is set). When parented: child windows always appear in front of their parent. Set to false if you want viewports to automatically be parent of main viewport, otherwise all viewports will be top-level OS windows. Parent/child relationship may be set on a per-window basis using ImGuiWindowClass. + ConfigViewportsPlatformFocusSetsImGuiFocus = true, -- = 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). - ConfigMemoryCompactTimer = 60.0, + ConfigMemoryCompactTimer = 60.0, -- = 60.0f -- Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. - MouseDrawCursor = false, + -- Miscellaneous options + -- (you can visualize and interact with all options in 'Demo->Configuration') + MouseDrawCursor = false, -- = false -- Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. - MouseClicked = {[0] = false, [1] = false, [2] = false}, - MouseReleased = {[0] = false, [1] = false, [2] = false}, - MouseClickedCount = {[0] = 0, [1] = 0, [2] = 0}, - MouseClickedLastCount = {[0] = 0, [1] = 0, [2] = 0}, - MouseDownDuration = {[0] = -1, [1] = -1, [2] = -1}, - MouseDownDurationPrev = {[0] = -1, [1] = -1, [2] = -1}, + MouseClicked = {[0] = false, [1] = false, [2] = false}, -- Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0) + MouseReleased = {[0] = false, [1] = false, [2] = false}, -- Mouse button went from Down to !Down + MouseClickedCount = {[0] = 0, [1] = 0, [2] = 0}, -- == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down + MouseClickedLastCount = {[0] = 0, [1] = 0, [2] = 0}, -- Count successive number of clicks. Stays valid after mouse release. Reset after another click is done. + MouseDownDuration = {[0] = -1, [1] = -1, [2] = -1}, -- Duration the mouse button has been down (0.0f == just clicked) + MouseDownDurationPrev = {[0] = -1, [1] = -1, [2] = -1}, -- Previous time the mouse button has been down - MouseDragMaxDistanceAbs = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, - MouseDragMaxDistanceSqr = {[0] = 0, [1] = 0, [2] = 0}, + MouseDragMaxDistanceAbs = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, -- Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point + MouseDragMaxDistanceSqr = {[0] = 0, [1] = 0, [2] = 0}, -- Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) - MouseDownOwned = {[0] = nil, [1] = nil, [2] = nil}, - MouseDownOwnedUnlessPopupClose = {[0] = nil, [1] = nil, [2] = nil}, - MouseClickedTime = {[0] = 0, [1] = 0, [2] = 0}, - MouseReleasedTime = {[0] = 0, [1] = 0, [2] = 0}, - MouseClickedPos = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, + MouseDownOwned = {[0] = nil, [1] = nil, [2] = nil}, -- 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. + MouseDownOwnedUnlessPopupClose = {[0] = nil, [1] = nil, [2] = nil}, -- Track if button was clicked inside a dear imgui window. + MouseClickedTime = {[0] = 0, [1] = 0, [2] = 0}, -- Time of last click (used to figure out double-click) + MouseReleasedTime = {[0] = 0, [1] = 0, [2] = 0}, -- Time of last released (rarely used! but useful to handle delayed single-click when trying to disambiguate them from double-click). + MouseClickedPos = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, -- Position at time of clicking - MouseDoubleClicked = {[0] = false, [1] = false, [2] = false}, + MouseDoubleClicked = {[0] = false, [1] = false, [2] = false}, -- Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2) - MouseDoubleClickTime = 0.30, - MouseSingleClickDelay = 0.50, - MouseDoubleClickMaxDist = 6.0, - MouseDragThreshold = 6.0, - KeyRepeatDelay = 0.275, - KeyRepeatRate = 0.050, + -- Inputs Behaviors + -- (other variables, ones which are expected to be tweaked within UI code, are exposed in ImGuiStyle) + MouseDoubleClickTime = 0.30, -- = 0.30f -- Time for consecutive clicks to account as a double-click, in seconds. + MouseSingleClickDelay = 0.50, -- Time for a delayed click when using GetItemClickedCountWithSingleClickDelay() or IsMouseReleasedWithDelay(), in seconds. Must be > io.MouseDoubleClickTime. + MouseDoubleClickMaxDist = 6.0, -- = 6.0f -- Distance threshold to stay in to validate a double-click or multiple clicks, in pixels. + MouseDragThreshold = 6.0, -- = 6.0f -- Distance threshold before considering we are dragging. + KeyRepeatDelay = 0.275, -- = 0.275f -- When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + KeyRepeatRate = 0.050, -- = 0.050f -- When holding a key/button, rate at which it repeats, in seconds. KeysData = {}, -- size = ImGuiKey.NamedKey_COUNT - WantCaptureMouse = nil, - WantCaptureKeyboard = nil, - WantTextInput = nil, + WantCaptureMouse = nil, -- Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). + WantCaptureKeyboard = nil, -- Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). + WantTextInput = nil, -- Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). - Framerate = 0, + Framerate = 0, -- Estimate of application framerate (rolling average over 60 frames, based on io.DeltaTime), in frame per second. Solely for convenience. Slow applications may not want to use a moving average or may want to reset underlying buffers occasionally. MetricsRenderVertices = 0, MetricsRenderIndices = 0, MetricsRenderWindows = 0, MetricsActiveWindows = 0, - NavActive = false, - NavVisible = false, + NavActive = false, -- Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey.NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags.NoNavInputs flag. + NavVisible = false, -- Keyboard/Gamepad navigation highlight is visible and allowed (will handle ImGuiKey.NavXXX events). - MetricsRenderWindows = 0, + MetricsRenderWindows = 0, -- Number of visible windows - Fonts = nil, - FontDefault = nil, + -- Font system + Fonts = nil, -- -- Font atlas: load, rasterize and pack one or more fonts into a single texture. + FontDefault = nil, -- = nil -- Font to use on NewFrame(). Use nil to uses Fonts->Fonts[0]. - BackendPlatformUserData = nil, - BackendRendererUserData = nil, + BackendPlatformUserData = nil, -- = nil -- User data for platform backend + BackendRendererUserData = nil, -- = nil -- User data for renderer backend - InputQueueCharacters = ImVector(), + InputQueueCharacters = ImVector(), -- Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper. - AppAcceptingEvents = true, - InputQueueSurrogate = 0 + AppAcceptingEvents = true, -- Only modify via SetAppAcceptingEvents() + InputQueueSurrogate = 0 -- For AddInputCharacterUTF16() } for i = 0, ImGuiKey.NamedKey_COUNT - 1 do @@ -32170,6 +36815,7 @@ function ImGuiIO() return setmetatable(this, MT.ImGuiIO) end +-- (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). --- @class ImGuiPlatformImeData --- @field WantVisible bool --- @field WantTextInput bool @@ -32181,11 +36827,11 @@ end --- @nodiscard function ImGuiPlatformImeData() return { - WantVisible = false, - WantTextInput = false, - InputPos = ImVec2(), - InputLineHeight = 0.0, - ViewportId = 0 + WantVisible = false, -- A widget wants the IME to be visible. + WantTextInput = false, -- A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput. + InputPos = ImVec2(), -- Position of input cursor (for IME). + InputLineHeight = 0.0, -- Line height (for IME). + ViewportId = 0 -- ID of platform window/viewport. } end @@ -32213,26 +36859,39 @@ function ImGuiPlatformImeData_Compare(data1, data2) return true end +------------------------------------------------------------------------------- +-- [SECTION] Viewports +------------------------------------------------------------------------------- + +-- Flags stored in ImGuiViewport::Flags, giving indications to the platform backends. --- @enum ImGuiViewportFlags ImGuiViewportFlags = { None = 0, - IsPlatformWindow = bitLShift(1, 0), - IsPlatformMonitor = bitLShift(1, 1), - OwnedByApp = bitLShift(1, 2), - NoDecoration = bitLShift(1, 3), - NoTaskBarIcon = bitLShift(1, 4), - NoFocusOnAppearing = bitLShift(1, 5), - NoFocusOnClick = bitLShift(1, 6), - NoInputs = bitLShift(1, 7), - NoRendererClear = bitLShift(1, 8), - NoAutoMerge = bitLShift(1, 9), - TopMost = bitLShift(1, 10), - CanHostOtherWindows = bitLShift(1, 11), + IsPlatformWindow = bitLShift(1, 0), -- Represent a Platform Window + IsPlatformMonitor = bitLShift(1, 1), -- Represent a Platform Monitor (unused yet) + OwnedByApp = bitLShift(1, 2), -- Platform Window: Is created/managed by the user application? (rather than our backend) + NoDecoration = bitLShift(1, 3), -- Platform Window: Disable platform decorations: title bar, borders, etc. (generally set all windows, but if ImGuiConfigFlags.ViewportsDecoration is set we only set this on popups/tooltips) + NoTaskBarIcon = bitLShift(1, 4), -- Platform Window: Disable platform task bar icon (generally set on popups/tooltips, or all windows if ImGuiConfigFlags.ViewportsNoTaskBarIcon is set) + NoFocusOnAppearing = bitLShift(1, 5), -- Platform Window: Don't take focus when created. + NoFocusOnClick = bitLShift(1, 6), -- Platform Window: Don't take focus when clicked on. + NoInputs = bitLShift(1, 7), -- Platform Window: Make mouse pass through so we can drag this window while peaking behind it. + NoRendererClear = bitLShift(1, 8), -- Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely). + NoAutoMerge = bitLShift(1, 9), -- Platform Window: Avoid merging this window into another host window. This can only be set via ImGuiWindowClass viewport flags override (because we need to now ahead if we are going to create a viewport in the first place!). + TopMost = bitLShift(1, 10), -- Platform Window: Display on top (for tooltips only). + CanHostOtherWindows = bitLShift(1, 11), -- Viewport can host multiple imgui windows (secondary viewports are associated to a single window). -- FIXME: In practice there's still probably code making the assumption that this is always and only on the MainViewport. Will fix once we add support for "no main viewport". - IsMinimized = bitLShift(1, 12), - IsFocused = bitLShift(1, 13) + -- Output status flags (from Platform) + IsMinimized = bitLShift(1, 12), -- Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. + IsFocused = bitLShift(1, 13) -- Platform Window: Window is focused (last call to Platform_GetWindowFocus() returned true) } +-- - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. +-- - With multi-viewport enabled, we extend this concept to have multiple active viewports. +-- - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. +-- - About Main Area vs Work Area: +-- - Main Area = entire viewport. +-- - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor). +-- - Windows are generally trying to stay within the Work Area of their host viewport. --- @class ImGuiViewport --- @field ID ImGuiID --- @field Flags ImGuiViewportFlags @@ -32268,21 +36927,26 @@ end --- @nodiscard function ImGuiViewport() return setmetatable({ - ID = 0, - Flags = 0, - Pos = ImVec2(), - Size = ImVec2(), - FramebufferScale = ImVec2(), - WorkPos = ImVec2(), - WorkSize = ImVec2(), - DpiScale = 0, + ID = 0, -- Unique identifier for the viewport + Flags = 0, -- See ImGuiViewportFlags_ + Pos = ImVec2(), -- Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) + Size = ImVec2(), -- Main Area: Size of the viewport. + FramebufferScale = ImVec2(), -- 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. + WorkPos = ImVec2(), -- Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) + WorkSize = ImVec2(), -- Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) + DpiScale = 0, -- 1.0f = 96 DPI = No extra scale. - PlatformHandle = nil, - PlatformHandleRaw = nil, - PlatformWindowCreated = false + PlatformHandle = nil, -- void* to hold higher-level, platform window handle (e.g. HWND for Win32 backend, Uint32 WindowID for SDL, GLFWWindow* for GLFW), for FindViewportByPlatformHandle(). + PlatformHandleRaw = nil, -- void* to hold lower-level, platform-native window handle (always HWND on Win32 platform, unused for other platforms). + PlatformWindowCreated = false -- Platform window has been created (Platform_CreateWindow() has been called). This is false during the first frame where a viewport is being created. }, MT.ImGuiViewport) end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) +------------------------------------------------------------------------------- + +-- Access via ImGui.GetPlatformIO() --- @class ImGuiPlatformIO --- @field Platform_GetClipboardTextFn fun(ctx?: ImGuiContext): string --- @field Platform_CreateWindow fun(vp: ImGuiViewport) @@ -32297,29 +36961,54 @@ MT.ImGuiPlatformIO.__index = MT.ImGuiPlatformIO --- @nodiscard function ImGuiPlatformIO() local this = { - Platform_GetClipboardTextFn = nil, + ------------------------------------------------------------------------------- + -- Input - Interface with OS and Platform backend (most common stuff) + ------------------------------------------------------------------------------- + + -- Optional: Access OS clipboard + -- (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + Platform_GetClipboardTextFn = nil, -- Should return nil on failure (e.g. clipboard data is not text). Platform_SetClipboardTextFn = nil, + -- Optional: Open link/folder/file in OS Shell + -- (default to use ShellExecuteW() on Windows, system() on Linux/Mac. expected to return false on failure, but some platforms may always return true) Platform_OpenInShellFn = nil, Platform_OpenInShellUserData = nil, + ------------------------------------------------------------------------------- + -- Input - Interface with Renderer Backend + ------------------------------------------------------------------------------- + + -- Optional: Maximum texture size supported by renderer (used to adjust how we size textures). 0 if not known. Renderer_TextureMaxWidth = 0, Renderer_TextureMaxHeight = 0, + -- Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure. Renderer_RenderState = nil, + -- (Optional) Monitor list + -- - Updated by: app/backend. Update every frame to dynamically support changing monitor or DPI configuration. + -- - Used by: dear imgui to query DPI info, clamp popups/tooltips within same monitor and not have them straddle monitors. Monitors = ImVector(), - Textures = ImVector(), - Viewports = ImVector(), + -- 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. + Textures = ImVector(), -- 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") + Viewports = ImVector(), -- Main viewports, followed by all secondary viewports. + -- Optional: Platform locale + -- [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point Platform_LocaleDecimalPoint = 46, -- '.' - Platform_OnChangedViewport = nil, + Platform_OnChangedViewport = nil, -- (Optional) [BETA] FIXME-DPI: DPI handling: Called during Begin() every time the viewport we are outputting into changes, so backend has a chance to swap fonts to adjust style. } return setmetatable(this, MT.ImGuiPlatformIO) end +-- (Optional) This is required when enabling multi-viewport. Represent the bounds of each connected monitor/display and their DPI. +-- We use this information for multiple DPI support + clamping the position of popups and tooltips so they don't straddle multiple monitors. --- @class ImGuiPlatformMonitor --- @field MainPos ImVec2 --- @field MainSize ImVec2 @@ -32332,45 +37021,52 @@ end --- @nodiscard function ImGuiPlatformMonitor() return { - MainPos = ImVec2(0, 0), + MainPos = ImVec2(0, 0), -- Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right) MainSize = ImVec2(0, 0), - WorkPos = ImVec2(0, 0), + WorkPos = ImVec2(0, 0), -- Coordinates without task bars / side bars / menu bars. Used to avoid positioning popups/tooltips inside this region. If you don't have this info, please copy the value for MainPos/MainSize. WorkSize = ImVec2(0, 0), - DpiScale = 1.0, + DpiScale = 1.0, -- 1.0f = 96 DPI - PlatformHandle = nil + PlatformHandle = nil -- Backend dependant data (e.g. HMONITOR, GLFWmonitor*, SDL Display Index, NSScreen*) } end +------------------------------------------------------------------------------- +-- [SECTION] Flags & Enumerations +------------------------------------------------------------------------------- + +-- Flags for ImGui.Begin() +-- (Those are per-window flags. There are shared flags in ImGuiIO: io.ConfigWindowsResizeFromEdges and io.ConfigWindowsMoveFromTitleBarOnly) --- @enum ImGuiWindowFlags ImGuiWindowFlags = { None = 0, - NoTitleBar = bitLShift(1, 0), - NoResize = bitLShift(1, 1), - NoMove = bitLShift(1, 2), - NoScrollbar = bitLShift(1, 3), - NoScrollWithMouse = bitLShift(1, 4), - NoCollapse = bitLShift(1, 5), - AlwaysAutoResize = bitLShift(1, 6), - NoBackground = bitLShift(1, 7), - NoSavedSettings = bitLShift(1, 8), - NoMouseInputs = bitLShift(1, 9), - MenuBar = bitLShift(1, 10), - HorizontalScrollbar = bitLShift(1, 11), - NoFocusOnAppearing = bitLShift(1, 12), - NoBringToFrontOnFocus = bitLShift(1, 13), - AlwaysVerticalScrollbar = bitLShift(1, 14), - AlwaysHorizontalScrollbar = bitLShift(1, 15), - NoNavInputs = bitLShift(1, 16), - NoNavFocus = bitLShift(1, 17), - UnsavedDocument = bitLShift(1, 18), - NoDocking = bitLShift(1, 19), - DockNodeHost = bitLShift(1, 23), - ChildWindow = bitLShift(1, 24), - Tooltip = bitLShift(1, 25), - Popup = bitLShift(1, 26), - Modal = bitLShift(1, 27), - ChildMenu = bitLShift(1, 28) + NoTitleBar = bitLShift(1, 0), -- Disable title-bar + NoResize = bitLShift(1, 1), -- Disable user resizing with the lower-right grip + NoMove = bitLShift(1, 2), -- Disable user moving the window + NoScrollbar = bitLShift(1, 3), -- Disable scrollbars (window can still scroll with mouse or programmatically) + NoScrollWithMouse = bitLShift(1, 4), -- Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. + NoCollapse = bitLShift(1, 5), -- Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node). + AlwaysAutoResize = bitLShift(1, 6), -- Resize every window to its content every frame + NoBackground = bitLShift(1, 7), -- Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). + NoSavedSettings = bitLShift(1, 8), -- Never load/save settings in .ini file + NoMouseInputs = bitLShift(1, 9), -- Disable catching mouse, hovering test with pass through. + MenuBar = bitLShift(1, 10), -- Has a menu-bar + HorizontalScrollbar = bitLShift(1, 11), -- Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + NoFocusOnAppearing = bitLShift(1, 12), -- Disable taking focus when transitioning from hidden to visible state + NoBringToFrontOnFocus = bitLShift(1, 13), -- Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) + AlwaysVerticalScrollbar = bitLShift(1, 14), -- Always show vertical scrollbar (even if ContentSize.y < Size.y) + AlwaysHorizontalScrollbar = bitLShift(1, 15), -- Always show horizontal scrollbar (even if ContentSize.x < Size.x) + NoNavInputs = bitLShift(1, 16), -- No keyboard/gamepad navigation within the window + NoNavFocus = bitLShift(1, 17), -- No focusing toward this window with keyboard/gamepad navigation (e.g. skipped by Ctrl+Tab) + UnsavedDocument = bitLShift(1, 18), -- Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + NoDocking = bitLShift(1, 19), -- Disable docking of this window + -- [Internal] + DockNodeHost = bitLShift(1, 23), -- Don't use! For internal use by Begin()/NewFrame() + ChildWindow = bitLShift(1, 24), -- Don't use! For internal use by BeginChild() + Tooltip = bitLShift(1, 25), -- Don't use! For internal use by BeginTooltip() + Popup = bitLShift(1, 26), -- Don't use! For internal use by BeginPopup() + Modal = bitLShift(1, 27), -- Don't use! For internal use by BeginPopupModal() + ChildMenu = bitLShift(1, 28) -- Don't use! For internal use by BeginMenu() } -- [Internal] @@ -32378,51 +37074,74 @@ ImGuiWindowFlags.NoNav = bitOr(ImGuiWindowFlags.NoNavInputs, ImGuiWindowF ImGuiWindowFlags.NoDecoration = bitOr(ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoCollapse) ImGuiWindowFlags.NoInputs = bitOr(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs, ImGuiWindowFlags.NoNavFocus) +-- Flags for ImGui.PushItemFlag() +-- (Those are shared by all submitted items) --- @enum ImGuiItemFlags ImGuiItemFlags = { - None = 0, - NoTabStop = bitLShift(1, 0), - NoNav = bitLShift(1, 1), - NoNavDefaultFocus = bitLShift(1, 2), - ButtonRepeat = bitLShift(1, 3), - AutoClosePopups = bitLShift(1, 4), - AllowDuplicateId = bitLShift(1, 5), - Disabled = bitLShift(1, 6), - LiveEditOnInputText = bitLShift(1, 7), - LiveEditOnInputScalar = bitLShift(1, 8) + None = 0, -- Default: + NoTabStop = bitLShift(1, 0), -- false -- Disable keyboard tabbing. This is a "lighter" version of ImGuiItemFlags.NoNav. + NoNav = bitLShift(1, 1), -- false -- Disable any form of focusing: keyboard/gamepad directional navigation and SetKeyboardFocusHere() calls. + NoNavDefaultFocus = bitLShift(1, 2), -- false -- Disable item being a candidate for default focus (e.g. used by title bar items). + ButtonRepeat = bitLShift(1, 3), -- false -- Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held. + AutoClosePopups = bitLShift(1, 4), -- true -- MenuItem()/Selectable() automatically close their parent popup window. + AllowDuplicateId = bitLShift(1, 5), -- false -- Allow submitting an item with the same identifier as an item already submitted this frame without triggering a warning tooltip if io.ConfigDebugHighlightIdConflicts is set. + Disabled = bitLShift(1, 6), -- false -- [Internal] Disable interactions. DOES NOT affect visuals. This is used by BeginDisabled()/EndDisabled() and only provided here so you can read back via GetItemFlags(). + ------------------------------------------------------------------------------- + -- LiveEdit refers to applying edits to backing variables _while_ typing a value using the keyboard. + -- Widget: | Input: | w/ LiveEdit: | Output: + -- InputText() | "123" | on(default) | "1" then "12" then "123" + -- InputText() | "123" | off | "123" after validating or tabbing out or losing focus. + -- DragFloat(), SliderInt(), etc. | "123" | on* | 1 then 12 then 123 + -- DragFloat(), SliderInt(), etc. | "123" | off(default)* | 123 after validation or tabbing out or losing focus. + -- (*) Since 1.92.9 (July 2026), ImGuiItemFlags.LiveEditOnInputScalar is OFF by default. In prior version it was ON for everything. + ------------------------------------------------------------------------------- + LiveEditOnInputText = bitLShift(1, 7), -- true -- InputText: apply keyboard edits to backing value while typing. Otherwise, edits are applied when validating, tabbing out or losing focus. + LiveEditOnInputScalar = bitLShift(1, 8) -- false -- DragXXX, SliderXXX, InputScalar: apply keyboard edits to backing value while typing. Otherwise, edits are applied when validating, tabbing out or losing focus. } ImGuiItemFlags.LiveEditOnInput = bitOr(ImGuiItemFlags.LiveEditOnInputText, ImGuiItemFlags.LiveEditOnInputScalar) +-- Status flags for an already submitted item +-- - output: stored in g.LastItemData.StatusFlags --- @enum ImGuiItemStatusFlags ImGuiItemStatusFlags = { None = 0, - HoveredRect = bitLShift(1, 0), - HasDisplayRect = bitLShift(1, 1), - Edited = bitLShift(1, 2), - ToggledSelection = bitLShift(1, 3), - ToggledOpen = bitLShift(1, 4), - HasDeactivated = bitLShift(1, 5), - Deactivated = bitLShift(1, 6), - HoveredWindow = bitLShift(1, 7), - Visible = bitLShift(1, 8), - HasClipRect = bitLShift(1, 9), - HasShortcut = bitLShift(1, 10), - EditedInternal = bitLShift(1, 11) + HoveredRect = bitLShift(1, 0), -- Mouse position is within item rectangle (does NOT mean that the window is in correct z-order and can be hovered!, this is only one part of the most-common IsItemHovered test) + HasDisplayRect = bitLShift(1, 1), -- g.LastItemData.DisplayRect is valid + Edited = bitLShift(1, 2), -- Value exposed by item was edited in the current frame (should match the bool return value of most widgets) + ToggledSelection = bitLShift(1, 3), -- Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected", only state changes, in order to easily handle clipping with less issues. + ToggledOpen = bitLShift(1, 4), -- Set when TreeNode() reports toggling their open state. + HasDeactivated = bitLShift(1, 5), -- Set if the widget/group is able to provide data for the ImGuiItemStatusFlags.Deactivated flag. + Deactivated = bitLShift(1, 6), -- Only valid if ImGuiItemStatusFlags.HasDeactivated is set. + HoveredWindow = bitLShift(1, 7), -- Override the HoveredWindow test to allow cross-window hover testing. + Visible = bitLShift(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()). + HasClipRect = bitLShift(1, 9), -- g.LastItemData.ClipRect is valid. + HasShortcut = bitLShift(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. + EditedInternal = bitLShift(1, 11) -- Similar to ImGuiItemStatusFlags.Edited but bypassing ImGuiItemFlags.NoMarkEdited. } +-- Flags for ImGui.BeginChild() +-- (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. +-- - This allows BeginChild() to return false when not within boundaries (e.g. when scrolling), which is more optimal. BUT it won't update its auto-size while clipped. +-- While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional "resizing after becoming visible again" glitch. +-- - You may also use ImGuiChildFlags.AlwaysAutoResize to force an update even when child window is not in view. +-- HOWEVER PLEASE UNDERSTAND THAT DOING SO WILL PREVENT BeginChild() FROM EVER RETURNING FALSE, disabling benefits of coarse clipping. --- @enum ImGuiChildFlags ImGuiChildFlags = { None = 0, - Borders = bitLShift(1, 0), - AlwaysUseWindowPadding = bitLShift(1, 1), - ResizeX = bitLShift(1, 2), - ResizeY = bitLShift(1, 3), - AutoResizeX = bitLShift(1, 4), - AutoResizeY = bitLShift(1, 5), - AlwaysAutoResize = bitLShift(1, 6), - FrameStyle = bitLShift(1, 7), - NavFlattened = bitLShift(1, 8) + Borders = bitLShift(1, 0), -- Show an outer border and enable WindowPadding. (IMPORTANT: this is always == 1 == true for legacy reason) + AlwaysUseWindowPadding = bitLShift(1, 1), -- Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) + ResizeX = bitLShift(1, 2), -- Allow resize from right border (layout direction). Enable .ini saving (unless ImGuiWindowFlags.NoSavedSettings passed to window flags) + ResizeY = bitLShift(1, 3), -- Allow resize from bottom border (layout direction). " + AutoResizeX = bitLShift(1, 4), -- Enable auto-resizing width. Read "IMPORTANT: Size measurement" details above. + AutoResizeY = bitLShift(1, 5), -- Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above. + AlwaysAutoResize = bitLShift(1, 6), -- Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. + FrameStyle = bitLShift(1, 7), -- Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. + NavFlattened = bitLShift(1, 8) -- [BETA] Share focus scope, allow keyboard/gamepad navigation to cross over parent border to this child or between sibling child windows. } ImGuiChildFlags.ResizeBoth = bitOr(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY) @@ -32439,25 +37158,30 @@ ImGuiNextItemDataFlags = { HasColorMarker = bitLShift(1, 5) } +-- Flags for ImDrawList functions --- @enum ImDrawFlags ImDrawFlags = { None = 0, - RoundCornersTopLeft = bitLShift(1, 4), - RoundCornersTopRight = bitLShift(1, 5), - RoundCornersBottomLeft = bitLShift(1, 6), - RoundCornersBottomRight = bitLShift(1, 7), - RoundCornersNone = bitLShift(1, 8), - Closed = bitLShift(1, 9) + -- - Rounding default to ImDrawFlags.RoundCornersAll when 'rounding > 0'. + -- - So you only need to use the ImDrawFlags.RoundCornersXXX flags if you want a special configuration (e.g. a rectangle with one rounded corner). + -- Rounding for AddRectXXX(), PathRect() ------ -- Prim/Scope? + RoundCornersTopLeft = bitLShift(1, 4), -- OK -- -- Round top-left corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersTopRight = bitLShift(1, 5), -- OK -- -- Round top-right corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersBottomLeft = bitLShift(1, 6), -- OK -- -- Round bottom-left corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersBottomRight = bitLShift(1, 7), -- OK -- -- Round bottom-right corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersNone = bitLShift(1, 8), -- OK -- -- Disable rounding even when 'rounding > 0.0f'. This value is NOT zero, it is NOT an implicit flag! + -- Stroke Options ----------------------------- -- Prim/Scope? + Closed = bitLShift(1, 9) -- OK -- -- PathStroke(), AddPolyline(): specify that shape should be closed. } ImDrawFlags.RoundCornersTop = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight) ImDrawFlags.RoundCornersBottom = bitOr(ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight) ImDrawFlags.RoundCornersLeft = bitOr(ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersTopLeft) ImDrawFlags.RoundCornersRight = bitOr(ImDrawFlags.RoundCornersBottomRight, ImDrawFlags.RoundCornersTopRight) -ImDrawFlags.RoundCornersAll = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight, ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight) +ImDrawFlags.RoundCornersAll = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight, ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight) -- (Default!!) ImDrawFlags.RoundCornersDefault_ = ImDrawFlags.RoundCornersAll -ImDrawFlags.RoundCornersMask_ = bitOr(ImDrawFlags.RoundCornersAll, ImDrawFlags.RoundCornersNone) -ImDrawFlags.InvalidMask_ = 0x8000000F +ImDrawFlags.RoundCornersMask_ = bitOr(ImDrawFlags.RoundCornersAll, ImDrawFlags.RoundCornersNone) -- [Internal] +ImDrawFlags.InvalidMask_ = 0x8000000F -- [Internal] == 0x8000000F. Reserved to detect misuses. --- @enum ImDrawListFlags ImDrawListFlags = { @@ -32469,155 +37193,195 @@ ImDrawListFlags = { TextNoPixelSnap = bitLShift(1, 4) } +-- 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, - NoLoadError = bitLShift(1, 1), - NoLoadGlyphs = bitLShift(1, 2), - LockBakedSizes = bitLShift(1, 3), - ImplicitRefSize = bitLShift(1, 4) + NoLoadError = bitLShift(1, 1), -- Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. + NoLoadGlyphs = bitLShift(1, 2), -- [Internal] Disable loading new glyphs. + LockBakedSizes = bitLShift(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. + ImplicitRefSize = bitLShift(1, 4) -- [Internal] Reference size was not set explicitly. } +-- Enumeration for AddMouseSourceEvent() actual source of Mouse Input data. +-- Historically we use "Mouse" terminology everywhere to indicate pointer data, e.g. MousePos, IsMousePressed(), io.AddMousePosEvent() +-- But that "Mouse" data can come from different source which occasionally may be useful for application to know about. +-- You can submit a change of pointer type using io.AddMouseSourceEvent(). --- @enum ImGuiMouseSource ImGuiMouseSource = { - Mouse = 0, - TouchScreen = 1, - Pen = 2, + Mouse = 0, -- Input is coming from an actual mouse. + TouchScreen = 1, -- Input is coming from a touch screen (no hovering prior to initial press, less precise initial press aiming, dual-axis wheeling possible). + Pen = 2, -- Input is coming from a pressure/magnetic pen (often used in conjunction with high-sampling rates). COUNT = 3 } +-- Enumeration for ImGui.SetNextWindow***(), SetWindow***(), SetNextItem***() functions +-- Represent a condition. +-- Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond.Always. --- @enum ImGuiCond ImGuiCond = { - None = 0, - Always = bitLShift(1, 0), - Once = bitLShift(1, 1), - FirstUseEver = bitLShift(1, 2), - Appearing = bitLShift(1, 3) + None = 0, -- No condition (always set the variable), same as _Always + Always = bitLShift(1, 0), -- No condition (always set the variable), same as _None + Once = bitLShift(1, 1), -- Set the variable once per runtime session (only the first call will succeed) + FirstUseEver = bitLShift(1, 2), -- Set the variable if the object/window has no persistently saved data (no entry in .ini file) + Appearing = bitLShift(1, 3) -- Set the variable if the object/window is appearing after being hidden/inactive (or the first time) } +-- Flags for Shortcut(), SetNextItemShortcut(), +-- (and for upcoming extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() that are still in imgui_internal.h) +-- Don't mistake with ImGuiInputTextFlags! (which is for ImGui.InputText() function) --- @enum ImGuiInputFlags ImGuiInputFlags = { None = 0, - Repeat = bitLShift(1, 0), - RouteActive = bitLShift(1, 10), - RouteFocused = bitLShift(1, 11), - RouteGlobal = bitLShift(1, 12), - RouteAlways = bitLShift(1, 13), - RouteOverFocused = bitLShift(1, 14), - RouteOverActive = bitLShift(1, 15), - RouteUnlessBgFocused = bitLShift(1, 16), - RouteFromRootWindow = bitLShift(1, 17), - Tooltip = bitLShift(1, 18) + Repeat = bitLShift(1, 0), -- Enable repeat. Return true on successive repeats. Default for legacy IsKeyPressed(). NOT Default for legacy IsMouseClicked(). MUST BE == 1. + -- Flags for Shortcut(), SetNextItemShortcut() + -- - Routing policies: RouteGlobal+OverActive >> RouteActive or RouteFocused (if owner is active item) >> RouteGlobal+OverFocused >> RouteFocused (if in focused window stack) >> RouteGlobal. + -- - Default policy is RouteFocused. Can select only 1 policy among all available. + RouteActive = bitLShift(1, 10), -- Route to active item only. + RouteFocused = bitLShift(1, 11), -- Route to windows in the focus stack (DEFAULT). Deep-most focused window takes inputs. Active item takes inputs over deep-most focused window. + RouteGlobal = bitLShift(1, 12), -- Global route (unless a focused window or active item registered the route). + RouteAlways = bitLShift(1, 13), -- Do not register route, poll keys directly. + -- - Routing options + RouteOverFocused = bitLShift(1, 14), -- Option: global route: higher priority than focused route (unless active item in focused route). + RouteOverActive = bitLShift(1, 15), -- Option: global route: higher priority than active item. Unlikely you need to use that: will interfere with every active items, e.g. Ctrl+A registered by InputText will be overridden by this. May not be fully honored as user/internal code is likely to always assume they can access keys when active. + RouteUnlessBgFocused = bitLShift(1, 16), -- Option: global route: will not be applied if underlying background/void is focused (== no Dear ImGui windows are focused). Useful for overlay applications. + RouteFromRootWindow = bitLShift(1, 17), -- Option: route evaluated from the point of view of root window rather than current window. + -- Flags for SetNextItemShortcut() + Tooltip = bitLShift(1, 18) -- Automatically display a tooltip when hovering item [BETA] Unsure of right api (opt-in/opt-out) } +-- Flags for InvisibleButton() [extended in imgui_internal.h] --- @enum ImGuiButtonFlags ImGuiButtonFlags = { None = 0, - MouseButtonLeft = bitLShift(1, 0), - MouseButtonRight = bitLShift(1, 1), - MouseButtonMiddle = bitLShift(1, 2), - EnableNav = bitLShift(1, 3), - PressedOnClick = bitLShift(1, 4), - PressedOnClickRelease = bitLShift(1, 5), - PressedOnClickReleaseAnywhere = bitLShift(1, 6), - PressedOnRelease = bitLShift(1, 7), - PressedOnDoubleClick = bitLShift(1, 8), - PressedOnDragDropHold = bitLShift(1, 9), - FlattenChildren = bitLShift(1, 11), - AllowOverlap = bitLShift(1, 12), - AlignTextBaseLine = bitLShift(1, 15), - NoKeyModsAllowed = bitLShift(1, 16), - NoHoldingActiveId = bitLShift(1, 17), - NoNavFocus = bitLShift(1, 18), - NoHoveredOnFocus = bitLShift(1, 19), - NoSetKeyOwner = bitLShift(1, 20), - NoTestKeyOwner = bitLShift(1, 21), - NoFocus = bitLShift(1, 22) + MouseButtonLeft = bitLShift(1, 0), -- React on left mouse button (default) + MouseButtonRight = bitLShift(1, 1), -- React on right mouse button + MouseButtonMiddle = bitLShift(1, 2), -- React on center mouse button + EnableNav = bitLShift(1, 3), -- InvisibleButton(): do not disable navigation/tabbing. Otherwise disabled by default. + PressedOnClick = bitLShift(1, 4), -- return true on click (mouse down event) + PressedOnClickRelease = bitLShift(1, 5), -- [Default] return true on click + release on same item <-- this is what the majority of Button are using + PressedOnClickReleaseAnywhere = bitLShift(1, 6), -- return true on click + release even if the release event is not done while hovering the item + PressedOnRelease = bitLShift(1, 7), -- return true on release (default requires click+release). Prior to 2026/03/20 this implied ImGuiButtonFlags.NoHoldingActiveId but they are separate now. + PressedOnDoubleClick = bitLShift(1, 8), -- return true on double-click (default requires click+release) + PressedOnDragDropHold = bitLShift(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 -> use ImGuiItemFlags.ButtonRepeat instead. + FlattenChildren = bitLShift(1, 11), -- allow interactions even if a child window is overlapping + AllowOverlap = bitLShift(1, 12), -- Hit testing will allow subsequent widgets to overlap this one. Require previous frame HoveredId to match before being usable. Shortcut to calling SetNextItemAllowOverlap(). + --ImGuiButtonFlags.DontClosePopups = 1 << 13, -- disable automatically closing parent popup on press + --ImGuiButtonFlags.Disabled = 1 << 14, -- disable interactions -> use BeginDisabled() or ImGuiItemFlags.Disabled + AlignTextBaseLine = bitLShift(1, 15), -- vertically align button to match text baseline - ButtonEx() only -- FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine + NoKeyModsAllowed = bitLShift(1, 16), -- disable mouse interaction if a key modifier is held + NoHoldingActiveId = bitLShift(1, 17), -- don't set ActiveId while holding the mouse (ImGuiButtonFlags.PressedOnClick only) + NoNavFocus = bitLShift(1, 18), -- don't override navigation focus when activated (FIXME: this is essentially used every time an item uses ImGuiItemFlags.NoNav, but because legacy specs don't requires LastItemData to be set ButtonBehavior(), we can't poll g.LastItemData.ItemFlags) + NoHoveredOnFocus = bitLShift(1, 19), -- don't report as hovered when nav focus is on this item + NoSetKeyOwner = bitLShift(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!) + NoTestKeyOwner = bitLShift(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!) + NoFocus = bitLShift(1, 22) -- [EXPERIMENTAL: Not very well specced]. Don't focus parent window when clicking. } -ImGuiButtonFlags.MouseButtonMask_ = bitOr(ImGuiButtonFlags.MouseButtonLeft, ImGuiButtonFlags.MouseButtonRight, ImGuiButtonFlags.MouseButtonMiddle) +ImGuiButtonFlags.MouseButtonMask_ = bitOr(ImGuiButtonFlags.MouseButtonLeft, ImGuiButtonFlags.MouseButtonRight, ImGuiButtonFlags.MouseButtonMiddle) -- [Internal] ImGuiButtonFlags.PressedOnMask_ = bitOr(ImGuiButtonFlags.PressedOnClick, ImGuiButtonFlags.PressedOnClickRelease, ImGuiButtonFlags.PressedOnClickReleaseAnywhere, ImGuiButtonFlags.PressedOnRelease, ImGuiButtonFlags.PressedOnDoubleClick, ImGuiButtonFlags.PressedOnDragDropHold) ImGuiButtonFlags.PressedOnDefault_ = ImGuiButtonFlags.PressedOnClickRelease ImGuiButtonFlags.NoKeyModifiers = ImGuiButtonFlags.NoKeyModsAllowed +-- Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. +-- - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. +-- During initialization or between frames, feel free to just poke into ImGuiStyle directly. +-- - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. --- @enum ImGuiStyleVar ImGuiStyleVar = { - Alpha = 0, - DisabledAlpha = 1, - WindowPadding = 2, - WindowRounding = 3, - WindowBorderSize = 4, - WindowMinSize = 5, - WindowTitleAlign = 6, - ChildRounding = 7, - ChildBorderSize = 8, - PopupRounding = 9, - PopupBorderSize = 10, - FramePadding = 11, - FrameRounding = 12, - FrameBorderSize = 13, - ItemSpacing = 14, - ItemInnerSpacing = 15, - IndentSpacing = 16, - CellPadding = 17, - ScrollbarSize = 18, - ScrollbarRounding = 19, - ScrollbarPadding = 20, - GrabMinSize = 21, - GrabRounding = 22, - ImageRounding = 23, - ImageBorderSize = 24, - TabRounding = 25, - TabBorderSize = 26, - TabMinWidthBase = 27, - TabMinWidthShrink = 28, - TabBarBorderSize = 29, - TabBarOverlineSize = 30, - TableAngledHeadersAngle = 31, - TableAngledHeadersTextAlign = 32, - TreeLinesSize = 33, - TreeLinesRounding = 34, - MenuItemRounding = 35, - SelectableRounding = 36, - DragDropTargetRounding = 37, - ButtonTextAlign = 38, - SelectableTextAlign = 39, - SeparatorTextBorderSize = 40, - SeparatorTextAlign = 41, - SeparatorTextPadding = 42, + -- Enum name -------------------------- -- Member in ImGuiStyle structure (see ImGuiStyle for descriptions) + Alpha = 0, -- float Alpha + DisabledAlpha = 1, -- float DisabledAlpha + WindowPadding = 2, -- ImVec2 WindowPadding + WindowRounding = 3, -- float WindowRounding + WindowBorderSize = 4, -- float WindowBorderSize + WindowMinSize = 5, -- ImVec2 WindowMinSize + WindowTitleAlign = 6, -- ImVec2 WindowTitleAlign + ChildRounding = 7, -- float ChildRounding + ChildBorderSize = 8, -- float ChildBorderSize + PopupRounding = 9, -- float PopupRounding + PopupBorderSize = 10, -- float PopupBorderSize + FramePadding = 11, -- ImVec2 FramePadding + FrameRounding = 12, -- float FrameRounding + FrameBorderSize = 13, -- float FrameBorderSize + ItemSpacing = 14, -- ImVec2 ItemSpacing + ItemInnerSpacing = 15, -- ImVec2 ItemInnerSpacing + IndentSpacing = 16, -- float IndentSpacing + CellPadding = 17, -- ImVec2 CellPadding + ScrollbarSize = 18, -- float ScrollbarSize + ScrollbarRounding = 19, -- float ScrollbarRounding + ScrollbarPadding = 20, -- float ScrollbarPadding + GrabMinSize = 21, -- float GrabMinSize + GrabRounding = 22, -- float GrabRounding + ImageRounding = 23, -- float ImageRounding + ImageBorderSize = 24, -- float ImageBorderSize + TabRounding = 25, -- float TabRounding + TabBorderSize = 26, -- float TabBorderSize + TabMinWidthBase = 27, -- float TabMinWidthBase + TabMinWidthShrink = 28, -- float TabMinWidthShrink + TabBarBorderSize = 29, -- float TabBarBorderSize + TabBarOverlineSize = 30, -- float TabBarOverlineSize + TableAngledHeadersAngle = 31, -- float TableAngledHeadersAngle + TableAngledHeadersTextAlign = 32, -- ImVec2 TableAngledHeadersTextAlign + TreeLinesSize = 33, -- float TreeLinesSize + TreeLinesRounding = 34, -- float TreeLinesRounding + MenuItemRounding = 35, -- float MenuItemRounding + SelectableRounding = 36, -- float SelectableRounding + DragDropTargetRounding = 37, -- float DragDropTargetRounding + ButtonTextAlign = 38, -- ImVec2 ButtonTextAlign + SelectableTextAlign = 39, -- ImVec2 SelectableTextAlign + SeparatorTextBorderSize = 40, -- float SeparatorTextBorderSize + SeparatorTextAlign = 41, -- ImVec2 SeparatorTextAlign + SeparatorTextPadding = 42, -- ImVec2 SeparatorTextPadding COUNT = 43 } +-- Flags for ImGui.IsItemHovered(), ImGui.IsWindowHovered() +-- Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ! +-- Note: windows with the ImGuiWindowFlags.NoInputs flag are ignored by IsWindowHovered() calls. --- @enum ImGuiHoveredFlags ImGuiHoveredFlags = { - None = 0, - ChildWindows = bitLShift(1, 0), - RootWindow = bitLShift(1, 1), - AnyWindow = bitLShift(1, 2), - NoPopupHierarchy = bitLShift(1, 3), - DockHierarchy = bitLShift(1, 4), - AllowWhenBlockedByPopup = bitLShift(1, 5), - AllowWhenBlockedByActiveItem = bitLShift(1, 7), - AllowWhenOverlappedByItem = bitLShift(1, 8), - AllowWhenOverlappedByWindow = bitLShift(1, 9), - AllowWhenDisabled = bitLShift(1, 10), - NoNavOverride = bitLShift(1, 11), - ForTooltip = bitLShift(1, 12), - Stationary = bitLShift(1, 13), - DelayNone = bitLShift(1, 14), - DelayShort = bitLShift(1, 15), - DelayNormal = bitLShift(1, 16), - NoSharedDelay = bitLShift(1, 17) + None = 0, -- Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. + ChildWindows = bitLShift(1, 0), -- IsWindowHovered() only: Return true if any children of the window is hovered + RootWindow = bitLShift(1, 1), -- IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) + AnyWindow = bitLShift(1, 2), -- IsWindowHovered() only: Return true if any window is hovered + NoPopupHierarchy = bitLShift(1, 3), -- IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + DockHierarchy = bitLShift(1, 4), -- IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + AllowWhenBlockedByPopup = bitLShift(1, 5), -- Return true even if a popup window is normally blocking access to this item/window + --ImGuiHoveredFlags.AllowWhenBlockedByModal = 1 << 6, -- Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. + AllowWhenBlockedByActiveItem = bitLShift(1, 7), -- Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. + AllowWhenOverlappedByItem = bitLShift(1, 8), -- IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item. + AllowWhenOverlappedByWindow = bitLShift(1, 9), -- IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window. + AllowWhenDisabled = bitLShift(1, 10), -- IsItemHovered() only: Return true even if the item is disabled + NoNavOverride = bitLShift(1, 11), -- IsItemHovered() only: Disable using keyboard/gamepad navigation state when active, always query mouse + -- Tooltips mode + -- - typically used in IsItemHovered() + SetTooltip() sequence. + -- - this is a shortcut to pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' where you can reconfigure desired behavior. + -- e.g. 'HoverFlagsForTooltipMouse' defaults to 'ImGuiHoveredFlags.Stationary | ImGuiHoveredFlags.DelayShort | ImGuiHoveredFlags.AllowWhenDisabled'. + -- - for frequently actioned or hovered items providing a tooltip, you want may to use ImGuiHoveredFlags.ForTooltip (stationary + delay) so the tooltip doesn't show too often. + -- - for items which main purpose is to be hovered, or items with low affordance, or in less consistent apps, prefer no delay or shorter delay. + ForTooltip = bitLShift(1, 12), -- Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence. + -- (Advanced) Mouse Hovering delays. + -- - generally you can use ImGuiHoveredFlags.ForTooltip to use application-standardized flags. + -- - use those if you need specific overrides. + Stationary = bitLShift(1, 13), -- Require mouse to be stationary for style.HoverStationaryDelay (~0.15 sec) _at least one time_. After this, can move on same item/window. Using the stationary test tends to reduces the need for a long delay. + DelayNone = bitLShift(1, 14), -- IsItemHovered() only: Return true immediately (default). As this is the default you generally ignore this. + DelayShort = bitLShift(1, 15), -- IsItemHovered() only: Return true after style.HoverDelayShort elapsed (~0.15 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). + DelayNormal = bitLShift(1, 16), -- IsItemHovered() only: Return true after style.HoverDelayNormal elapsed (~0.40 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). + NoSharedDelay = bitLShift(1, 17) -- IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) } +-- Flags for ImGui.IsWindowFocused() --- @enum ImGuiFocusedFlags ImGuiFocusedFlags = { None = 0, ChildWindows = bitLShift(1, 0), -- Return true if any children of the window is focused RootWindow = bitLShift(1, 1), -- Test from root window (top most parent of the current hierarchy) - AnyWindow = bitLShift(1, 2), -- Return true if any window is focused - NoPopupHierarchy = bitLShift(1, 3), -- Do not consider popup hierarchy - DockHierarchy = bitLShift(1, 4), -- Consider docking hierarchy + AnyWindow = bitLShift(1, 2), -- Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! + NoPopupHierarchy = bitLShift(1, 3), -- Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + DockHierarchy = bitLShift(1, 4), -- Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) } ImGuiFocusedFlags.RootAndChildWindows = bitOr(ImGuiFocusedFlags.RootWindow, ImGuiFocusedFlags.ChildWindows) @@ -32628,13 +37392,20 @@ ImGuiHoveredFlags.DelayMask_ = bitOr(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFl ImGuiHoveredFlags.AllowedMaskForIsWindowHovered = bitOr(ImGuiHoveredFlags.ChildWindows, ImGuiHoveredFlags.RootWindow, ImGuiHoveredFlags.AnyWindow, ImGuiHoveredFlags.NoPopupHierarchy, ImGuiHoveredFlags.DockHierarchy, ImGuiHoveredFlags.AllowWhenBlockedByPopup, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.Stationary) ImGuiHoveredFlags.AllowedMaskForIsItemHovered = bitOr(ImGuiHoveredFlags.AllowWhenBlockedByPopup, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, ImGuiHoveredFlags.AllowWhenOverlapped, ImGuiHoveredFlags.AllowWhenDisabled, ImGuiHoveredFlags.NoNavOverride, ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayMask_) +-- 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 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 latter 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 ImGuiKey = { + -- Keyboard None = 0, - NamedKey_BEGIN = 512, + NamedKey_BEGIN = 512, -- First valid key value (other than 0) - Tab = 512, + Tab = 512, -- == ImGuiKey.NamedKey_BEGIN LeftArrow = 513, RightArrow = 514, UpArrow = 515, @@ -32671,10 +37442,14 @@ ImGuiKey = { Keypad0 = 612, Keypad1 = 613, Keypad2 = 614, Keypad3 = 615, Keypad4 = 616, Keypad5 = 617, Keypad6 = 618, Keypad7 = 619, Keypad8 = 620, Keypad9 = 621, KeypadDecimal = 622, KeypadDivide = 623, KeypadMultiply = 624, KeypadSubtract = 625, KeypadAdd = 626, KeypadEnter = 627, KeypadEqual = 628, - AppBack = 629, + AppBack = 629, -- Available on some keyboard/mouses. Often referred as "Browser Back" AppForward = 630, - Oem102 = 631, + Oem102 = 631, -- Non-US backslash. + -- Gamepad + -- (analog values are 0.0f to 1.0f) + -- (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) + -- XBOX | SWITCH | PLAYSTA. | -> ACTION GamepadStart = 632, GamepadBack = 633, GamepadFaceLeft = 634, GamepadFaceRight = 635, GamepadFaceUp = 636, GamepadFaceDown = 637, GamepadDpadLeft = 638, GamepadDpadRight = 639, GamepadDpadUp = 640, GamepadDpadDown = 641, @@ -32688,121 +37463,138 @@ ImGuiKey = { ReservedForModCtrl = 663, ReservedForModShift = 664, ReservedForModAlt = 665, ReservedForModSuper = 666, + -- [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey.NamedKey_BEGIN..ImGuiKey.NamedKey_END. NamedKey_END = 667 } ImGuiKey.NamedKey_COUNT = ImGuiKey.NamedKey_END - ImGuiKey.NamedKey_BEGIN +-- Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) +-- - 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. +-- In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and +-- backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user... +-- - On macOS, we swap Cmd(Super) and Ctrl keys at the time of the io.AddKeyEvent() call. ImGuiMod_None = 0 -ImGuiMod_Ctrl = bitLShift(1, 12) -ImGuiMod_Shift = bitLShift(1, 13) -ImGuiMod_Alt = bitLShift(1, 14) -ImGuiMod_Super = bitLShift(1, 15) -ImGuiMod_Mask_ = 0xF000 +ImGuiMod_Ctrl = bitLShift(1, 12) -- Ctrl (non-macOS), Cmd (macOS) +ImGuiMod_Shift = bitLShift(1, 13) -- Shift +ImGuiMod_Alt = bitLShift(1, 14) -- Option/Menu +ImGuiMod_Super = bitLShift(1, 15) -- Windows/Super (non-macOS), Ctrl (macOS) +ImGuiMod_Mask_ = 0xF000 -- 4-bits +-- Enumeration for PushStyleColor() / PopStyleColor() --- @enum ImGuiCol ImGuiCol = { Text = 0, TextDisabled = 1, - WindowBg = 2, - ChildBg = 3, - PopupBg = 4, + WindowBg = 2, -- Background of normal windows + ChildBg = 3, -- Background of child windows + PopupBg = 4, -- Background of popups, menus, tooltips windows Border = 5, BorderShadow = 6, - FrameBg = 7, + FrameBg = 7, -- Background of checkbox, radio button, plot, slider, text input FrameBgHovered = 8, FrameBgActive = 9, - TitleBg = 10, - TitleBgActive = 11, - TitleBgCollapsed = 12, + TitleBg = 10, -- Title bar + TitleBgActive = 11, -- Title bar when focused + TitleBgCollapsed = 12, -- Title bar when collapsed MenuBarBg = 13, ScrollbarBg = 14, ScrollbarGrab = 15, ScrollbarGrabHovered = 16, ScrollbarGrabActive = 17, - CheckMark = 18, - CheckboxSelectedBg = 19, + CheckMark = 18, -- Checkbox tick and RadioButton circle + CheckboxSelectedBg = 19, -- Checkbox background when Selected, otherwise use FrameBg SliderGrab = 20, SliderGrabActive = 21, Button = 22, ButtonHovered = 23, ButtonActive = 24, - Header = 25, + Header = 25, -- Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem HeaderHovered = 26, HeaderActive = 27, Separator = 28, SeparatorHovered = 29, SeparatorActive = 30, - ResizeGrip = 31, + ResizeGrip = 31, -- Resize grip in lower-right and lower-left corners of windows. ResizeGripHovered = 32, ResizeGripActive = 33, - InputTextCursor = 34, - TabHovered = 35, - Tab = 36, - TabSelected = 37, - TabSelectedOverline = 38, - TabDimmed = 39, - TabDimmedSelected = 40, - TabDimmedSelectedOverline = 41, - DockingPreview = 42, - DockingEmptyBg = 43, + InputTextCursor = 34, -- InputText cursor/caret + TabHovered = 35, -- Tab background, when hovered + Tab = 36, -- Tab background, when tab-bar is focused & tab is unselected + TabSelected = 37, -- Tab background, when tab-bar is focused & tab is selected + TabSelectedOverline = 38, -- Tab horizontal overline, when tab-bar is focused & tab is selected + TabDimmed = 39, -- Tab background, when tab-bar is unfocused & tab is unselected + TabDimmedSelected = 40, -- Tab background, when tab-bar is unfocused & tab is selected + TabDimmedSelectedOverline = 41, -- ..horizontal overline, when tab-bar is unfocused & tab is selected + DockingPreview = 42, -- Preview overlay color when about to docking something + DockingEmptyBg = 43, -- Background color for empty node (e.g. CentralNode with no window docked into it) PlotLines = 44, PlotLinesHovered = 45, PlotHistogram = 46, PlotHistogramHovered = 47, - TableHeaderBg = 48, - TableBorderStrong = 49, - TableBorderLight = 50, - TableRowBg = 51, - TableRowBgAlt = 52, - TextLink = 53, - TextSelectedBg = 54, - TreeLines = 55, - DragDropTarget = 56, - DragDropTargetBg = 57, - UnsavedMarker = 58, - NavCursor = 59, - NavWindowingHighlight = 60, - NavWindowingDimBg = 61, - ModalWindowDimBg = 62, + TableHeaderBg = 48, -- Table header background + TableBorderStrong = 49, -- Table outer and header borders (prefer using Alpha=1.0 here) + TableBorderLight = 50, -- Table inner borders (prefer using Alpha=1.0 here) + TableRowBg = 51, -- Table row background (even rows) + TableRowBgAlt = 52, -- Table row background (odd rows) + TextLink = 53, -- Hyperlink color + TextSelectedBg = 54, -- Selected text inside an InputText + TreeLines = 55, -- Tree node hierarchy outlines when using ImGuiTreeNodeFlags.DrawLines + DragDropTarget = 56, -- Rectangle border highlighting a drop target + DragDropTargetBg = 57, -- Rectangle background highlighting a drop target + UnsavedMarker = 58, -- Unsaved Document marker (in window title and tabs) + NavCursor = 59, -- Color of keyboard/gamepad navigation cursor/rectangle, when visible + NavWindowingHighlight = 60, -- Highlight window when using Ctrl+Tab + NavWindowingDimBg = 61, -- Darken/colorize entire screen behind the Ctrl+Tab window list, when active + ModalWindowDimBg = 62, -- Darken/colorize entire screen behind a modal window, when one is active COUNT = 63 } +-- Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend. --- @enum ImGuiBackendFlags ImGuiBackendFlags = { None = 0, - HasGamepad = bitLShift(1, 0), - HasMouseCursors = bitLShift(1, 1), - HasSetMousePos = bitLShift(1, 2), - RendererHasVtxOffset = bitLShift(1, 3), - RendererHasTextures = bitLShift(1, 4), + HasGamepad = bitLShift(1, 0), -- Backend Platform supports gamepad and currently has one connected. + HasMouseCursors = bitLShift(1, 1), -- Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. + HasSetMousePos = bitLShift(1, 2), -- Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if io.ConfigNavMoveSetMousePos is set). + RendererHasVtxOffset = bitLShift(1, 3), -- Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. + RendererHasTextures = bitLShift(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] Multi-Viewports - RendererHasViewports = bitLShift(1, 10), - PlatformHasViewports = bitLShift(1, 11), - HasMouseHoveredViewport = bitLShift(1, 12), - HasParentViewport = bitLShift(1, 13) + RendererHasViewports = bitLShift(1, 10), -- Backend Renderer supports multiple viewports. + PlatformHasViewports = bitLShift(1, 11), -- Backend Platform supports multiple viewports. + HasMouseHoveredViewport = bitLShift(1, 12), -- Backend Platform supports calling io.AddMouseViewportEvent() with the viewport under the mouse. IF POSSIBLE, ignore viewports with the ImGuiViewportFlags.NoInputs flag (Win32 backend, GLFW 3.30+ backend can do this, SDL backend cannot). If this cannot be done, Dear ImGui needs to use a flawed heuristic to find the viewport under. + HasParentViewport = bitLShift(1, 13) -- Backend Platform supports honoring viewport->ParentViewport/ParentViewportId value, by applying the corresponding parent/child relationship at the Platform level. Child windows always appear in front of their parent window. } +-- Flags for ImGui.BeginDragDropSource(), ImGui.AcceptDragDropPayload() --- @enum ImGuiDragDropFlags ImGuiDragDropFlags = { None = 0, - SourceNoPreviewTooltip = bitLShift(1, 0), - SourceNoDisableHover = bitLShift(1, 1), - SourceNoHoldToOpenOthers = bitLShift(1, 2), - SourceAllowNullID = bitLShift(1, 3), - SourceExtern = bitLShift(1, 4), - PayloadAutoExpire = bitLShift(1, 5), - PayloadNoCrossContext = bitLShift(1, 6), - PayloadNoCrossProcess = bitLShift(1, 7), - AcceptBeforeDelivery = bitLShift(1, 10), - AcceptNoDrawDefaultRect = bitLShift(1, 11), - AcceptNoPreviewTooltip = bitLShift(1, 12), - AcceptDrawAsHovered = bitLShift(1, 13) + -- BeginDragDropSource() flags + SourceNoPreviewTooltip = bitLShift(1, 0), -- Disable preview tooltip. By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disables this behavior. + SourceNoDisableHover = bitLShift(1, 1), -- By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disables this behavior so you can still call IsItemHovered() on the source item. + SourceNoHoldToOpenOthers = bitLShift(1, 2), -- Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. + SourceAllowNullID = bitLShift(1, 3), -- Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. + SourceExtern = bitLShift(1, 4), -- External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. + PayloadAutoExpire = bitLShift(1, 5), -- Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) + PayloadNoCrossContext = bitLShift(1, 6), -- Hint to specify that the payload may not be copied outside current dear imgui context. + PayloadNoCrossProcess = bitLShift(1, 7), -- Hint to specify that the payload may not be copied outside current process. + -- AcceptDragDropPayload() flags + AcceptBeforeDelivery = bitLShift(1, 10), -- AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. + AcceptNoDrawDefaultRect = bitLShift(1, 11), -- Do not draw the default highlight rectangle when hovering over target. + AcceptNoPreviewTooltip = bitLShift(1, 12), -- Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. + AcceptDrawAsHovered = bitLShift(1, 13) -- Accepting item will render as if hovered. Useful for e.g. a Button() used as a drop target. } -ImGuiDragDropFlags.AcceptPeekOnly = bitOr(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoDrawDefaultRect) +ImGuiDragDropFlags.AcceptPeekOnly = bitOr(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoDrawDefaultRect) -- For peeking ahead and inspecting the payload before delivery. +-- Helpers macros to generate 32-bit encoded colors IM_COL32_R_SHIFT = 0 IM_COL32_G_SHIFT = 8 IM_COL32_B_SHIFT = 16 @@ -32818,121 +37610,145 @@ IM_COL32_WHITE = IM_COL32(255, 255, 255, 255) IM_COL32_BLACK = IM_COL32(0, 0, 0, 255) IM_COL32_BLACK_TRANS = IM_COL32(0, 0, 0, 0) +-- Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. +-- - IMPORTANT: If you ever used the left mouse button with BeginPopupContextXXX() helpers before 1.92.6: Read "API BREAKING CHANGES" 2026/01/07 (1.92.6) entry in imgui.cpp or GitHub topic #9157. +-- - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). --- @enum ImGuiPopupFlags ImGuiPopupFlags = { None = 0, - MouseButtonLeft = bitLShift(1, 2), - MouseButtonRight = bitLShift(2, 2), - MouseButtonMiddle = bitLShift(3, 2), - NoReopen = bitLShift(1, 5), - NoOpenOverExistingPopup = bitLShift(1, 7), - NoOpenOverItems = bitLShift(1, 8), - AnyPopupId = bitLShift(1, 10), - AnyPopupLevel = bitLShift(1, 11) + MouseButtonLeft = bitLShift(1, 2), -- For BeginPopupContext*(): open on Left Mouse release. Only one button allowed! + MouseButtonRight = bitLShift(2, 2), -- For BeginPopupContext*(): open on Right Mouse release. Only one button allowed! (default) + MouseButtonMiddle = bitLShift(3, 2), -- For BeginPopupContext*(): open on Middle Mouse release. Only one button allowed! + NoReopen = bitLShift(1, 5), -- For OpenPopup*(), BeginPopupContext*(): don't reopen same popup if already open (won't reposition, won't reinitialize navigation) + --ImGuiPopupFlags.NoReopenAlwaysNavInit = 1 << 6, -- For OpenPopup*(), BeginPopupContext*(): focus and initialize navigation even when not reopening. + NoOpenOverExistingPopup = bitLShift(1, 7), -- For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack + NoOpenOverItems = bitLShift(1, 8), -- For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space + AnyPopupId = bitLShift(1, 10), -- For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. + AnyPopupLevel = bitLShift(1, 11) -- For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) } ImGuiPopupFlags.AnyPopup = bitOr(ImGuiPopupFlags.AnyPopupId, ImGuiPopupFlags.AnyPopupLevel) -ImGuiPopupFlags.MouseButtonShift_ = 2 -ImGuiPopupFlags.MouseButtonMask_ = 0x0C -ImGuiPopupFlags.InvalidMask_ = 0x03 +ImGuiPopupFlags.MouseButtonShift_ = 2 -- [Internal] +ImGuiPopupFlags.MouseButtonMask_ = 0x0C -- [Internal] +ImGuiPopupFlags.InvalidMask_ = 0x03 -- [Internal] Reserve legacy bits 0-1 to detect incorrectly passing 1 or 2 to the function. +-- Flags for ImGui.BeginCombo() --- @enum ImGuiComboFlags ImGuiComboFlags = { None = 0, - PopupAlignLeft = bitLShift(1, 0), - HeightSmall = bitLShift(1, 1), - HeightRegular = bitLShift(1, 2), - HeightLarge = bitLShift(1, 3), - HeightLargest = bitLShift(1, 4), - NoArrowButton = bitLShift(1, 5), - NoPreview = bitLShift(1, 6), - WidthFitPreview = bitLShift(1, 7) + PopupAlignLeft = bitLShift(1, 0), -- Align the popup toward the left by default + HeightSmall = bitLShift(1, 1), -- Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() + HeightRegular = bitLShift(1, 2), -- Max ~8 items visible (default) + HeightLarge = bitLShift(1, 3), -- Max ~20 items visible + HeightLargest = bitLShift(1, 4), -- As many fitting items as possible + NoArrowButton = bitLShift(1, 5), -- Display on the preview box without the square arrow button + NoPreview = bitLShift(1, 6), -- Display only a square arrow button + WidthFitPreview = bitLShift(1, 7) -- Width dynamically calculated from preview contents } ImGuiComboFlags.HeightMask_ = bitOr(ImGuiComboFlags.HeightSmall, ImGuiComboFlags.HeightRegular, ImGuiComboFlags.HeightLarge, ImGuiComboFlags.HeightLargest) ImGuiComboFlags.CustomPreview = bitLShift(1, 20) +-- Flags for ImGui.Selectable() --- @enum ImGuiSelectableFlags ImGuiSelectableFlags = { None = 0, - NoAutoClosePopups = bitLShift(1, 0), - SpanAllColumns = bitLShift(1, 1), - AllowDoubleClick = bitLShift(1, 2), - Disabled = bitLShift(1, 3), - AllowOverlap = bitLShift(1, 4), - Highlight = bitLShift(1, 5), - SelectOnNav = bitLShift(1, 6), + NoAutoClosePopups = bitLShift(1, 0), -- Clicking this doesn't close parent popup window (overrides ImGuiItemFlags.AutoClosePopups) + SpanAllColumns = bitLShift(1, 1), -- Frame will span all columns of its container table (text will still fit in current column) + AllowDoubleClick = bitLShift(1, 2), -- Generate press events on double clicks too + Disabled = bitLShift(1, 3), -- Cannot be selected, display grayed out text + AllowOverlap = bitLShift(1, 4), -- Hit testing will allow subsequent widgets to overlap this one. Require previous frame HoveredId to match before being usable. Shortcut to calling SetNextItemAllowOverlap(). + Highlight = bitLShift(1, 5), -- Make the item be displayed as if it is hovered + SelectOnNav = bitLShift(1, 6), -- Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block. + -- NB: need to be in sync with last value of ImGuiSelectableFlags_ NoHoldingActiveID = bitLShift(1, 20), - SelectOnClick = bitLShift(1, 22), - SelectOnRelease = bitLShift(1, 23), - SpanAvailWidth = bitLShift(1, 24), - SetNavIdOnHover = bitLShift(1, 25), - NoPadWithHalfSpacing = bitLShift(1, 26), - NoSetKeyOwner = bitLShift(1, 27), + SelectOnClick = bitLShift(1, 22), -- Override button behavior to react on Click (default is Click+Release) + SelectOnRelease = bitLShift(1, 23), -- Override button behavior to react on Release (default is Click+Release) + SpanAvailWidth = bitLShift(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) + SetNavIdOnHover = bitLShift(1, 25), -- Set Nav/Focus ID on mouse hover (used by MenuItem) + NoPadWithHalfSpacing = bitLShift(1, 26), -- Disable padding each side with ItemSpacing * 0.5f + NoSetKeyOwner = bitLShift(1, 27), -- Don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey.MouseLeft!) } +-- Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() --- @enum ImGuiColorEditFlags ImGuiColorEditFlags = { None = 0, - NoAlpha = bitLShift(1, 1), - NoPicker = bitLShift(1, 2), - NoOptions = bitLShift(1, 3), - NoSmallPreview = bitLShift(1, 4), - NoInputs = bitLShift(1, 5), - NoTooltip = bitLShift(1, 6), - NoLabel = bitLShift(1, 7), - NoSidePreview = bitLShift(1, 8), - NoDragDrop = bitLShift(1, 9), - NoBorder = bitLShift(1, 10), - NoColorMarkers = bitLShift(1, 11), + NoAlpha = bitLShift(1, 1), -- ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). + NoPicker = bitLShift(1, 2), -- ColorEdit: disable picker when clicking on color square. + NoOptions = bitLShift(1, 3), -- ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. + NoSmallPreview = bitLShift(1, 4), -- ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) + NoInputs = bitLShift(1, 5), -- ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). + NoTooltip = bitLShift(1, 6), -- ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. + NoLabel = bitLShift(1, 7), -- ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). + NoSidePreview = bitLShift(1, 8), -- ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. + NoDragDrop = bitLShift(1, 9), -- ColorEdit: disable drag and drop target/source. ColorButton: disable drag and drop source. + NoBorder = bitLShift(1, 10), -- ColorButton: disable border (which is enforced by default) + NoColorMarkers = bitLShift(1, 11), -- ColorEdit: disable rendering R/G/B/A color marker. May also be disabled globally by setting style.ColorMarkerSize = 0. -- Alpha preview - AlphaOpaque = bitLShift(1, 12), - AlphaNoBg = bitLShift(1, 13), - AlphaPreviewHalf = bitLShift(1, 14), + AlphaOpaque = bitLShift(1, 12), -- 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. + AlphaNoBg = bitLShift(1, 13), -- ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color. + AlphaPreviewHalf = bitLShift(1, 14), -- ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview. -- User Options (right-click on widget to change some of them) - AlphaBar = bitLShift(1, 18), - HDR = bitLShift(1, 19), - DisplayRGB = bitLShift(1, 20), - DisplayHSV = bitLShift(1, 21), - DisplayHex = bitLShift(1, 22), - Uint8 = bitLShift(1, 23), - Float = bitLShift(1, 24), - PickerHueBar = bitLShift(1, 25), - PickerHueWheel = bitLShift(1, 26), - PickerNoRotate = bitLShift(1, 27), - InputRGB = bitLShift(1, 28), - InputHSV = bitLShift(1, 29) + AlphaBar = bitLShift(1, 18), -- ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. + HDR = bitLShift(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). + DisplayRGB = bitLShift(1, 20), -- [Display] -- ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. + DisplayHSV = bitLShift(1, 21), -- [Display] -- " + DisplayHex = bitLShift(1, 22), -- [Display] -- " + Uint8 = bitLShift(1, 23), -- [DataType] -- ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. + Float = bitLShift(1, 24), -- [DataType] -- ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. + PickerHueBar = bitLShift(1, 25), -- [Picker] -- ColorPicker: bar for Hue, rectangle for Sat/Value. + PickerHueWheel = bitLShift(1, 26), -- [Picker] -- ColorPicker: wheel for Hue, triangle for Sat/Value. + PickerNoRotate = bitLShift(1, 27), -- [Picker] -- ColorPicker: disable rotating Sat/Value triangle. Best set in io.ConfigColorEditFlags once. + InputRGB = bitLShift(1, 28), -- [Input] -- ColorEdit, ColorPicker: input and output data in RGB format. + InputHSV = bitLShift(1, 29) -- [Input] -- ColorEdit, ColorPicker: input and output data in HSV format. } +-- Defaults Options copied to io.ConfigColorEditFlags during initialization. +-- The intent is that you probably don't want to override them in most of your calls. +-- Let the user choose via the option menu and/or modify io.ConfigColorEditFlags directly during startup if you want. ImGuiColorEditFlags.DefaultOptions_ = bitOr(ImGuiColorEditFlags.Uint8, ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.InputRGB, ImGuiColorEditFlags.PickerHueBar) +-- [Internal] Masks ImGuiColorEditFlags.AlphaMask_ = bitOr( ImGuiColorEditFlags.NoAlpha, ImGuiColorEditFlags.AlphaOpaque, ImGuiColorEditFlags.AlphaNoBg, ImGuiColorEditFlags.AlphaPreviewHalf ) ImGuiColorEditFlags.DisplayMask_ = bitOr( ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.DisplayHSV, ImGuiColorEditFlags.DisplayHex ) ImGuiColorEditFlags.DataTypeMask_ = bitOr( ImGuiColorEditFlags.Uint8, ImGuiColorEditFlags.Float ) ImGuiColorEditFlags.PickerMask_ = bitOr( ImGuiColorEditFlags.PickerHueWheel, ImGuiColorEditFlags.PickerHueBar ) ImGuiColorEditFlags.InputMask_ = bitOr( ImGuiColorEditFlags.InputRGB, ImGuiColorEditFlags.InputHSV ) +-- Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +-- We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. +-- (Those are per-item flags. There is shared behavior flag too: ImGuiIO: io.ConfigDragClickToInputText) --- @enum ImGuiSliderFlags ImGuiSliderFlags = { None = 0, - Logarithmic = bitLShift(1, 5), - NoRoundToFormat = bitLShift(1, 6), - NoInput = bitLShift(1, 7), - WrapAround = bitLShift(1, 8), - ClampOnInput = bitLShift(1, 9), - ClampZeroRange = bitLShift(1, 10), - NoSpeedTweaks = bitLShift(1, 11), - ColorMarkers = bitLShift(1, 12), - InvalidMask_ = 0x7000000F, + Logarithmic = bitLShift(1, 5), -- Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags.NoRoundToFormat with this if using a format-string with small amount of digits. + NoRoundToFormat = bitLShift(1, 6), -- Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). + NoInput = bitLShift(1, 7), -- Disable Ctrl+Click or Enter key allowing to input text directly into the widget. + WrapAround = bitLShift(1, 8), -- Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now. + ClampOnInput = bitLShift(1, 9), -- Clamp value to min/max bounds when input manually with Ctrl+Click. By default Ctrl+Click allows going out of bounds. + ClampZeroRange = bitLShift(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. + NoSpeedTweaks = bitLShift(1, 11), -- Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. + ColorMarkers = bitLShift(1, 12), -- DragScalarN(), SliderScalarN(): Draw R/G/B/A color markers on each component. + --ImGuiSliderFlags.LiveEditOnInput = 1 << 13, -- Shortcut to enable LiveEdit for this field. + --ImGuiSliderFlags.NoLiveEditOnInput= 1 << 14, -- Shortcut to disable LiveEdit for this field. + InvalidMask_ = 0x7000000F, -- [Internal] We treat using those bits as being potentially a 'float power' argument from legacy API (obsoleted 2020-08) that has got miscast to this enum, and will trigger an assert if needed. } ImGuiSliderFlags.AlwaysClamp = bitOr(ImGuiSliderFlags.ClampOnInput, ImGuiSliderFlags.ClampZeroRange) -ImGuiSliderFlags.Vertical = bitLShift(1, 20) -ImGuiSliderFlags.ReadOnly = bitLShift(1, 21) +ImGuiSliderFlags.Vertical = bitLShift(1, 20) -- Should this slider be orientated vertically? +ImGuiSliderFlags.ReadOnly = bitLShift(1, 21) -- Consider using g.NextItemData.ItemFlags |= ImGuiItemFlags.ReadOnly instead. +-- [ALPHA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions. +-- Important: the content of this class is still highly WIP and likely to change and be refactored +-- before we stabilize Docking features. Please be mindful if using this. +-- Provide hints: +-- - To the platform backend via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) +-- - To the platform backend for OS level parent/child relationships of viewport (otherwise: default is configured via io.ConfigViewportsNoDefaultParent) +-- - To the docking system for various options and filtering. --- @class ImGuiWindowClass --- @field ClassId ImGuiID --- @field ParentViewportId ImGuiID @@ -32944,66 +37760,82 @@ ImGuiSliderFlags.ReadOnly = bitLShift(1, 21) --- @nodiscard function ImGuiWindowClass() return { - ClassId = 0, - ParentViewportId = 0xFFFFFFFF, - FocusRouteParentWindowId = 0, - ViewportFlagsOverrideSet = 0, - ViewportFlagsOverrideClear = 0, + ClassId = 0, -- User data. 0 = Default class (unclassed). Windows of different classes cannot be docked with each others. + ParentViewportId = 0xFFFFFFFF, -- Hint for the platform backend. -1: use default. 0: request platform backend to not parent the platform. != 0: request platform backend to create a parent<>child relationship between the platform windows. Not conforming backends are free to e.g. parent every viewport to the main viewport or not. + FocusRouteParentWindowId = 0, -- ID of parent window for shortcut focus route evaluation, e.g. Shortcut() call from Parent Window will succeed when this window is focused. + ViewportFlagsOverrideSet = 0, -- Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ViewportFlagsOverrideClear = 0, -- Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. - TabItemFlagsOverrideSet = 0, - DockNodeFlagsOverrideSet = 0, - DockingAlwaysTabBar = false, - DockingAllowUnclassed = true + TabItemFlagsOverrideSet = 0, -- [EXPERIMENTAL] TabItem flags to set when a window of this class gets submitted into a dock node tab bar. May use with ImGuiTabItemFlags.Leading or ImGuiTabItemFlags.Trailing. + DockNodeFlagsOverrideSet = 0, -- [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) + DockingAlwaysTabBar = false, -- Set to true to enforce single floating windows of this class always having their own docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar) + DockingAllowUnclassed = true -- Set to true to allow windows of this class to be docked/merged with an unclassed window. -- FIXME-DOCK: Move to DockNodeFlags override? } end +-- Flags for ImGui.InputText() +-- (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigInputTextCursorBlink and io.ConfigInputTextEnterKeepActive) --- @enum ImGuiInputTextFlags ImGuiInputTextFlags = { + -- Basic filters (also see ImGuiInputTextFlags.CallbackCharFilter) None = 0, -- Basic filters (also see ImGuiInputTextFlags.CallbackCharFilter) - CharsDecimal = bitLShift(1, 0), - CharsHexadecimal = bitLShift(1, 1), - CharsScientific = bitLShift(1, 2), - CharsUppercase = bitLShift(1, 3), - CharsNoBlank = bitLShift(1, 4), + CharsDecimal = bitLShift(1, 0), -- Allow 0123456789.+-*/ + CharsHexadecimal = bitLShift(1, 1), -- Allow 0123456789ABCDEFabcdef + CharsScientific = bitLShift(1, 2), -- Allow 0123456789.+-*/eE (Scientific notation input) + CharsUppercase = bitLShift(1, 3), -- Turn a..z into A..Z + CharsNoBlank = bitLShift(1, 4), -- Filter out spaces, tabs -- Inputs - AllowTabInput = bitLShift(1, 5), - EnterReturnsTrue = bitLShift(1, 6), - EscapeClearsAll = bitLShift(1, 7), - CtrlEnterForNewLine = bitLShift(1, 8), + AllowTabInput = bitLShift(1, 5), -- Pressing TAB input a '\t' character into the text field + EnterReturnsTrue = bitLShift(1, 6), -- Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider disabling LiveEdit! or using IsItemDeactivatedAfterEdit() instead! + EscapeClearsAll = bitLShift(1, 7), -- Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) + CtrlEnterForNewLine = bitLShift(1, 8), -- In multi-line mode: validate with Enter, add new line with Ctrl+Enter (default is opposite: validate with Ctrl+Enter, add line with Enter). Note that Shift+Enter always enter a new line either way. -- Other options - ReadOnly = bitLShift(1, 9), - Password = bitLShift(1, 10), - AlwaysOverwrite = bitLShift(1, 11), - AutoSelectAll = bitLShift(1, 12), - ParseEmptyRefVal = bitLShift(1, 13), - DisplayEmptyRefVal = bitLShift(1, 14), - NoHorizontalScroll = bitLShift(1, 15), - NoUndoRedo = bitLShift(1, 16), + ReadOnly = bitLShift(1, 9), -- Read-only mode + Password = bitLShift(1, 10), -- Password mode, display all characters as '*', disable copy + AlwaysOverwrite = bitLShift(1, 11), -- Overwrite mode + AutoSelectAll = bitLShift(1, 12), -- Select entire text when first taking mouse focus + ParseEmptyRefVal = bitLShift(1, 13), -- InputFloat(), InputInt(), InputScalar() etc. only: parse empty string as zero value. + DisplayEmptyRefVal = bitLShift(1, 14), -- InputFloat(), InputInt(), InputScalar() etc. only: when value is zero, do not display it. Generally used with ImGuiInputTextFlags.ParseEmptyRefVal. + NoHorizontalScroll = bitLShift(1, 15), -- Disable following the cursor horizontally + NoUndoRedo = bitLShift(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 - ElideLeft = bitLShift(1, 17), + ElideLeft = bitLShift(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 - CallbackCompletion = bitLShift(1, 18), - CallbackHistory = bitLShift(1, 19), - CallbackAlways = bitLShift(1, 20), - CallbackCharFilter = bitLShift(1, 21), - CallbackResize = bitLShift(1, 22), - CallbackEdit = bitLShift(1, 23), + CallbackCompletion = bitLShift(1, 18), -- Callback on pressing TAB (for completion handling) + CallbackHistory = bitLShift(1, 19), -- Callback on pressing Up/Down arrows (for history handling) + CallbackAlways = bitLShift(1, 20), -- Callback on each iteration. User code may query cursor position, modify text buffer. + CallbackCharFilter = bitLShift(1, 21), -- Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. + CallbackResize = bitLShift(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) + CallbackEdit = bitLShift(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] - WordWrap = bitLShift(1, 24), + WordWrap = bitLShift(1, 24), -- InputTextMultiline(): word-wrap lines that are too long. -- [Internal] - Multiline = bitLShift(1, 26), - TempInput = bitLShift(1, 27), - LocalizeDecimalPoint = bitLShift(1, 28), + Multiline = bitLShift(1, 26), -- For internal use by InputTextMultiline() + TempInput = bitLShift(1, 27), -- For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match. + LocalizeDecimalPoint = bitLShift(1, 28), -- For internal use by InputScalar() and TempInputScalar() } +------------------------------------------------------------------------------- +-- [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) +------------------------------------------------------------------------------- + +-- 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 + 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 +-- - ImGuiInputTextFlags.CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. +-- - ImGuiInputTextFlags.CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. --- @class ImGuiInputTextCallbackData --- @return ImGuiInputTextCallbackData @@ -33064,40 +37896,51 @@ function MT.ImGuiInputTextCallbackData:SelectAll() self.SelectionStart = 0; self function MT.ImGuiInputTextCallbackData:ClearSelection() self.SelectionStart = self.BufTextLen; self.SelectionEnd = self.BufTextLen end function MT.ImGuiInputTextCallbackData:HasSelection() return self.SelectionStart ~= self.SelectionEnd end +-- Callback and functions types --- @alias ImGuiInputTextCallback fun(data: ImGuiInputTextCallbackData) --- @alias ImGuiMemAllocFunc fun(T: function, start_idx: int, end_idx: int, userdata: any): table --- @alias ImGuiMemFreeFunc fun(owner: table, field: string, userdata: any) +-- ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] +-- NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, +-- you can poke into the draw list for that! Draw callback may be useful for example to: +-- A) Change your GPU render state, +-- B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. +-- The expected behavior from your rendering function is 'if (cmd.UserCallback != nil) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' --- @alias ImDrawCallback fun(parent_list: ImDrawList, cmd: ImDrawCmd) +-- Flags for ImGui.TreeNodeEx(), ImGui.CollapsingHeader*() --- @enum ImGuiTreeNodeFlags ImGuiTreeNodeFlags = { None = 0, - Selected = bitLShift(1, 0), - Framed = bitLShift(1, 1), - AllowOverlap = bitLShift(1, 2), - NoTreePushOnOpen = bitLShift(1, 3), - NoAutoOpenOnLog = bitLShift(1, 4), - DefaultOpen = bitLShift(1, 5), - OpenOnDoubleClick = bitLShift(1, 6), - OpenOnArrow = bitLShift(1, 7), - Leaf = bitLShift(1, 8), - Bullet = bitLShift(1, 9), - FramePadding = bitLShift(1, 10), - SpanAvailWidth = bitLShift(1, 11), - SpanFullWidth = bitLShift(1, 12), - SpanLabelWidth = bitLShift(1, 13), - SpanAllColumns = bitLShift(1, 14), - LabelSpanAllColumns = bitLShift(1, 15), - NavLeftJumpsToParent = bitLShift(1, 17), - DrawLinesNone = bitLShift(1, 18), - DrawLinesFull = bitLShift(1, 19), - DrawLinesToNodes = bitLShift(1, 20), + Selected = bitLShift(1, 0), -- Draw as selected + Framed = bitLShift(1, 1), -- Draw frame with background (e.g. for CollapsingHeader) + AllowOverlap = bitLShift(1, 2), -- Hit testing will allow subsequent widgets to overlap this one. Require previous frame HoveredId to match before being usable. Shortcut to calling SetNextItemAllowOverlap(). + NoTreePushOnOpen = bitLShift(1, 3), -- Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + NoAutoOpenOnLog = bitLShift(1, 4), -- Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + DefaultOpen = bitLShift(1, 5), -- Default node to be open + OpenOnDoubleClick = bitLShift(1, 6), -- Open on double-click instead of simple click (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. + OpenOnArrow = bitLShift(1, 7), -- Open when clicking on the arrow part (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. + Leaf = bitLShift(1, 8), -- No collapsing, no arrow (use as a convenience for leaf nodes). Note: will always open a tree/id scope and return true. If you never use that scope, add ImGuiTreeNodeFlags.NoTreePushOnOpen. + Bullet = bitLShift(1, 9), -- Display a bullet instead of arrow. IMPORTANT: node can still be marked open/close if you don't set the _Leaf flag! + FramePadding = bitLShift(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. + SpanAvailWidth = bitLShift(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. + SpanFullWidth = bitLShift(1, 12), -- Extend hit box to the left-most and right-most edges (cover the indent area). + SpanLabelWidth = bitLShift(1, 13), -- Narrow hit box + narrow hovering highlight, will only cover the label text. + SpanAllColumns = bitLShift(1, 14), -- Frame will span all columns of its container table (label will still fit in current column) + LabelSpanAllColumns = bitLShift(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 + NavLeftJumpsToParent = bitLShift(1, 17), -- Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfulfilled Left nav request remaining. + -- [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920. + -- Default value is pulled from style.TreeLinesFlags. May be overridden in TreeNode calls. + DrawLinesNone = bitLShift(1, 18), -- No lines drawn + DrawLinesFull = bitLShift(1, 19), -- Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. Faster (for large trees). + DrawLinesToNodes = bitLShift(1, 20), -- Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). - NoNavFocus = bitLShift(1, 27), - ClipLabelForTrailingButton = bitLShift(1, 28), - UpsideDownArrow = bitLShift(1, 29), + NoNavFocus = bitLShift(1, 27), -- Don't claim nav focus when interacting with this item (#8551) + ClipLabelForTrailingButton = bitLShift(1, 28), -- FIXME-WIP: Hard-coded for CollapsingHeader() + UpsideDownArrow = bitLShift(1, 29), -- FIXME-WIP: Turn Down arrow into an Up arrow, for reversed trees (#6517) } ImGuiTreeNodeFlags.CollapsingHeader = bitOr(ImGuiTreeNodeFlags.Framed, ImGuiTreeNodeFlags.NoTreePushOnOpen, ImGuiTreeNodeFlags.NoAutoOpenOnLog) @@ -33105,94 +37948,152 @@ ImGuiTreeNodeFlags.CollapsingHeader = bitOr(ImGuiTreeNodeFlags.Framed, ImGuiTree ImGuiTreeNodeFlags.OpenOnMask_ = bitOr(ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.OpenOnArrow) ImGuiTreeNodeFlags.DrawLinesMask_ = bitOr(ImGuiTreeNodeFlags.DrawLinesNone, ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DrawLinesToNodes) +------------------------------------------------------------------------------- +-- [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +------------------------------------------------------------------------------- + +-- Flags for ImGui.BeginTable() +-- - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. +-- Read comments/demos carefully + experiment with live demos to get acquainted with them. +-- - The DEFAULT sizing policies are: +-- - Default to ImGuiTableFlags.SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags.AlwaysAutoResize. +-- - Default to ImGuiTableFlags.SizingStretchSame if ScrollX is off. +-- - When ScrollX is off: +-- - Table defaults to ImGuiTableFlags.SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags.WidthStretch with same weight. +-- - Columns sizing policy allowed: Stretch (default), Fixed/Auto. +-- - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). +-- - Stretch Columns will share the remaining width according to their respective weight. +-- - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. +-- The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +-- (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). +-- - When ScrollX is on: +-- - Table defaults to ImGuiTableFlags.SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags.WidthFixed +-- - Columns sizing policy allowed: Fixed/Auto mostly. +-- - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed. +-- - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. +-- - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). +-- If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. +-- - Read on documentation at the top of imgui_tables.cpp for details. --- @enum ImGuiTableFlags ImGuiTableFlags = { + -- Features None = 0, - Resizable = bitLShift(1, 0), - Reorderable = bitLShift(1, 1), - Hideable = bitLShift(1, 2), - Sortable = bitLShift(1, 3), - NoSavedSettings = bitLShift(1, 4), - ContextMenuInBody = bitLShift(1, 5), - RowBg = bitLShift(1, 6), - BordersInnerH = bitLShift(1, 7), - BordersOuterH = bitLShift(1, 8), - BordersInnerV = bitLShift(1, 9), - BordersOuterV = bitLShift(1, 10), - NoBordersInBody = bitLShift(1, 11), - NoBordersInBodyUntilResize = bitLShift(1, 12), - SizingFixedFit = bitLShift(1, 13), - SizingFixedSame = bitLShift(2, 13), - SizingStretchProp = bitLShift(3, 13), - SizingStretchSame = bitLShift(4, 13), - NoHostExtendX = bitLShift(1, 16), - NoHostExtendY = bitLShift(1, 17), - NoKeepColumnsVisible = bitLShift(1, 18), - PreciseWidths = bitLShift(1, 19), - NoClip = bitLShift(1, 20), - PadOuterX = bitLShift(1, 21), - NoPadOuterX = bitLShift(1, 22), - NoPadInnerX = bitLShift(1, 23), - ScrollX = bitLShift(1, 24), - ScrollY = bitLShift(1, 25), - SortMulti = bitLShift(1, 26), - SortTristate = bitLShift(1, 27), - HighlightHoveredColumn = bitLShift(1, 28), + Resizable = bitLShift(1, 0), -- Enable resizing columns. + Reorderable = bitLShift(1, 1), -- Enable reordering columns in header row. (Need calling TableSetupColumn() + TableHeadersRow() to display headers, or using ImGuiTableFlags.ContextMenuInBody to access context-menu without headers). + Hideable = bitLShift(1, 2), -- Enable hiding/disabling columns in context menu. + Sortable = bitLShift(1, 3), -- Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags.SortMulti and ImGuiTableFlags.SortTristate. + NoSavedSettings = bitLShift(1, 4), -- Disable persisting columns order, width, visibility and sort settings in the .ini file. + ContextMenuInBody = bitLShift(1, 5), -- Right-click on columns body/contents will also display table context menu. By default it is available in TableHeadersRow(). + -- Decorations + RowBg = bitLShift(1, 6), -- Set each RowBg color with ImGuiCol.TableRowBg or ImGuiCol.TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags.RowBg0 on each row manually) + BordersInnerH = bitLShift(1, 7), -- Draw horizontal borders between rows. + BordersOuterH = bitLShift(1, 8), -- Draw horizontal borders at the top and bottom. + BordersInnerV = bitLShift(1, 9), -- Draw vertical borders between columns. + BordersOuterV = bitLShift(1, 10), -- Draw vertical borders on the left and right sides. + NoBordersInBody = bitLShift(1, 11), -- [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style + NoBordersInBodyUntilResize = bitLShift(1, 12), -- [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style + -- Sizing Policy (read above for defaults) + SizingFixedFit = bitLShift(1, 13), -- Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. + SizingFixedSame = bitLShift(2, 13), -- Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags.NoKeepColumnsVisible. + SizingStretchProp = bitLShift(3, 13), -- Columns default to _WidthStretch with default weights proportional to each columns contents widths. + SizingStretchSame = bitLShift(4, 13), -- Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). + -- Sizing Extra Options + NoHostExtendX = bitLShift(1, 16), -- Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. + NoHostExtendY = bitLShift(1, 17), -- Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. + NoKeepColumnsVisible = bitLShift(1, 18), -- Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. + PreciseWidths = bitLShift(1, 19), -- Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. + -- Clipping + NoClip = bitLShift(1, 20), -- Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). + -- Padding + PadOuterX = bitLShift(1, 21), -- Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. + NoPadOuterX = bitLShift(1, 22), -- Default if BordersOuterV is off. Disable outermost padding. + NoPadInnerX = bitLShift(1, 23), -- Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). + -- Scrolling + ScrollX = bitLShift(1, 24), -- Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. + ScrollY = bitLShift(1, 25), -- Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + -- Sorting + SortMulti = bitLShift(1, 26), -- Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). + SortTristate = bitLShift(1, 27), -- Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). + -- Miscellaneous + HighlightHoveredColumn = bitLShift(1, 28), -- Highlight column headers when hovered (may evolve into a fuller highlight) } -ImGuiTableFlags.BordersH = bitOr(ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.BordersOuterH) -ImGuiTableFlags.BordersV = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersOuterV) -ImGuiTableFlags.BordersInner = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersInnerH) -ImGuiTableFlags.BordersOuter = bitOr(ImGuiTableFlags.BordersOuterV, ImGuiTableFlags.BordersOuterH) -ImGuiTableFlags.Borders = bitOr(ImGuiTableFlags.BordersInner, ImGuiTableFlags.BordersOuter) +ImGuiTableFlags.BordersH = bitOr(ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.BordersOuterH) -- Draw horizontal borders. +ImGuiTableFlags.BordersV = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersOuterV) -- Draw vertical borders. +ImGuiTableFlags.BordersInner = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersInnerH) -- Draw inner borders. +ImGuiTableFlags.BordersOuter = bitOr(ImGuiTableFlags.BordersOuterV, ImGuiTableFlags.BordersOuterH) -- Draw outer borders. +ImGuiTableFlags.Borders = bitOr(ImGuiTableFlags.BordersInner, ImGuiTableFlags.BordersOuter) -- Draw all borders. +-- [Internal] Combinations and masks ImGuiTableFlags.SizingMask_ = bitOr(ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.SizingFixedSame, ImGuiTableFlags.SizingStretchProp, ImGuiTableFlags.SizingStretchSame) +-- Flags for ImGui.TableSetupColumn() --- @enum ImGuiTableColumnFlags ImGuiTableColumnFlags = { + -- Input configuration flags None = 0, - Disabled = bitLShift(1, 0), - DefaultHide = bitLShift(1, 1), - DefaultSort = bitLShift(1, 2), - WidthStretch = bitLShift(1, 3), - WidthFixed = bitLShift(1, 4), - NoResize = bitLShift(1, 5), - NoReorder = bitLShift(1, 6), - NoHide = bitLShift(1, 7), - NoClip = bitLShift(1, 8), - NoSort = bitLShift(1, 9), - NoSortAscending = bitLShift(1, 10), - NoSortDescending = bitLShift(1, 11), - NoHeaderLabel = bitLShift(1, 12), - NoHeaderWidth = bitLShift(1, 13), - PreferSortAscending = bitLShift(1, 14), - PreferSortDescending = bitLShift(1, 15), - IndentEnable = bitLShift(1, 16), - IndentDisable = bitLShift(1, 17), - AngledHeader = bitLShift(1, 18), + Disabled = bitLShift(1, 0), -- Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) + DefaultHide = bitLShift(1, 1), -- Default as a hidden/disabled column. + DefaultSort = bitLShift(1, 2), -- Default as a sorting column. + WidthStretch = bitLShift(1, 3), -- Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). + WidthFixed = bitLShift(1, 4), -- Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). + NoResize = bitLShift(1, 5), -- Disable manual resizing. + NoReorder = bitLShift(1, 6), -- Disable manual reordering this column, this will also prevent other columns from crossing over this column. + NoHide = bitLShift(1, 7), -- Disable ability to hide/disable this column. + NoClip = bitLShift(1, 8), -- Disable clipping for this column (all NoClip columns will render in a same draw command). + NoSort = bitLShift(1, 9), -- Disable ability to sort on this field (even if ImGuiTableFlags.Sortable is set on the table). + NoSortAscending = bitLShift(1, 10), -- Disable ability to sort in the ascending direction. + NoSortDescending = bitLShift(1, 11), -- Disable ability to sort in the descending direction. + NoHeaderLabel = bitLShift(1, 12), -- TableHeadersRow() will submit an empty label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. You may append into this cell by calling TableSetColumnIndex() right after the TableHeadersRow() call. + NoHeaderWidth = bitLShift(1, 13), -- Disable header text width contribution to automatic column width. + PreferSortAscending = bitLShift(1, 14), -- Make the initial sort direction Ascending when first sorting on this column (default). + PreferSortDescending = bitLShift(1, 15), -- Make the initial sort direction Descending when first sorting on this column. + IndentEnable = bitLShift(1, 16), -- Use current Indent value when entering cell (default for column 0). + IndentDisable = bitLShift(1, 17), -- Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. + AngledHeader = bitLShift(1, 18), -- TableHeadersRow() will submit an angled header row for this column. Note this will add an extra row. - IsEnabled = bitLShift(1, 24), - IsVisible = bitLShift(1, 25), - IsSorted = bitLShift(1, 26), - IsHovered = bitLShift(1, 27), + -- Output status flags, read-only via TableGetColumnFlags() + IsEnabled = bitLShift(1, 24), -- Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. + IsVisible = bitLShift(1, 25), -- Status: is visible == is enabled AND not clipped by scrolling. + IsSorted = bitLShift(1, 26), -- Status: is currently part of the sort specs + IsHovered = bitLShift(1, 27), -- Status: is hovered by mouse - NoDirectResize_ = bitLShift(1, 30), + NoDirectResize_ = bitLShift(1, 30), -- [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) } +-- [Internal] Combinations and masks ImGuiTableColumnFlags.WidthMask_ = bitOr(ImGuiTableColumnFlags.WidthStretch, ImGuiTableColumnFlags.WidthFixed) ImGuiTableColumnFlags.IndentMask_ = bitOr(ImGuiTableColumnFlags.IndentEnable, ImGuiTableColumnFlags.IndentDisable) ImGuiTableColumnFlags.StatusMask_ = bitOr(ImGuiTableColumnFlags.IsEnabled, ImGuiTableColumnFlags.IsVisible, ImGuiTableColumnFlags.IsSorted, ImGuiTableColumnFlags.IsHovered) +-- Flags for ImGui.TableNextRow() +-- - Headers: Identify header row (set default background color + width of its contents accounted differently for auto column width) --- @enum ImGuiTableRowFlags ImGuiTableRowFlags = { None = 0, Headers = bitLShift(1, 0) } +-- Enum for ImGui.TableSetBgColor() +-- Background colors are rendering in 3 layers: +-- - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. +-- - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. +-- - Layer 2: draw with CellBg color if set. +-- The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color. +-- When using ImGuiTableFlags.RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. +-- If you set the color of RowBg0 target, your color will override the existing RowBg0 color. +-- If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. +-- - RowBg0: Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags.RowBg is used) +-- - RowBg1: Set row background color 1 (generally used for selection marking) +-- - CellBg: Set cell background color (top-most color) --- @enum ImGuiTableBgTarget ImGuiTableBgTarget = { None = 0, RowBg0 = 1, RowBg1 = 2, CellBg = 3 } +-- A sorting direction +-- - Ascending = 0->9, A->Z etc. +-- - Descending = 9->0, Z->A etc. --- @enum ImGuiSortDirection ImGuiSortDirection = { None = 0, Ascending = 1, Descending = 2 } +-- Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() --- @class ImGuiPayload --- Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity. local IM_PAYLOAD = {} @@ -33209,6 +38110,12 @@ function ImGuiPayload_IsDataType(p, t) return p.DataFrameCount ~= -1 and p.DataT function ImGuiPayload_IsPreview(p) return p.Preview end function ImGuiPayload_IsDelivery(p) return p.Delivery end +------------------------------------------------------------------------------- +-- [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) +------------------------------------------------------------------------------- + +-- Helper: Growable text buffer for logging/accumulating text +-- (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') --- @class ImGuiTextBuffer # string builder: Buf is a list of string chunks local ImGuiTextBufferMT = {} ImGuiTextBufferMT.__index = ImGuiTextBufferMT @@ -40987,9 +45894,36 @@ ffff001300090013001d002700310033003d004a0054005e00680072007c00860090009a00a400ae end __FILES['imgui_internal.lua'] = function() ---- Dear ImGui WIP +-- dear imgui, v1.93.0 WIP -- (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. + +-- Index of this file: +-- +-- [SECTION] Context pointer +-- [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 +-- [SECTION] Inputs support +-- [SECTION] Navigation support +-- [SECTION] Viewport support +-- [SECTION] Settings support +-- [SECTION] Localization support +-- [SECTION] Metrics, Debug tools +-- [SECTION] ImGuiContext (main imgui context) +-- [SECTION] ImGuiWindowTempData, ImGuiWindow +-- [SECTION] Tab bar, Tab item support +-- [SECTION] ImGui internal API +-- [SECTION] ImFontLoader +-- [SECTION] ImFontAtlas internal API +-- +-- PORT: the order of declarations in this file does not strictly follow upstream's imgui_internal.h. + --- @meta local type = ImGui._GetTypeFunc() @@ -41023,6 +45957,9 @@ function ImGui._ByteArrayToString(buf, buf_begin, buf_end) end +-- 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, +-- Indexes have the same lifetime as the associated object. --- ImPool: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based). --- `ctor` creates a new element. Removed slots are recycled via FreeIdx (-1 = none; free slots chain through `_NextFree`). local IM_POOL = {} @@ -41060,8 +45997,13 @@ end function IM_POOL:Reserve(n) end -- NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end` +------------------------------------------------------------------------------- +-- [SECTION] Context pointer +-- See implementation of this variable in imgui.cpp for comments and details. +------------------------------------------------------------------------------- + --- @type ImGuiContext? -local GImGui +local GImGui -- Current implicit context pointer -- Sets local `GImGui` in this file(imgui_internal.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` @@ -41074,6 +46016,10 @@ local setmetatable = setmetatable local MT = ImGui.GetMetatables() +------------------------------------------------------------------------------- +-- [SECTION] Macros +------------------------------------------------------------------------------- + IM_TABSIZE = 4 FLT_MIN = 1.1754943508223e-38 @@ -41083,13 +46029,22 @@ INT_MIN = -0x7fffffff - 1 INT_MAX = 0x7fffffff UINT_MAX = 0x7fffffff * 2 + 1 -NAV_WINDOWING_HIGHLIGHT_DELAY = 0.5 -NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10 -NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY = 0.60 +NAV_WINDOWING_HIGHLIGHT_DELAY = 0.5 -- Time before the highlight and screen dimming starts fading in +NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10 -- Time to highlight an item activated by a shortcut. +NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY = 0.60 -- Time to hold activation button (e.g. FaceDown) to turn the activation into a text input. IM_PI = math.pi -ImPow = math.pow -ImLog = math.log + +------------------------------------------------------------------------------- +-- [SECTION] Generic helpers +-- Note that the ImXXX helpers functions are lower-level than ImGui functions. +-- ImGui functions or the ImGui context are never called/used from other ImXXX functions. +------------------------------------------------------------------------------- + +-- Helpers: Maths +-- - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy) +ImPow = math.pow -- DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision +ImLog = math.log -- DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision ImAbs = math.abs ImFabs = math.abs ImFmod = function(a, b) if b < 0 then b = -b end; if a < 0 then return -(-a % b) else return a % b end; end @@ -41127,6 +46082,7 @@ function ImSubClampOverflow(a, b, mn, mx) return a - b end +-- - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double --- @overload fun(lhs: number, rhs: number): number --- @overload fun(lhs: ImVec2, rhs: ImVec2): ImVec2 @native @@ -41143,6 +46099,7 @@ function ImMax(lhs, rhs) return ImVec2(mathMax(lhs.x, rhs.x), mathMax(lhs.y, rhs.y)) end +-- Helpers: Sorting --- @param base table --- @param count int --- @param cmp_func fun(lhs, rhs): bool @@ -41180,6 +46137,7 @@ end ImTrunc64 = _Trunc +-- Consider using the bit-hack version (search for "0x1p120f"). --- @param f float function ImCeilFast(f) local i @@ -41192,10 +46150,11 @@ function IM_ROUNDUP_TO_EVEN(n) return (ImCeil((n) / 2) * 2) end function ImRsqrt(x) return (1 / ImSqrt(x)) end function IM_TRUNC(VAL) return math.floor(VAL) end -- Positive values only! -function IM_ROUND(VAL) return math.floor(VAL + 0.5) end +function IM_ROUND(VAL) return math.floor(VAL + 0.5) end -- Positive values only! -function ImFloor(f) if f >= 0 or math.floor(f) == f then return math.floor(f) else return math.floor(f) - 1 end end +function ImFloor(f) if f >= 0 or math.floor(f) == f then return math.floor(f) else return math.floor(f) - 1 end end -- Decent replacement for floorf() +-- Helpers: Bit manipulation --- @param v int function ImIsPowerOfTwo(v) return (v ~= 0) and (bitAnd(v, (v - 1)) == 0) @@ -41315,8 +46274,8 @@ end function ImSaturate(f) return ((f < 0.0 and 0.0) or (f > 1.0 and 1.0) or f) end -IM_F32_TO_INT8_UNBOUND = function(val) return math.floor(val * 255.0 + (val >= 0 and 0.5 or -0.5)) end -IM_F32_TO_INT8_SAT = function(val) return math.floor(ImSaturate(val) * 255.0 + 0.5) end +IM_F32_TO_INT8_UNBOUND = function(val) return math.floor(val * 255.0 + (val >= 0 and 0.5 or -0.5)) end -- Unsaturated, for display purpose +IM_F32_TO_INT8_SAT = function(val) return math.floor(ImSaturate(val) * 255.0 + 0.5) end -- Saturated, always output 0..255 --- @param s ImString --- @param i int @@ -41329,6 +46288,7 @@ function ImStrByte(s, i) end end +-- Stacked color modifier, backup of modified data so we can restore it --- @class ImGuiColorMod --- @field Col ImGuiCol --- @field BackupValue ImVec4 @@ -41423,20 +46383,27 @@ IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE = 128.0 IMGUI_WINDOW_HARD_MIN_SIZE = 4.0 -IM_DRAWLIST_ARCFAST_TABLE_SIZE = 48 -IM_DRAWLIST_ARCFAST_SAMPLE_MAX = IM_DRAWLIST_ARCFAST_TABLE_SIZE +-- ImDrawList: Lookup tables +IM_DRAWLIST_ARCFAST_TABLE_SIZE = 48 -- Number of samples in adaptive arc drawing lookup table. +IM_DRAWLIST_ARCFAST_SAMPLE_MAX = IM_DRAWLIST_ARCFAST_TABLE_SIZE -- Sample index _PathArcToFastEx() for 360 angle. +-- Macros used by Recoverable Error handling +-- - Only dispatch error if _EXPR: evaluate as assert (similar to an assert macro). +-- - The message will always be a string literal, in order to increase likelihood of being display by an assert handler. +-- - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling. +-- - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling. -- Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert. -function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end +function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end -- Recoverable User Error function IM_ASSERT_USER_ERROR_RET(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end +-- Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam. local function DebugLogIf(flag, fmt, ...) local g = GImGui if g and bitAnd(g.DebugLogFlags, flag) ~= 0 then ImGui.DebugLog(fmt, ...) end end function IMGUI_DEBUG_LOG_ACTIVEID(...) DebugLogIf(ImGuiDebugLogFlags.EventActiveId, ...) end function IMGUI_DEBUG_LOG_POPUP(...) DebugLogIf(ImGuiDebugLogFlags.EventPopup, ...) end -function IMGUI_DEBUG_LOG_FONT(...) DebugLogIf(ImGuiDebugLogFlags.EventFont, ...) end +function IMGUI_DEBUG_LOG_FONT(...) DebugLogIf(ImGuiDebugLogFlags.EventFont, ...) end -- Called from ImFontAtlas function which may operate without a context. function IMGUI_DEBUG_LOG_VIEWPORT(...) DebugLogIf(ImGuiDebugLogFlags.EventViewport, ...) end function IMGUI_DEBUG_LOG_FOCUS(...) DebugLogIf(ImGuiDebugLogFlags.EventFocus, ...) end function IMGUI_DEBUG_LOG_NAV(...) DebugLogIf(ImGuiDebugLogFlags.EventNav, ...) end @@ -41451,9 +46418,17 @@ function IMGUI_DEBUG_LOG_ERROR(...) DebugLogIf(ImGuiDebugLogFlags.EventError, .. --- @alias ImGuiSelectionUserData any ImGuiSelectionUserData_Invalid = -1 -ImGuiKeyOwner_Any = 0 -ImGuiKeyOwner_NoOwner = 4294967295 +-- Input function taking an 'ImGuiID owner_id' argument defaults to (ImGuiKeyOwner_Any == 0) aka don't test ownership, which matches legacy behavior. +ImGuiKeyOwner_Any = 0 -- Accept key that have an owner, UNLESS a call to SetKeyOwner() explicitly used ImGuiInputFlags.LockThisFrame or ImGuiInputFlags.LockUntilRelease. +ImGuiKeyOwner_NoOwner = 4294967295 -- Require key to have no owner. +------------------------------------------------------------------------------- +-- [SECTION] ImGui internal API +-- No guarantee of forward compatibility here! +------------------------------------------------------------------------------- + +-- Inputs +-- FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. --- @param button ImGuiMouseButton --- @return ImGuiKey function ImGui.MouseButtonToKey(button) IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT) return ImGuiKey.MouseLeft + button end @@ -41509,6 +46484,17 @@ function ImGui.ConvertSingleModFlagToKey(key) return key end +-- [EXPERIMENTAL] Low-Level: Key/Input Ownership +-- - The idea is that instead of "eating" a given input, we can link to an owner id. +-- - Ownership is most often claimed as a result of reacting to a press/down event (but occasionally may be claimed ahead). +-- - Input queries can then read input by specifying ImGuiKeyOwner_Any (== 0), ImGuiKeyOwner_NoOwner (== -1) or a custom ID. +-- - Legacy input queries (without specifying an owner or _Any or _None) are equivalent to using ImGuiKeyOwner_Any (== 0). +-- - Input ownership is automatically released on the frame after a key is released. Therefore: +-- - for ownership registration happening as a result of a down/press event, the SetKeyOwner() call may be done once (common case). +-- - for ownership registration happening ahead of a down/press event, the SetKeyOwner() call needs to be made every frame (happens if e.g. claiming ownership on hover). +-- - SetItemKeyOwner() is a shortcut for common simple case. A custom widget will probably want to call SetKeyOwner() multiple times directly based on its interaction state. +-- - This is marked experimental because not all widgets are fully honoring the Set/Test idioms. We will need to move forward step by step. +-- Please open a GitHub Issue to submit your usage scenario or if there's a use case you need solved. --- @param ctx ImGuiContext --- @param key ImGuiKey function ImGui.GetKeyOwnerData(ctx, key) @@ -41517,6 +46503,8 @@ function ImGui.GetKeyOwnerData(ctx, key) return ctx.KeysOwnerData[key - ImGuiKey.NamedKey_BEGIN] end +-- This extends ImGuiKeyData but only for named keys (legacy keys don't support the new features) +-- Stored in main context (1 per named key). In the future it might be merged into ImGuiKeyData. --- @class ImGuiKeyOwnerData --- @return ImGuiKeyOwnerData @@ -41525,8 +46513,8 @@ function ImGuiKeyOwnerData() return { OwnerCurr = ImGuiKeyOwner_NoOwner, OwnerNext = ImGuiKeyOwner_NoOwner, - LockThisFrame = false, - LockUntilRelease = false + LockThisFrame = false, -- Reading this key requires explicit owner id (until end of frame). Set by ImGuiInputFlags.LockThisFrame. + LockUntilRelease = false -- Reading this key requires explicit owner id (until key is released). Set by ImGuiInputFlags.LockUntilRelease. When this is true LockThisFrame is always true as well. } end @@ -41569,22 +46557,22 @@ function ImCharIsBlankW(c) return c == 32 or c == 9 or c == 0x3000 end ImGuiNavMoveFlags = { None = 0, - LoopX = bitLShift(1, 0), + LoopX = bitLShift(1, 0), -- On failed request, restart from opposite side LoopY = bitLShift(1, 1), - WrapX = bitLShift(1, 2), - WrapY = bitLShift(1, 3), - AllowCurrentNavId = bitLShift(1, 4), - AlsoScoreVisibleSet = bitLShift(1, 5), - ScrollToEdgeY = bitLShift(1, 6), + WrapX = bitLShift(1, 2), -- On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left) + WrapY = bitLShift(1, 3), -- This is not super useful but provided for completeness + AllowCurrentNavId = bitLShift(1, 4), -- Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place) + AlsoScoreVisibleSet = bitLShift(1, 5), -- Store alternate result in NavMoveResultLocalVisible that only comprise elements that are already fully visible (used by PageUp/PageDown) + ScrollToEdgeY = bitLShift(1, 6), -- Force scrolling to min/max (used by Home/End) -- FIXME-NAV: Aim to remove or reword as ImGuiScrollFlags Forwarded = bitLShift(1, 7), - DebugNoResult = bitLShift(1, 8), - FocusApi = bitLShift(1, 9), - IsTabbing = bitLShift(1, 10), - IsPageMove = bitLShift(1, 11), - Activate = bitLShift(1, 12), - NoSelect = bitLShift(1, 13), - NoSetNavCursorVisible = bitLShift(1, 14), - NoClearActiveId = bitLShift(1, 15), + DebugNoResult = bitLShift(1, 8), -- Dummy scoring for debug purpose, don't apply result + FocusApi = bitLShift(1, 9), -- Requests from focus API can land/focus/activate items even if they are marked with _NoTabStop (see NavProcessItemForTabbingRequest() for details) + IsTabbing = bitLShift(1, 10), -- == Focus + Activate if item is Inputable + DontChangeNavHighlight + IsPageMove = bitLShift(1, 11), -- Identify a PageDown/PageUp request. + Activate = bitLShift(1, 12), -- Activate/select target item. + NoSelect = bitLShift(1, 13), -- Don't trigger selection by not setting g.NavJustMovedTo + NoSetNavCursorVisible = bitLShift(1, 14), -- Do not alter the nav cursor visible state + NoClearActiveId = bitLShift(1, 15), -- (Experimental) Do not clear active id when applying move result } ImGuiNavMoveFlags.WrapMask_ = bitOr(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.LoopY, ImGuiNavMoveFlags.WrapX, ImGuiNavMoveFlags.WrapY) @@ -41592,40 +46580,54 @@ ImGuiNavMoveFlags.WrapMask_ = bitOr(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.L --- @enum ImGuiNavLayer ImGuiNavLayer = { - Main = 0, - Menu = 1, + Main = 0, -- Main scrolling layer + Menu = 1, -- Menu layer (access with Alt) COUNT = 2 } -ImGuiItemFlags.ReadOnly = bitLShift(1, 11) +------------------------------------------------------------------------------- +-- [SECTION] Widgets support: flags, enums, data structures +------------------------------------------------------------------------------- + +-- Extend ImGuiItemFlags +-- - input: PushItemFlag() manipulates g.CurrentItemFlags, g.NextItemData.ItemFlags, ItemAdd() calls may add extra flags too. +-- - output: stored in g.LastItemData.ItemFlags + +-- Controlled by user +ImGuiItemFlags.ReadOnly = bitLShift(1, 11) -- false -- [ALPHA] Allow hovering interactions but underlying value is not changed. ImGuiItemFlags.MixedValue = bitLShift(1, 12) -ImGuiItemFlags.NoWindowHoverableCheck = bitLShift(1, 13) -ImGuiItemFlags.AllowOverlap = bitLShift(1, 14) -ImGuiItemFlags.NoNavDisableMouseHover = bitLShift(1, 15) -ImGuiItemFlags.NoMarkEdited = bitLShift(1, 16) -ImGuiItemFlags.NoFocus = bitLShift(1, 17) +ImGuiItemFlags.NoWindowHoverableCheck = bitLShift(1, 13) -- false -- Disable hoverable check in ItemHoverable() +ImGuiItemFlags.AllowOverlap = bitLShift(1, 14) -- false -- Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. +ImGuiItemFlags.NoNavDisableMouseHover = bitLShift(1, 15) -- false -- Nav keyboard/gamepad mode doesn't disable hover highlight (behave as if NavHighlightItemUnderNav==false). +ImGuiItemFlags.NoMarkEdited = bitLShift(1, 16) -- false -- Skip calling MarkItemEdited() +ImGuiItemFlags.NoFocus = bitLShift(1, 17) -- false -- [EXPERIMENTAL: Not very well specced] Clicking doesn't take focus. Automatically sets ImGuiButtonFlags.NoFocus + ImGuiButtonFlags.NoNavFocus in ButtonBehavior(). -ImGuiItemFlags.Inputable = bitLShift(1, 20) -ImGuiItemFlags.HasSelectionUserData = bitLShift(1, 21) -ImGuiItemFlags.IsMultiSelect = bitLShift(1, 22) +-- Controlled by widget code +ImGuiItemFlags.Inputable = bitLShift(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. +ImGuiItemFlags.HasSelectionUserData = bitLShift(1, 21) -- false -- Set by SetNextItemSelectionUserData() +ImGuiItemFlags.IsMultiSelect = bitLShift(1, 22) -- false -- Set by SetNextItemSelectionUserData() -ImGuiItemFlags.Default_ = bitOr(ImGuiItemFlags.AutoClosePopups, ImGuiItemFlags.LiveEditOnInputText) +ImGuiItemFlags.Default_ = bitOr(ImGuiItemFlags.AutoClosePopups, ImGuiItemFlags.LiveEditOnInputText) -- Please don't change, use PushItemFlag() instead. +-- Helpers: High-level text functions (DO NOT USE!!! THIS IS A MINIMAL SUBSET OF LARGER UPCOMING CHANGES) --- @enum ImDrawTextFlags ImDrawTextFlags = { None = 0, - CpuFineClip = bitLShift(1, 0), + CpuFineClip = bitLShift(1, 0), -- Must be == 1/true for legacy with 'bool cpu_fine_clip' arg to RenderText() WrapKeepBlanks = bitLShift(1, 1), StopOnNewLine = bitLShift(1, 2) } +-- Flags for FocusWindow(). This is not called ImGuiFocusFlags to avoid confusion with public-facing ImGuiFocusedFlags. +-- FIXME: Once we finishing replacing more uses of GetTopMostPopupModal()+IsWindowWithinBeginStackOf() +-- and FindBlockingModal() with this, we may want to change the flag to be opt-out instead of opt-in. --- @enum ImGuiFocusRequestFlags ImGuiFocusRequestFlags = { None = 0, - RestoreFocusedChild = bitLShift(1, 0), - UnlessBelowModal = bitLShift(1, 1) + RestoreFocusedChild = bitLShift(1, 0), -- Find last focused child (if any) and focus it instead. + UnlessBelowModal = bitLShift(1, 1) -- Do not set focus if the window is below a modal. } --- @enum ImGuiTextFlags @@ -41635,6 +46637,7 @@ ImGuiTextFlags = NoWidthForLargeClippedText = bitLShift(1, 0) } +-- Character classification for word-wrapping logic --- @enum ImWcharClass ImWcharClass = { @@ -41643,6 +46646,8 @@ ImWcharClass = Other = 2 } +-- Helper: ImVec1 (1D vector) +-- (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) --- @class ImVec1 --- @field x number local IM_VEC1 = {} @@ -41658,11 +46663,13 @@ function ImVec1_Copy(dest, src) dest.x = src.x end +-- Helper: ImRect (2D axis aligned bounding-box) +-- NB: we can't rely on ImVec2 math operators being available here! --- @class ImRect --- @field [1] ImVec2 --- @field [2] ImVec2 ---- @field Min ImVec2 ---- @field Max ImVec2 +--- @field Min ImVec2 # Upper-left +--- @field Max ImVec2 # Lower-right local IM_RECT = {} setmetatable(IM_RECT, { __index = function(_, k) if k ~= "Min" and k ~= "Max" then error("ImRect: unknown key " .. tostring(k), 2) end end }) @@ -41714,20 +46721,22 @@ function IM_RECT:GetHeight() return self.Max.y - self.Min.y end function IM_RECT:GetSize() return ImVec2(self.Max.x - self.Min.x, self.Max.y - self.Min.y) end --- @nodiscard -function IM_RECT:GetTL() return ImVec2(self.Min.x, self.Min.y) end +function IM_RECT:GetTL() return ImVec2(self.Min.x, self.Min.y) end -- Top-left --- @nodiscard -function IM_RECT:GetTR() return ImVec2(self.Max.x, self.Min.y) end +function IM_RECT:GetTR() return ImVec2(self.Max.x, self.Min.y) end -- Top-right --- @nodiscard -function IM_RECT:GetBL() return ImVec2(self.Min.x, self.Max.y) end +function IM_RECT:GetBL() return ImVec2(self.Min.x, self.Max.y) end -- Bottom-left --- @nodiscard -function IM_RECT:GetBR() return ImVec2(self.Max.x, self.Max.y) end +function IM_RECT:GetBR() return ImVec2(self.Max.x, self.Max.y) end -- Bottom-right +-- Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. --- @param r ImRect @native function IM_RECT:ClipWith(r) ImVec2_Copy(self.Min, ImMax(self.Min, r.Min)); ImVec2_Copy(self.Max, ImMin(self.Max, r.Max)) end +-- Full version, ensure both points are fully clipped. --- @param r ImRect @native function IM_RECT:ClipWithFull(r) @@ -41808,12 +46817,15 @@ function ImRect_CopyFromV4(dest, src) dest.Max.x = src.z; dest.Max.y = src.w end +-- Helper: ImBitArray +-- Macro version of ImBitArrayTestBit(): ensure args have side-effect or are costly! --- @param _ARRAY ImU32[] --- @param _N int function IM_BITARRAY_TESTBIT(_ARRAY, _N) return bitAnd(_ARRAY[bitRShift(_N - 1, 5) + 1], bitLShift(1, bitAnd(_N - 1, 31))) ~= 0 end +-- Macro version of ImBitArrayClearBit(): ensure args have side-effect or are costly! --- @param _ARRAY ImU32[] --- @param _N int function IM_BITARRAY_CLEARBIT(_ARRAY, _N) @@ -41829,8 +46841,11 @@ function ImBitArraySetBit(arr, n) arr[idx] = bitOr(arr[idx], mask) end +-- Bit array for named keys --- @alias ImBitArrayForNamedKeys ImBitArray +-- Helper: ImBitArray class (wrapper over ImBitArray functions) +-- Store 1-bit per value. --- NOTE: This struct is expensive to create --- @class ImBitArray --- @field Data ImU32[] @@ -41857,6 +46872,9 @@ function ImBitArray(BITCOUNT, OFFSET) return this end +-- 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. +-- so e.g. 'PathArcTo(center, radius, PI * -0.5, PI)' is ok, whereas 'PathArcTo(center, radius, PI, PI * -0.5)' won't have correct anti-aliasing when followed by PathFillConvex(). function MT.ImDrawList:PathClear() self._Path:clear() end --- @param pos ImVec2 @@ -41894,24 +46912,32 @@ function ImGui.SetNextItemColorMarker(col) g.NextItemData.ColorMarker = col end +------------------------------------------------------------------------------- +-- [SECTION] ImDrawList support +------------------------------------------------------------------------------- + +-- Data shared between all ImDrawList instances +-- 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. --- @class ImDrawListSharedData ---- @field TexUvWhitePixel ImVec2 ---- @field TexUvLines ImVec4[] ---- @field FontAtlas ImFontAtlas ---- @field Font ImFont ---- @field FontSize float ---- @field FontScale float +--- @field TexUvWhitePixel ImVec2 # UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) +--- @field TexUvLines ImVec4[] # UV of anti-aliased lines in the atlas (== FontAtlas->Builder->TexUvLines) +--- @field FontAtlas ImFontAtlas # Current font atlas +--- @field Font ImFont # Current font (used for simplified AddText overload) +--- @field FontSize float # Current font size (used for simplified AddText overload) +--- @field FontScale float # Current font scale (== FontSize / Font->FontSize) --- @field CurveTessellationTol float ---- @field CircleTessellationMaxError float +--- @field CircleTessellationMaxError float # Number of circle segments to use per pixel of radius for AddCircle() etc --- @field InitialFringeScale float --- @field InitialFlags ImDrawListFlags ---- @field ClipRectFullscreen? ImVec4 ---- @field TempBuffer ImVector ---- @field DrawLists ImVector ---- @field Context? ImGuiContext ---- @field ArcFastVtx table # 1-based table ---- @field ArcFastRadiusCutoff float ---- @field CircleSegmentCounts table # 1-based table +--- @field ClipRectFullscreen? ImVec4 # Value for PushClipRectFullscreen() +--- @field TempBuffer ImVector # Temporary write buffer +--- @field DrawLists ImVector # All draw lists associated to this ImDrawListSharedData +--- @field Context? ImGuiContext # [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case. +--- @field ArcFastVtx table # 1-based table. Sample points on the quarter of the circle. +--- @field ArcFastRadiusCutoff float # Cutoff radius after which arc drawing will fallback to slower PathArcTo() +--- @field CircleSegmentCounts table # 1-based table. Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) MT.ImDrawListSharedData = {} MT.ImDrawListSharedData.__index = MT.ImDrawListSharedData @@ -41919,28 +46945,29 @@ MT.ImDrawListSharedData.__index = MT.ImDrawListSharedData --- @nodiscard function ImDrawListSharedData() local this = setmetatable({ - TexUvWhitePixel = nil, - TexUvLines = nil, - FontAtlas = nil, + TexUvWhitePixel = nil, -- UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) + TexUvLines = nil, -- UV of anti-aliased lines in the atlas (== FontAtlas->Builder->TexUvLines) + FontAtlas = nil, -- Current font atlas - Font = nil, - FontSize = 0, - FontScale = 0, + Font = nil, -- Current font (used for simplified AddText overload) + FontSize = 0, -- Current font size (used for simplified AddText overload) + FontScale = 0, -- Current font scale (== FontSize / Font->FontSize) CurveTessellationTol = 0, - CircleTessellationMaxError = 0, + CircleTessellationMaxError = 0, -- Number of circle segments to use per pixel of radius for AddCircle() etc InitialFringeScale = 1, InitialFlags = 0, - ClipRectFullscreen = nil, - TempBuffer = ImVector(ImVec2), - DrawLists = ImVector(), + ClipRectFullscreen = nil, -- Value for PushClipRectFullscreen() + TempBuffer = ImVector(ImVec2), -- Temporary write buffer + DrawLists = ImVector(), -- All draw lists associated to this ImDrawListSharedData - ArcFastVtx = {}, - ArcFastRadiusCutoff = nil, - CircleSegmentCounts = {}, + -- Lookup tables + ArcFastVtx = {}, -- Sample points on the quarter of the circle. + ArcFastRadiusCutoff = nil, -- Cutoff radius after which arc drawing will fallback to slower PathArcTo() + CircleSegmentCounts = {}, -- Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) - Context = nil + Context = nil -- [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case. }, MT.ImDrawListSharedData) for i = 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE do @@ -41951,6 +46978,7 @@ function ImDrawListSharedData() return this end +-- Internal storage for incrementally packing and building a ImFontAtlas --- @class ImFontAtlasBuilder --- @field PackContext stbrp_context --- @field PackNodes ImVector @@ -41980,27 +47008,29 @@ function ImFontAtlasBuilder() --- @type ImFontAtlasBuilder local this = setmetatable({}, MT.ImFontAtlasBuilder) - this.PackContext = nil -- struct stbrp_context_opaque { char data[80]; }; + this.PackContext = nil -- struct stbrp_context_opaque { char data[80]; }; -- Actually 'stbrp_context' but we don't want to define this in the header file. this.PackNodes = ImVector() this.Rects = ImVector() - this.RectsIndex = ImVector() - this.TempBuffer = ImVector() - this.RectsIndexFreeListStart = -1 - this.RectsPackedCount = 0 - this.RectsPackedSurface = 0 + this.RectsIndex = ImVector() -- ImFontAtlasRectId -> index into Rects[] + this.TempBuffer = ImVector() -- Misc scratch buffer + this.RectsIndexFreeListStart = -1 -- First unused entry + this.RectsPackedCount = 0 -- Number of packed rectangles. + this.RectsPackedSurface = 0 -- Number of packed pixels. Used when compacting to heuristically find the ideal texture size. this.RectsDiscardedCount = 0 this.RectsDiscardedSurface = 0 - this.FrameCount = -1 - this.MaxRectSize = ImVec2() - this.MaxRectBounds = ImVec2() - this.LockDisableResize = false - this.PreloadedAllGlyphsRanges = false + this.FrameCount = -1 -- Current frame count + this.MaxRectSize = ImVec2() -- Largest rectangle to pack (de-facto used as a "minimum texture size") + this.MaxRectBounds = ImVec2() -- Bottom-right most used pixels + this.LockDisableResize = false -- Disable resizing texture + this.PreloadedAllGlyphsRanges = false -- Set when missing ImGuiBackendFlags.RendererHasTextures features forces atlas to preload everything. + -- Cache of all ImFontBaked this.BakedPool = ImVector() -- ImStableVector - this.BakedMap = {} + this.BakedMap = {} -- BakedId --> ImFontBaked this.BakedDiscardedCount = 0 - this.PackIdMouseCursors = -1 + -- Custom rectangle identifiers + this.PackIdMouseCursors = -1 -- White pixel + mouse cursors. Also happen to be fallback in case of packing failure. this.PackIdLinesTexData = -1 return this @@ -42008,8 +47038,8 @@ end --- @class ImFontStackData --- @field Font ImFont ---- @field FontSizeBeforeScaling float ---- @field FontSizeAfterScaling float +--- @field FontSizeBeforeScaling float # ~~ style.FontSizeBase +--- @field FontSizeAfterScaling float # ~~ g.FontSize --- @return ImFontStackData --- @param font ImFont @@ -42019,14 +47049,18 @@ end function ImFontStackData(font, font_size_before_scaling, font_size_after_scaling) return { Font = font, - FontSizeBeforeScaling = font_size_before_scaling, - FontSizeAfterScaling = font_size_after_scaling + FontSizeBeforeScaling = font_size_before_scaling, -- ~~ style.FontSizeBase + FontSizeAfterScaling = font_size_after_scaling -- ~~ g.FontSize } end +------------------------------------------------------------------------------- +-- [SECTION] Style support +------------------------------------------------------------------------------- + --- `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers! --- @class ImGuiStyleVarInfo ---- @field Count ImU32 +--- @field Count ImU32 # 1+ --- @field DataType ImGuiDataType --- @field Key string # key in parent structure. Note that the cpp Dear ImGui uses `ImU32 Offset`! @@ -42039,6 +47073,7 @@ function ImGuiStyleVarInfo(count, data_type, key) return { Count = count, DataType = data_type, Key = key } end +-- Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. --- @class ImGuiStyleMod --- @field VarIdx ImGuiStyleVar --- @field BackupVal table @@ -42058,36 +47093,42 @@ function ImGuiStyleMod(idx, v) return this end ---- Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo() +------------------------------------------------------------------------------- +-- [SECTION] Data types support +------------------------------------------------------------------------------- + +-- Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). --- @class ImGuiDataTypeInfo --- @field Size size_t # Size in bytes --- @field Name string # Short descriptive name for the type, for debugging --- @field PrintFmt string # Default printf format for the type --- @field ScanFmt string # Default scanf format for the type +-- Status storage for the last submitted item --- @class ImGuiLastItemData --- @field ID ImGuiID ---- @field ItemFlags ImGuiItemFlags ---- @field StatusFlags ImGuiItemStatusFlags ---- @field Rect ImRect ---- @field NavRect ImRect ---- @field DisplayRect ImRect ---- @field ClipRect ImRect ---- @field Shortcut ImGuiKeyChord +--- @field ItemFlags ImGuiItemFlags # See ImGuiItemFlags (called 'InFlags' before v1.91.4). +--- @field StatusFlags ImGuiItemStatusFlags # See ImGuiItemStatusFlags +--- @field Rect ImRect # Full rectangle +--- @field NavRect ImRect # Navigation scoring rectangle (not displayed) +--- @field DisplayRect ImRect # Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasDisplayRect) is set. +--- @field ClipRect ImRect # Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasClipRect) is set.. +--- @field Shortcut ImGuiKeyChord # Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasShortcut) is set.. --- @return ImGuiLastItemData --- @nodiscard function ImGuiLastItemData() return { ID = 0, - ItemFlags = 0, - StatusFlags = 0, - Rect = ImRect(), - NavRect = ImRect(), + ItemFlags = 0, -- See ImGuiItemFlags (called 'InFlags' before v1.91.4). + StatusFlags = 0, -- See ImGuiItemStatusFlags + Rect = ImRect(), -- Full rectangle + NavRect = ImRect(), -- Navigation scoring rectangle (not displayed) - DisplayRect = ImRect(), - ClipRect = ImRect(), - Shortcut = 0 + -- Rarely used fields are not explicitly cleared, only valid when the corresponding ImGuiItemStatusFlags are set. + DisplayRect = ImRect(), -- Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasDisplayRect) is set. + ClipRect = ImRect(), -- Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasClipRect) is set.. + Shortcut = 0 -- Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasShortcut) is set.. } end @@ -42104,6 +47145,10 @@ function ImGuiLastItemData_Copy(dest, src) dest.Shortcut = src.Shortcut end +-- Store data emitted by TreeNode() for usage by TreePop() +-- - 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. --- @class ImGuiTreeNodeStackData --- @field ID ImGuiID --- @field TreeFlags ImGuiTreeNodeFlags @@ -42119,14 +47164,15 @@ local function ImGuiTreeNodeStackData() return { ID = nil, TreeFlags = nil, - ItemFlags = nil, - NavRect = ImRect(), + ItemFlags = nil, -- Used for nav landing + NavRect = ImRect(), -- Used for nav landing DrawLinesX1 = nil, DrawLinesToNodesY2 = nil, DrawLinesTableColumn = nil } end +-- Storage for SetNextItem** functions --- @class ImGuiNextItemData --- @field HasFlags ImGuiNextItemDataFlags --- @field ItemFlagsSet ImGuiItemFlags @@ -42143,6 +47189,7 @@ end local IMGUI_NEXT_ITEM_DATA = {} IMGUI_NEXT_ITEM_DATA.__index = IMGUI_NEXT_ITEM_DATA +-- Also cleared manually by ItemAdd()! function IMGUI_NEXT_ITEM_DATA:ClearFlags() self.HasFlags = ImGuiNextItemDataFlags.None self.ItemFlagsSet = ImGuiItemFlags.None @@ -42152,22 +47199,24 @@ end --- @nodiscard function ImGuiNextItemData() return setmetatable({ - HasFlags = 0, - ItemFlagsSet = 0, + HasFlags = 0, -- Called HasFlags instead of Flags to avoid mistaking this + ItemFlagsSet = 0, -- Currently only tested/used for ImGuiItemFlags.AllowOverlap and ImGuiItemFlags.HasSelectionUserData. - FocusScopeId = 0, - SelectionUserData = -1, - Width = 0.0, - Shortcut = 0, - ShortcutFlags = 0, - OpenVal = false, - OpenCond = 0, - RefVal = 0, - StorageId = 0, - ColorMarker = 0 + -- Members below are NOT cleared by ItemAdd() meaning they are still valid during e.g. NavProcessItem(). Always rely on HasFlags. + FocusScopeId = 0, -- Set by SetNextItemSelectionUserData() + SelectionUserData = -1, -- Set by SetNextItemSelectionUserData() (note that nil/0 is a valid value, we use -1 == ImGuiSelectionUserData_Invalid to mark invalid values) + Width = 0.0, -- Set by SetNextItemWidth() + Shortcut = 0, -- Set by SetNextItemShortcut() + ShortcutFlags = 0, -- Set by SetNextItemShortcut() + OpenVal = false, -- Set by SetNextItemOpen() + OpenCond = 0, -- Set by SetNextItemOpen() + RefVal = 0, -- Not exposed yet, for ImGuiInputTextFlags.ParseEmptyAsRefVal + StorageId = 0, -- Set by SetNextItemStorageID() + ColorMarker = 0 -- Set by SetNextItemColorMarker(). Not exposed yet, supported by DragScalar,SliderScalar and for ImGuiSliderFlags.ColorMarkers. }, IMGUI_NEXT_ITEM_DATA) end +-- Storage for SetNexWindow** functions --- @class ImGuiNextWindowData --- @field HasFlags ImGuiNextWindowDataFlags --- @field PosCond ImGuiCond @@ -42200,6 +47249,7 @@ function ImGuiNextWindowData() return setmetatable({ HasFlags = 0, + -- Members below are NOT cleared. Always rely on HasFlags. PosCond = 0, SizeCond = 0, CollapsedCond = 0, @@ -42210,9 +47260,9 @@ function ImGuiNextWindowData() ScrollVal = ImVec2(), WindowFlags = nil, ChildFlags = nil, - WindowFlagsSet = 0, + WindowFlagsSet = 0, -- Flags to set. Use SetNextWindowFlags()! WindowFlagsClear = 0, - ChildFlagsSet = 0, + ChildFlagsSet = 0, -- Flags to set. Use SetNextWindowChildFlags(). ChildFlagsClear = 0, ViewportId = 0, DockId = 0, @@ -42223,8 +47273,8 @@ function ImGuiNextWindowData() SizeConstraintRect = nil, SizeCallback = nil, SizeCallbackUserData = nil, - BgAlphaVal = nil, - MenuBarOffsetMinVal = ImVec2(), + BgAlphaVal = nil, -- Override background alpha + MenuBarOffsetMinVal = ImVec2(), -- (Always on) This is not exposed publicly, so we don't clear it and it doesn't have a corresponding flag (could we? for consistency?) RefreshFlagsVal = nil, CacheKeySet = false, -- [Port] SetNextWindowCached() CacheKeyVal = nil @@ -42234,7 +47284,7 @@ end --- @enum ImGuiWindowBgClickFlags ImGuiWindowBgClickFlags = { None = 0, - Move = bitLShift(1, 0), + Move = bitLShift(1, 0), -- Click on bg/void + drag to move window. Cleared by default when using io.ConfigWindowsMoveFromTitleBarOnly. } --- @enum ImGuiNextWindowDataFlags @@ -42256,6 +47306,8 @@ ImGuiNextWindowDataFlags = { HasWindowClass = bitLShift(1, 13) } +-- FIXME: this is in development, not exposed/functional as a generic feature yet. +-- Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2 --- @enum ImGuiLayoutType ImGuiLayoutType = { @@ -42269,7 +47321,7 @@ ImGuiSeparatorFlags = None = 0, Horizontal = bitLShift(1, 0), -- Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar Vertical = bitLShift(1, 1), - SpanAllColumns = bitLShift(1, 2) -- Make separator cover all columns of a legacy Columns() set + SpanAllColumns = bitLShift(1, 2) -- Make separator cover all columns of a legacy Columns() set. } --- @class ImGuiStyle @@ -42281,111 +47333,114 @@ MT.ImGuiStyle.__index = MT.ImGuiStyle function ImGuiStyle() --- @type ImGuiStyle local this = { - FontSizeBase = 0.0, - FontScaleMain = 1.0, - FontScaleDpi = 1.0, + FontSizeBase = 0.0, -- Will default to io.Fonts.Fonts[0] on first frame. + FontScaleMain = 1.0, -- Main scale factor. May be set by application once, or exposed to end-user. + FontScaleDpi = 1.0, -- Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. - Alpha = 1.0, - DisabledAlpha = 0.60, + Alpha = 1.0, -- Global alpha applies to everything in Dear ImGui. + DisabledAlpha = 0.60, -- Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. - FramePadding = ImVec2(4, 3), - FrameRounding = 0.0, - FrameBorderSize = 0.0, - WindowPadding = ImVec2(8, 8), + FramePadding = ImVec2(4, 3), -- Padding within a framed rectangle (used by most widgets) + FrameRounding = 0.0, -- Radius of frame corners rounding. Set to 0.0 to have rectangular frames (used by most widgets). + FrameBorderSize = 0.0, -- Thickness of border around frames. Generally set to 0.0 or 1.0. Other values not well tested. + WindowPadding = ImVec2(8, 8), -- Padding within a window - TouchExtraPadding = ImVec2(0, 0), - IndentSpacing = 21.0, + TouchExtraPadding = ImVec2(0, 0), -- Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + IndentSpacing = 21.0, -- Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). - WindowRounding = 0, - WindowBorderSize = 1, + WindowRounding = 0, -- Radius of window corners rounding. Set to 0.0 to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. + WindowBorderSize = 1, -- Thickness of border around windows. Generally set to 0.0 or 1.0. Other values not well tested. - ScrollbarSize = 14.0, - ScrollbarRounding = 9.0, - ScrollbarPadding = 2.0, - GrabMinSize = 12.0, - GrabRounding = 0.0, - ImageRounding = 0.0, - ImageBorderSize = 0.0, + ScrollbarSize = 14.0, -- Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarRounding = 9.0, -- Radius of grab corners rounding for scrollbar + ScrollbarPadding = 2.0, -- Padding of scrollbar grab within its frame (same for both axes) + GrabMinSize = 12.0, -- Minimum width/height of a grab box for slider/scrollbar + GrabRounding = 0.0, -- Radius of grabs corners rounding. Set to 0.0 to have rectangular slider grabs. + ImageRounding = 0.0, -- Rounding of Image() calls. + ImageBorderSize = 0.0, -- Thickness of border around Image() calls. - WindowBorderHoverPadding = 4.0, + WindowBorderHoverPadding = 4.0, -- 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. TreeLinesFlags = ImGuiTreeNodeFlags.DrawLinesNone, - TreeLinesSize = 1.0, - TreeLinesRounding = 0.0, - MenuItemRounding = 0.0, - SelectableRounding = 0.0, + TreeLinesSize = 1.0, -- Thickness of outlines when using ImGuiTreeNodeFlags.DrawLines. + TreeLinesRounding = 0.0, -- Radius of lines connecting child nodes to the vertical line. + MenuItemRounding = 0.0, -- Radius of MenuItem, BeginMenu rounding. + SelectableRounding = 0.0, -- Radius of selectable rounding. MODIFYING THIS IS DISCOURAGED. CONTIGUOUS SELECTIONS WILL NOT LOOK RIGHT. (#7589) - ColorMarkerSize = 3.0, - ColorButtonPosition = ImGuiDir.Right, + ColorMarkerSize = 3.0, -- Size of R/G/B/A color markers for ColorEdit4() and for Drags/Sliders when using ImGuiSliderFlags.ColorMarkers. + ColorButtonPosition = ImGuiDir.Right, -- Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir.Right. - InputTextCursorSize = 1.0, - SeparatorSize = 1.0, - SeparatorTextBorderSize = 3.0, - SeparatorTextAlign = ImVec2(0.0, 0.5), - SeparatorTextPadding = ImVec2(20.0, 3.0), + InputTextCursorSize = 1.0, -- Thickness of cursor/caret in InputText(). + SeparatorSize = 1.0, -- Thickness of border in Separator(). + SeparatorTextBorderSize = 3.0, -- Thickness of border in SeparatorText(). + SeparatorTextAlign = ImVec2(0.0, 0.5), -- Alignment of text within the separator. Defaults to (0.0, 0.5) (left aligned, center). + SeparatorTextPadding = ImVec2(20.0, 3.0), -- Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. - DisplaySafeAreaPadding = ImVec2(3, 3), - DisplayWindowPadding = ImVec2(19, 19), + 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. + 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. - AntiAliasedLines = true, - AntiAliasedLinesUseTex = true, - AntiAliasedFill = true, + -- Rendering & Tessellation + AntiAliasedLines = true, -- Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawListFlags.AntiAliasedLines in all draw-lists. + AntiAliasedLinesUseTex = true, -- Enable anti-aliased lines/borders using textures for legacy strokes. Require backend to render with bilinear filtering (NOT point/nearest filtering). + AntiAliasedFill = true, -- Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Used at the beginning of the frame to set ImDrawListFlags.AntiAliasedFill in all draw-lists. - CurveTessellationTol = 1.25, - CircleTessellationMaxError = 0.30, + CurveTessellationTol = 1.25, -- Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + CircleTessellationMaxError = 0.30, -- 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. - HoverStationaryDelay = 0.15, - HoverDelayShort = 0.15, - HoverDelayNormal = 0.40, + -- Behaviors + HoverStationaryDelay = 0.15, -- Delay for IsItemHovered(ImGuiHoveredFlags.Stationary). Time required to consider mouse stationary. + HoverDelayShort = 0.15, -- Delay for IsItemHovered(ImGuiHoveredFlags.DelayShort). Usually used along with HoverStationaryDelay. + HoverDelayNormal = 0.40, -- Delay for IsItemHovered(ImGuiHoveredFlags.DelayNormal). " Colors = {}, - ButtonTextAlign = ImVec2(0.5, 0.5), - SelectableTextAlign = ImVec2(0.0, 0.0), + ButtonTextAlign = ImVec2(0.5, 0.5), -- Alignment of button text when button is larger than text. + SelectableTextAlign = ImVec2(0.0, 0.0), -- Alignment of selectable text. Defaults to (0.0, 0.0) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. - WindowMinSize = ImVec2(32, 32), - WindowTitleAlign = ImVec2(0.0, 0.5), - WindowMenuButtonPosition = ImGuiDir.Left, - ChildRounding = 0.0, - ChildBorderSize = 1.0, - PopupRounding = 0.0, - PopupBorderSize = 1.0, + WindowMinSize = ImVec2(32, 32), -- Minimum window size + WindowTitleAlign = ImVec2(0.0, 0.5), -- Alignment for title bar text + WindowMenuButtonPosition = ImGuiDir.Left, -- Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir.Left. + ChildRounding = 0.0, -- Radius of child window corners rounding. Set to 0.0 to have rectangular child windows + ChildBorderSize = 1.0, -- Thickness of border around child windows. Generally set to 0.0 or 1.0. Other values not well tested. + PopupRounding = 0.0, -- Radius of popup window corners rounding. Set to 0.0 to have rectangular child windows + PopupBorderSize = 1.0, -- Thickness of border around popup or tooltip windows. Generally set to 0.0 or 1.0. Other values not well tested. - DockingSeparatorSize = 2.0, - DockingNodeHasCloseButton = true, - MouseCursorScale = 1.0, + DockingSeparatorSize = 2.0, -- Thickness of resizing border between docked windows + DockingNodeHasCloseButton = true, -- Docking nodes have their own CloseButton() to close all docked windows. + MouseCursorScale = 1.0, -- Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. - ItemSpacing = ImVec2(8, 4), - ItemInnerSpacing = ImVec2(4, 4), - CellPadding = ImVec2(4, 2), + ItemSpacing = ImVec2(8, 4), -- Horizontal and vertical spacing between widgets/lines + ItemInnerSpacing = ImVec2(4, 4), -- Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + CellPadding = ImVec2(4, 2), -- Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows. - ColumnsMinSpacing = 6.0, + ColumnsMinSpacing = 6.0, -- Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). - LogSliderDeadzone = 4.0, + LogSliderDeadzone = 4.0, -- The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. - TabRounding = 5.0, - TabBorderSize = 0.0, - TabMinWidthBase = 1.0, - TabMinWidthShrink = 80.0, - TabCloseButtonMinWidthSelected = -1.0, - TabCloseButtonMinWidthUnselected = 0.0, - TabBarBorderSize = 1.0, - TabBarOverlineSize = 1.0, - TableAngledHeadersAngle = 35.0 * (IM_PI / 180.0), - TableAngledHeadersTextAlign = ImVec2(0.5, 0.0), + TabRounding = 5.0, -- Radius of upper corners of a tab. Set to 0.0 to have rectangular tabs. + TabBorderSize = 0.0, -- Thickness of border around tabs. + TabMinWidthBase = 1.0, -- Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected. + TabMinWidthShrink = 80.0, -- Minimum tab width after shrinking, when using ImGuiTabBarFlags.FittingPolicyMixed policy. FLT_MAX: never shrink, will behave like ImGuiTabBarFlags.FittingPolicyScroll. + TabCloseButtonMinWidthSelected = -1.0, -- -1: always visible. 0.0: visible when hovered. >0.0: visible when hovered if minimum width. + TabCloseButtonMinWidthUnselected = 0.0, -- -1: always visible. 0.0: visible when hovered. >0.0: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. + TabBarBorderSize = 1.0, -- Thickness of tab-bar separator, which takes on the tab active color to denote focus. + TabBarOverlineSize = 1.0, -- Thickness of tab-bar overline, which highlights the selected tab-bar. + TableAngledHeadersAngle = 35.0 * (IM_PI / 180.0), -- Angle of angled headers (supported values range from -50 degrees to +50 degrees). + TableAngledHeadersTextAlign = ImVec2(0.5, 0.0), -- Alignment of angled headers within the cell - DragDropTargetRounding = 0.0, - DragDropTargetBorderSize = 2.0, - DragDropTargetPadding = 3.0, + DragDropTargetRounding = 0.0, -- Radius of the drag and drop target frame. + DragDropTargetBorderSize = 2.0, -- Thickness of the drag and drop target border. + DragDropTargetPadding = 3.0, -- Size to expand the drag and drop target from actual target item size. - HoverFlagsForTooltipMouse = bitOr(ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.AllowWhenDisabled), - HoverFlagsForTooltipNav = bitOr(ImGuiHoveredFlags.NoSharedDelay, ImGuiHoveredFlags.DelayNormal, ImGuiHoveredFlags.AllowWhenDisabled), + HoverFlagsForTooltipMouse = bitOr(ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.AllowWhenDisabled), -- Default flags when using IsItemHovered(ImGuiHoveredFlags.ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. + HoverFlagsForTooltipNav = bitOr(ImGuiHoveredFlags.NoSharedDelay, ImGuiHoveredFlags.DelayNormal, ImGuiHoveredFlags.AllowWhenDisabled), -- Default flags when using IsItemHovered(ImGuiHoveredFlags.ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. -- [Internal] _MainScale = 1.0, _NextFrameFontSizeBase = 0.0 } + -- Default theme ImGui.StyleColorsDark(this) setmetatable(this, MT.ImGuiStyle) @@ -42393,6 +47448,7 @@ function ImGuiStyle() return this end +-- Storage for each window pushed into the stack. --- @class ImGuiWindowStackData --- @return ImGuiWindowStackData @@ -42401,12 +47457,13 @@ function ImGuiWindowStackData() return { Window = nil, ParentLastItemDataBackup = ImGuiLastItemData(), - StackSizesInBegin = nil, - DisabledOverrideReenable = nil, + StackSizesInBegin = nil, -- Store size of various stacks for asserting + DisabledOverrideReenable = nil, -- Non-child window override disabled flag DisabledOverrideReenableAlphaBackup = nil } end +-- Storage data for BeginComboPreview()/EndComboPreview() --- @class ImGuiComboPreviewData --- @field PreviewRect ImRect --- @field BackupCursorPos ImVec2 @@ -42432,10 +47489,12 @@ end --- @alias ImStbTexteditState STB_TexteditState +-- Internal state of the currently focused/edited text input box +-- For a given item ID, access with ImGui.GetInputTextState() --- @class ImGuiInputTextState --- @field Ctx ImGuiContext # parent UI context (needs to be set explicitly by parent) --- @field Stb ImStbTexteditState # State for stb_textedit.lua ---- @field Flags ImGuiInputTextFlags +--- @field Flags ImGuiInputTextFlags # copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags.Password is set. --- @field ID ImGuiID # widget id owning the text state --- @field TextLen int # UTF-8 length of the string in TextA (in bytes) --- @field TextSrc ImStringBuffer # == TextA.Data unless read-only, in which case == buf passed to InputText(). For _ReadOnly fields, pointer will be null outside the InputText() call @@ -42457,33 +47516,35 @@ MT.ImGuiInputTextState.__index = MT.ImGuiInputTextState local function ImGuiInputTextState() local this = { - Ctx = nil, - Stb = STB_TexteditState(), -- FIXME: no global! - Flags = 0, - ID = 0, + Ctx = nil, -- parent UI context (needs to be set explicitly by parent). + Stb = STB_TexteditState(), -- FIXME: no global! -- State for stb_textedit.h + Flags = 0, -- copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags.Password is set. + ID = 0, -- widget id owning the text state - TextLen = 0, - TextSrc = nil, - TextA = ImVector(), - TextToRevertTo = ImVector(), - CallbackTextBackup = ImVector(), + TextLen = 0, -- UTF-8 length of the string in TextA (in bytes) + TextSrc = nil, -- == TextA.Data unless read-only, in which case == buf passed to InputText(). For _ReadOnly fields, pointer will be null outside the InputText() call. + TextA = ImVector(), -- main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1). + TextToRevertTo = ImVector(), -- value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered) + CallbackTextBackup = ImVector(), -- temporary storage for callback to support automatic reconcile of undo-stack - BufCapacity = 0, - Scroll = ImVec2(), - LineCount = 0, - WrapWidth = 0.0, + BufCapacity = 0, -- end-user buffer capacity (include zero terminator) + Scroll = ImVec2(), -- horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) + LineCount = 0, -- last line count (solely for debugging) + WrapWidth = 0.0, -- word-wrapping width - CursorAnim = 0.0, - CursorFollow = false, - CursorCenterY = false, - SelectedAllMouseLock = false, - EditedBefore = false, - EditedThisFrame = false, + CursorAnim = 0.0, -- timer for cursor blink, reset on every user action so the cursor reappears immediately + CursorFollow = false, -- set when we want scrolling to follow the current cursor position (not always!) + CursorCenterY = false, -- set when we want scrolling to be centered over the cursor position (while resizing a word-wrapping field) + SelectedAllMouseLock = false, -- after a double-click to select all, we ignore further mouse drags to update selection + EditedBefore = false, -- edited since activated + EditedThisFrame = false, -- edited this frame } return setmetatable(this, MT.ImGuiInputTextState) end +-- Internal temporary state for deactivating InputText() instances. +-- Store as part of ImGuiDeactivatedItemData? --- @class ImGuiInputTextDeactivatedState --- @field ID ImGuiID # widget id owning the text state (which just got deactivated) --- @field ElapseFrame int @@ -42501,19 +47562,20 @@ end --- @nodiscard local function ImGuiInputTextDeactivatedState() return setmetatable({ - ID = 0, + ID = 0, -- widget id owning the text state (which just got deactivated) ElapseFrame = 0, - TextA = ImVector() + TextA = ImVector() -- text buffer }, IMGUI_INPUT_TEXT_DEACTIVATED_STATE) end --- @alias ImGuiKeyRoutingIndex ImS16 +-- Routing table entry (sizeof() == 16 bytes) --- @class ImGuiKeyRoutingData --- @field NextEntryIndex ImGuiKeyRoutingIndex ---- @field Mods ImU16 ---- @field RoutingCurrScore ImU16 ---- @field RoutingNextScore ImU16 +--- @field Mods ImU16 # Technically we'd only need 4-bits but for simplify we store ImGuiMod_ values which need 16-bits. +--- @field RoutingCurrScore ImU16 # [DEBUG] For debug display +--- @field RoutingNextScore ImU16 # Lower is better (0: perfect score) --- @field RoutingCurr ImGuiID --- @field RoutingNext ImGuiID @@ -42522,18 +47584,20 @@ end function ImGuiKeyRoutingData() return { NextEntryIndex = -1, - Mods = 0, - RoutingCurrScore = 0, - RoutingNextScore = 0, + Mods = 0, -- Technically we'd only need 4-bits but for simplify we store ImGuiMod_ values which need 16-bits. + RoutingCurrScore = 0, -- [DEBUG] For debug display + RoutingNextScore = 0, -- Lower is better (0: perfect score) RoutingCurr = ImGuiKeyOwner_NoOwner, RoutingNext = ImGuiKeyOwner_NoOwner } end +-- Routing table: maintain a desired owner for each possible key-chord (key + mods), and setup owner in NewFrame() when mods are matching. +-- Stored in main context (1 instance) --- @class ImGuiKeyRoutingTable ---- @field Index ImGuiKeyRoutingIndex[] +--- @field Index ImGuiKeyRoutingIndex[] # Index of first entry in Entries[] --- @field Entries ImVector ---- @field EntriesNext ImVector +--- @field EntriesNext ImVector # Double-buffer to avoid reallocation (could use a shared buffer) local _ImGuiKeyRoutingTable = {} _ImGuiKeyRoutingTable.__index = _ImGuiKeyRoutingTable @@ -42546,9 +47610,9 @@ end --- @return ImGuiKeyRoutingTable local function ImGuiKeyRoutingTable() local this = setmetatable({ - Index = {}, + Index = {}, -- Index of first entry in Entries[] Entries = ImVector(), - EntriesNext = ImVector() + EntriesNext = ImVector() -- Double-buffer to avoid reallocation (could use a shared buffer) }, _ImGuiKeyRoutingTable) this:Clear() @@ -42556,9 +47620,11 @@ local function ImGuiKeyRoutingTable() return this end +-- Helper: ImGuiTextIndex +-- Maintain a line index for a text buffer. This is a strong candidate to be moved into the public API. --- @class ImGuiTextIndex --- @field Offsets ImVector ---- @field EndOffset int +--- @field EndOffset int # Because we don't own text buffer we need to maintain EndOffset (may bake in LineOffsets?) local IMGUI_TEXT_INDEX = {} IMGUI_TEXT_INDEX.__index = IMGUI_TEXT_INDEX @@ -42588,18 +47654,18 @@ local function ImGuiDebugAllocEntry() end --- @class ImGuiDebugAllocInfo ---- @field TotalAllocCount int +--- @field TotalAllocCount int # Number of call to MemAlloc(). --- @field TotalFreeCount int ---- @field LastEntriesIdx ImS16 ---- @field LastEntriesBuf ImGuiDebugAllocEntry[] +--- @field LastEntriesIdx ImS16 # Current index in buffer +--- @field LastEntriesBuf ImGuiDebugAllocEntry[] # Track last 6 frames that had allocations --- @return ImGuiDebugAllocInfo local function ImGuiDebugAllocInfo() local this = { - TotalAllocCount = 0, + TotalAllocCount = 0, -- Number of call to MemAlloc(). TotalFreeCount = 0, - LastEntriesIdx = 1, - LastEntriesBuf = {nil, nil, nil, nil, nil, nil}, + LastEntriesIdx = 1, -- Current index in buffer + LastEntriesBuf = {nil, nil, nil, nil, nil, nil}, -- Track last 6 frames that had allocations } for i = 1, 6 do @@ -42620,16 +47686,17 @@ local function ImGuiMetricsConfig() } end +-- Storage for navigation query/results --- @class ImGuiNavItemData ---- @field Window ImGuiWindow? ---- @field ID ImGuiID ---- @field FocusScopeId ImGuiID ---- @field RectRel ImRect ---- @field ItemFlags ImGuiItemFlags ---- @field SelectionUserData ImGuiSelectionUserData ---- @field DistBox float ---- @field DistCenter float ---- @field DistAxial float +--- @field Window ImGuiWindow? # Init,Move -- Best candidate window (result->ItemWindow->RootWindowForNav == request->Window) +--- @field ID ImGuiID # Init,Move -- Best candidate item ID +--- @field FocusScopeId ImGuiID # Init,Move -- Best candidate focus scope ID +--- @field RectRel ImRect # Init,Move -- Best candidate bounding box in window relative space +--- @field ItemFlags ImGuiItemFlags # ????,Move -- Best candidate item flags +--- @field SelectionUserData ImGuiSelectionUserData # I+Mov -- Best candidate SetNextItemSelectionUserData() value. Valid if (ItemFlags & ImGuiItemFlags.HasSelectionUserData) +--- @field DistBox float # Move -- Best candidate box distance to current NavId +--- @field DistCenter float # Move -- Best candidate center distance to current NavId +--- @field DistAxial float # Move -- Best candidate axial distance to current NavId local IMGUI_NAV_ITEM_DATA = {} IMGUI_NAV_ITEM_DATA.__index = IMGUI_NAV_ITEM_DATA @@ -42652,10 +47719,14 @@ local function ImGuiNavItemData() return this end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiContext (main Dear ImGui context) +------------------------------------------------------------------------------- + --- @class ImGuiContext --- @field Initialized bool ---- @field WithinFrameScope bool ---- @field WithinFrameScopeWithImplicitWindow bool +--- @field WithinFrameScope bool # Set by NewFrame(), cleared by EndFrame() +--- @field WithinFrameScopeWithImplicitWindow bool # Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed --- @field FrameCount int --- @field FrameCountEnded int --- @field CurrentWindow ImGuiWindow @@ -42715,49 +47786,54 @@ end --- @field DebugAllocInfo ImGuiDebugAllocInfo --- @field TempBuffer ImVector ----------------------------------------------------------------- --- [SECTION] Tab bar, Tab item support (public flags from imgui.h + private extensions) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Tab bar, Tab item support +-- PORT: public flags from imgui.h + private extensions +------------------------------------------------------------------------------- +-- Flags for ImGui.BeginTabBar() --- @enum ImGuiTabBarFlags ImGuiTabBarFlags = { None = 0, - Reorderable = bitLShift(1, 0), - AutoSelectNewTabs = bitLShift(1, 1), - TabListPopupButton = bitLShift(1, 2), - NoCloseWithMiddleMouseButton = bitLShift(1, 3), - NoTabListScrollingButtons = bitLShift(1, 4), - NoTooltip = bitLShift(1, 5), - DrawSelectedOverline = bitLShift(1, 6), - FittingPolicyMixed = bitLShift(1, 7), - FittingPolicyShrink = bitLShift(1, 8), - FittingPolicyScroll = bitLShift(1, 9), + Reorderable = bitLShift(1, 0), -- Allow manually dragging tabs to re-order them + New tabs are appended at the end of list + AutoSelectNewTabs = bitLShift(1, 1), -- Automatically select new tabs when they appear + TabListPopupButton = bitLShift(1, 2), -- Disable buttons to open the tab list popup + NoCloseWithMiddleMouseButton = bitLShift(1, 3), -- Disable behavior of closing tabs (that are submitted with p_open ~= nil) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) p_open = false. + NoTabListScrollingButtons = bitLShift(1, 4), -- Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags.FittingPolicyScroll) + NoTooltip = bitLShift(1, 5), -- Disable tooltips when hovering a tab + DrawSelectedOverline = bitLShift(1, 6), -- Draw selected overline markers over selected tab + + -- Fitting/Resize policy + FittingPolicyMixed = bitLShift(1, 7), -- Shrink down tabs when they don't fit, until width is style.TabMinWidthShrink, then enable scrolling. Setting TabMinWidthShrink to FLT_MAX makes this behave like ImGuiTabBarFlags.FittingPolicyScroll. + FittingPolicyShrink = bitLShift(1, 8), -- Shrink down tabs when they don't fit + FittingPolicyScroll = bitLShift(1, 9), -- Enable scrolling buttons when tabs don't fit -- Private - DockNode = bitLShift(1, 20), + DockNode = bitLShift(1, 20), -- Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around] IsFocused = bitLShift(1, 21), - SaveSettings = bitLShift(1, 22), + SaveSettings = bitLShift(1, 22), -- FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs } ImGuiTabBarFlags.FittingPolicyMask_ = bitOr(ImGuiTabBarFlags.FittingPolicyMixed, ImGuiTabBarFlags.FittingPolicyShrink, ImGuiTabBarFlags.FittingPolicyScroll) ImGuiTabBarFlags.FittingPolicyDefault_ = ImGuiTabBarFlags.FittingPolicyMixed -ImGuiTabBarFlags.FittingPolicyResizeDown = ImGuiTabBarFlags.FittingPolicyShrink +ImGuiTabBarFlags.FittingPolicyResizeDown = ImGuiTabBarFlags.FittingPolicyShrink -- Renamed in 1.92.2 +-- Flags for ImGui.BeginTabItem() --- @enum ImGuiTabItemFlags ImGuiTabItemFlags = { None = 0, - UnsavedDocument = bitLShift(1, 0), - SetSelected = bitLShift(1, 1), - NoCloseWithMiddleMouseButton = bitLShift(1, 2), - NoPushId = bitLShift(1, 3), - NoTooltip = bitLShift(1, 4), - NoReorder = bitLShift(1, 5), - Leading = bitLShift(1, 6), - Trailing = bitLShift(1, 7), - NoAssumedClosure = bitLShift(1, 8), + UnsavedDocument = bitLShift(1, 0), -- Display a dot next to the title + set ImGuiTabItemFlags.NoAssumedClosure. + SetSelected = bitLShift(1, 1), -- Trigger flag to programmatically make the tab selected when calling BeginTabItem() + NoCloseWithMiddleMouseButton = bitLShift(1, 2), -- Disable behavior of closing tabs (that are submitted with p_open ~= nil) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) p_open = false. + NoPushId = bitLShift(1, 3), -- Don't call PushID()/PopID() on BeginTabItem()/EndTabItem() + NoTooltip = bitLShift(1, 4), -- Disable tooltip for the given tab + NoReorder = bitLShift(1, 5), -- Disable reordering this tab or having another tab cross over this tab + Leading = bitLShift(1, 6), -- Enforce the tab position to the left of the tab bar (after the tab list popup button) + Trailing = bitLShift(1, 7), -- Enforce the tab position to the right of the tab bar (before the scrolling buttons) + NoAssumedClosure = bitLShift(1, 8), -- Tab is selected when trying to close + closure is not immediately assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. -- Private - NoCloseButton = bitLShift(1, 20), - Button = bitLShift(1, 21), - Invisible = bitLShift(1, 22), - Unsorted = bitLShift(1, 23), + NoCloseButton = bitLShift(1, 20), -- Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) + Button = bitLShift(1, 21), -- Used by TabItemButton, change the tab item behavior to mimic a button + Invisible = bitLShift(1, 22), -- To reserve space e.g. with ImGuiTabItemFlags.Leading + Unsorted = bitLShift(1, 23), -- [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window. } ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing) @@ -42766,13 +47842,17 @@ ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFl --- @return ImGuiTabItem function ImGuiTabItem() return { - ID = 0, Flags = 0, Window = nil, - LastFrameVisible = -1, LastFrameSelected = -1, + ID = 0, Flags = 0, Window = nil, -- Window: When TabItem is part of a DockNode's TabBar, we hold on to a window. + LastFrameVisible = -1, LastFrameSelected = -1, -- LastFrameSelected: This allows us to infer an ordered list of the last activated tabs with little maintenance + -- Offset: Position relative to beginning of tab bar + -- Width: Width currently displayed + -- ContentWidth: Width of label + padding, stored during BeginTabItem() call (misnamed as "Content" would normally imply width of label only) + -- RequestedWidth: Width optionally requested by caller, -1.0 is unused Offset = 0.0, Width = 0.0, ContentWidth = 0.0, RequestedWidth = -1.0, NameOffset = -1, Name = nil, - BeginOrder = -1, -- 0-based - IndexDuringLayout = -1, -- 0-based - WantClose = false, + BeginOrder = -1, -- 0-based -- BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags.Reorderable + IndexDuringLayout = -1, -- 0-based -- Index only used during TabBarLayout(). Tabs gets reordered so 'Tabs[n].IndexDuringLayout == n' but may mismatch during additions. + WantClose = false, -- Marked as closed by SetTabItemClosed() } end @@ -42781,19 +47861,24 @@ end --- @return ImGuiTabBar function ImGuiTabBar() return { - Window = nil, Tabs = ImVector(), Flags = 0, ID = 0, + Window = nil, Tabs = ImVector(), Flags = 0, ID = 0, -- ID: Zero for tab-bars used by docking + -- SelectedTabId: Selected tab/window + -- NextSelectedTabId: Next selected tab/window. Will also trigger a scrolling animation + -- VisibleTabId: Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) SelectedTabId = 0, NextSelectedTabId = 0, NextScrollToTabId = 0, VisibleTabId = 0, CurrFrameVisible = -1, PrevFrameVisible = -1, - BarRect = ImRect(), BarRectPrevWidth = 0.0, - CurrTabsContentsHeight = 0.0, PrevTabsContentsHeight = 0.0, + BarRect = ImRect(), BarRectPrevWidth = 0.0, -- BarRectPrevWidth: Backup of previous width. When width change we enforce keep horizontal scroll on focused tab. + CurrTabsContentsHeight = 0.0, PrevTabsContentsHeight = 0.0, -- PrevTabsContentsHeight: Record the height of contents submitted below the tab bar + -- WidthAllTabs: Actual width of all tabs (locked during layout) + -- WidthAllTabsIdeal: Ideal width if all tabs were visible and not clipped WidthAllTabs = 0.0, WidthAllTabsIdeal = 0.0, ScrollingAnim = 0.0, ScrollingTarget = 0.0, ScrollingTargetDistToVisibility = 0.0, ScrollingSpeed = 0.0, ScrollingRectMinX = 0.0, ScrollingRectMaxX = 0.0, SeparatorMinX = 0.0, SeparatorMaxX = 0.0, ReorderRequestTabId = 0, ReorderRequestOffset = 0, BeginCount = 0, - WantLayout = false, VisibleTabWasSubmitted = false, TabsAddedNew = false, ScrollButtonEnabled = false, - TabsActiveCount = 0, - LastTabItemIdx = -1, -- 0-based - ItemSpacingY = 0.0, FramePadding = ImVec2(), BackupCursorPos = ImVec2(), + WantLayout = false, VisibleTabWasSubmitted = false, TabsAddedNew = false, ScrollButtonEnabled = false, -- TabsAddedNew: Set to true when a new tab item or button has been added to the tab bar during last frame + TabsActiveCount = 0, -- Number of tabs submitted this frame. + LastTabItemIdx = -1, -- 0-based -- Index of last BeginTabItem() tab for use by EndTabItem() + ItemSpacingY = 0.0, FramePadding = ImVec2(), BackupCursorPos = ImVec2(), -- FramePadding: style.FramePadding locked at the time of BeginTabBar() } end @@ -42806,86 +47891,86 @@ function ImGuiShrinkWidthItem() return { Index = 0, Width = 0.0, InitialWidth = function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this structure local this = { Style = ImGuiStyle(), - ColorStack = ImVector(), - StyleVarStack = ImVector(), + ColorStack = ImVector(), -- Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() + StyleVarStack = ImVector(), -- Stack for PushStyleVar()/PopStyleVar() - inherited by Begin() Config = nil, Initialized = false, - WithinFrameScope = false, - WithinFrameScopeWithImplicitWindow = false, + WithinFrameScope = false, -- Set by NewFrame(), cleared by EndFrame() + WithinFrameScopeWithImplicitWindow = false, -- Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed Windows = ImVector(), -- Windows sorted in display order, back to front WindowsById = {}, -- Map window's ID to window ref - WindowsBorderHoverPadding = 0, + WindowsBorderHoverPadding = 0, -- 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. - WindowsActiveCount = 0, + WindowsActiveCount = 0, -- Number of unique windows submitted by frame - WindowsTempSortBuffer = ImVector(), + WindowsTempSortBuffer = ImVector(), -- Temporary buffer used in EndFrame() to reorder windows so parents are kept before their child CurrentWindowStack = ImVector(), - CurrentWindow = nil, + CurrentWindow = nil, -- Window being drawn into - WindowsFocusOrder = ImVector(), + WindowsFocusOrder = ImVector(), -- Root windows, sorted in focus order, back to front. IO = ImGuiIO(), PlatformIO = ImGuiPlatformIO(), - ConfigFlagsCurrFrame = ImGuiConfigFlags.None, + ConfigFlagsCurrFrame = ImGuiConfigFlags.None, -- = g.IO.ConfigFlags at the time of NewFrame() ConfigFlagsLastFrame = ImGuiConfigFlags.None, MouseLastValidPos = ImVec2(), - KeysMayBeCharInput = ImBitArray(ImGuiKey.NamedKey_COUNT, -ImGuiKey.NamedKey_BEGIN), + KeysMayBeCharInput = ImBitArray(ImGuiKey.NamedKey_COUNT, -ImGuiKey.NamedKey_BEGIN), -- Lookup to tell if a key can emit char input, see IsKeyChordPotentiallyCharInput(). KeysOwnerData = {}, -- size = ImGuiKey.NamedKey_COUNT KeysRoutingTable = ImGuiKeyRoutingTable(), - InputEventsQueue = ImVector(), + InputEventsQueue = ImVector(), -- Input events which will be trickled/written into IO structure. InputEventsNextMouseSource = ImGuiMouseSource.Mouse, InputEventsNextEventId = 1, - MovingWindow = nil, + MovingWindow = nil, -- Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow.RootWindowDockTree. - WheelingWindow = nil, - WheelingWindowStartFrame = -1, WheelingWindowScrolledFrame = -1, + WheelingWindow = nil, -- Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. + WheelingWindowStartFrame = -1, WheelingWindowScrolledFrame = -1, -- This may be set one frame before WheelingWindow is ~= nil WheelingWindowReleaseTimer = 0.0, WheelingWindowRefMousePos = ImVec2(), WheelingWindowWheelRemainder = ImVec2(), WheelingAxisAvg = ImVec2(), - ActiveIdClickOffset = ImVec2(), + ActiveIdClickOffset = ImVec2(), -- Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) - HoveredWindow = nil, - HoveredWindowUnderMovingWindow = nil, - HoveredIdIsDisabled = false, + HoveredWindow = nil, -- Window the mouse is hovering. Will typically catch mouse inputs. + HoveredWindowUnderMovingWindow = nil, -- Hovered window ignoring MovingWindow. Only set if MovingWindow is set. + HoveredIdIsDisabled = false, -- At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. ActiveIdFromShortcut = false, AnyIdHasBeenEditedThisFrame = false, - ActiveId = 0, + ActiveId = 0, -- Active widget ActiveIdWindow = nil, ActiveIdMouseButton = -1, - ActiveIdIsJustActivated = false, + ActiveIdIsJustActivated = false, -- Set at the time of activation for one frame - ActiveIdWasSelected = false, ActiveIdWasSoleSelected = false, + ActiveIdWasSelected = false, ActiveIdWasSoleSelected = false, -- Active ID was selected at the time of activating LastActiveIdWasSelected = false, LastActiveIdWasSoleSelected = false, - ActiveIdNoClearOnFocusLoss = false, - ActiveIdHasBeenPressedBefore = false, + ActiveIdNoClearOnFocusLoss = false, -- Disable losing active id if the active id window gets unfocused. + ActiveIdHasBeenPressedBefore = false, -- Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. - ActiveIdIsAlive = nil, + ActiveIdIsAlive = nil, -- Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) ActiveIdPreviousFrame = 0, ActiveIdTimer = 0.0, - LastActiveId = 0, - LastActiveIdTimer = 0.0, + LastActiveId = 0, -- Store the last non-zero ActiveId, useful for animation. + LastActiveIdTimer = 0.0, -- Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. - ActiveIdUsingNavDirMask = 0x00, - ActiveIdUsingAllKeyboardKeys = false, + ActiveIdUsingNavDirMask = 0x00, -- Active widget will want to read those nav move requests (e.g. can activate a button and move away from it) + ActiveIdUsingAllKeyboardKeys = false, -- Active widget will want to read all keyboard keys inputs. (this is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations) DeactivatedItemData = { ID = 0, @@ -42894,64 +47979,64 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct IsAlive = false }, - HoveredId = 0, - HoveredIdTimer = 0.0, - HoveredIdNotActiveTimer = 0.0, + HoveredId = 0, -- Hovered widget, filled during the frame + HoveredIdTimer = 0.0, -- Measure contiguous hovering time + HoveredIdNotActiveTimer = 0.0, -- Measure contiguous hovering time where the item has not been active HoveredIdAllowOverlap = false, HoverItemDelayId = 0, HoverItemDelayIdPreviousFrame = 0, HoverItemUnlockedStationaryId = 0, HoverWindowUnlockedStationaryId = 0, - HoverItemDelayTimer = 0.0, HoverItemDelayClearTimer = 0.0, + HoverItemDelayTimer = 0.0, HoverItemDelayClearTimer = 0.0, -- Currently used by IsItemHovered() - ActiveIdAllowOverlap = false, + ActiveIdAllowOverlap = false, -- Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) - NavLayer = ImGuiNavLayer.Main, - NavId = 0, + NavLayer = ImGuiNavLayer.Main, -- Focused layer (main scrolling layer, or menu/title bar layer) + NavId = 0, -- Focused item for navigation NavOpenContextMenuItemId = 0, NavOpenContextMenuWindowId = 0, - NavWindow = nil, + NavWindow = nil, -- Focused window for navigation. Could be called 'FocusedWindow' NavHighlightActivatedId = 0, NavHighlightActivatedTimer = 0.0, - NavCursorVisible = false, + NavCursorVisible = false, -- Nav focus cursor/rectangle is visible? We hide it after a mouse click. We show it after a nav move. NavCursorHideFrames = 0, - NavHighlightItemUnderNav = false, - NavIdIsAlive = false, - NavInputSource = ImGuiInputSource.Keyboard, - NavWindowingTarget = nil, NavWindowingTargetAnim = nil, NavWindowingListWindow = nil, + NavHighlightItemUnderNav = false, -- Disable mouse hovering highlight. Highlight navigation focused item instead of mouse hovered item. + NavIdIsAlive = false, -- Nav widget has been seen this frame ~~ NavRectRel is valid + NavInputSource = ImGuiInputSource.Keyboard, -- Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource.Keyboard or ImGuiInputSource.Gamepad + NavWindowingTarget = nil, NavWindowingTargetAnim = nil, NavWindowingListWindow = nil, -- Target window when doing Ctrl+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! NavWindowingTimer = 0.0, NavWindowingHighlightAlpha = 0.0, - NavWindowingToggleLayer = false, - NavWindowingToggleKey = ImGuiKey.None, + NavWindowingToggleLayer = false, -- Set while Alt or GamepadMenu is held, may be cleared by other operations, and processed when releasing the key. + NavWindowingToggleKey = ImGuiKey.None, -- Keyboard/gamepad key used when toggling to menu layer. NavWindowingInputSource = ImGuiInputSource.None, NavWindowingAccumDeltaPos = ImVec2(0.0, 0.0), NavWindowingAccumDeltaSize = ImVec2(0.0, 0.0), - DimBgRatio = 0.0, - LastKeyboardKeyPressTime = -1.0, LastKeyModsChangeTime = -1.0, LastKeyModsChangeFromNoneTime = -1.0, - ConfigNavWindowingKeyNext = bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Tab), - ConfigNavWindowingKeyPrev = bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Tab), - ConfigNavWindowingWithGamepad = true, + DimBgRatio = 0.0, -- 0.0..1.0 animation when fading in a dimming background (for modal window and Ctrl+Tab list) + LastKeyboardKeyPressTime = -1.0, LastKeyModsChangeTime = -1.0, LastKeyModsChangeFromNoneTime = -1.0, -- Record the last time a keyboard key (ignore mouse/gamepad ones) was pressed. + ConfigNavWindowingKeyNext = bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Tab), -- = ImGuiMod_Ctrl | ImGuiKey.Tab (or ImGuiMod_Super | ImGuiKey.Tab on OS X). Set to 0 to disable. For reconfiguration (see #4828) + ConfigNavWindowingKeyPrev = bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Tab), -- = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey.Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey.Tab on OS X) + ConfigNavWindowingWithGamepad = true, -- = true. Enable Ctrl+Tab by holding ImGuiKey.GamepadFaceLeft (== ImGuiKey.NavGamepadMenu). When false, the button may still be used to toggle Menu layer. - NavFocusRoute = ImVector(), + NavFocusRoute = ImVector(), -- Reversed copy focus scope stack for NavId (should contains NavFocusScopeId). This essentially follow the window.ParentWindowForFocusRoute chain. - NavAnyRequest = false, - NavInitRequest = false, + NavAnyRequest = false, -- ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd() + NavInitRequest = false, -- Init request for appearing window to select first item NavInitRequestFromMove = false, - NavInitResult = ImGuiNavItemData(), - NavMoveSubmitted = false, - NavMoveScoringItems = false, + NavInitResult = ImGuiNavItemData(), -- Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) + NavMoveSubmitted = false, -- Move request submitted, will process result on next NewFrame() + NavMoveScoringItems = false, -- Move request submitted, still scoring incoming items NavMoveForwardToNextFrame = false, NavMoveFlags = ImGuiNavMoveFlags.None, NavMoveScrollFlags = ImGuiScrollFlags.None, NavMoveKeyMods = ImGuiMod_None, - NavMoveDir = ImGuiDir.None, NavMoveDirForDebug = ImGuiDir.None, NavMoveClipDir = ImGuiDir.None, - NavMoveResultLocal = ImGuiNavItemData(), - NavMoveResultOther = ImGuiNavItemData(), - NavMoveResultLocalVisible = ImGuiNavItemData(), - NavTabbingResultFirst = ImGuiNavItemData(), - NavScoringRect = ImRect(), - NavScoringNoClipRect = ImRect(), - ConfigNavEnableTabbing = true, - NavTabbingCounter = 0, - NavTabbingDir = 0, - NavNextActivateId = 0, + NavMoveDir = ImGuiDir.None, NavMoveDirForDebug = ImGuiDir.None, NavMoveClipDir = ImGuiDir.None, -- Direction of the move request (left/right/up/down) + NavMoveResultLocal = ImGuiNavItemData(), -- Best move request candidate within NavWindow + NavMoveResultOther = ImGuiNavItemData(), -- Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags.NavFlattened flag) + NavMoveResultLocalVisible = ImGuiNavItemData(), -- Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags.AlsoScoreVisibleSet flag) + NavTabbingResultFirst = ImGuiNavItemData(), -- First tabbing request candidate within NavWindow and flattened hierarchy + NavScoringRect = ImRect(), -- Rectangle used for scoring, in screen space. Based of window.NavRectRel[], modified for directional navigation scoring. + NavScoringNoClipRect = ImRect(), -- Some nav operations (such as PageUp/PageDown) enforce a region which clipper will attempt to always keep submitted. Unset/invalid if inverted. + ConfigNavEnableTabbing = true, -- = true. Enable tabbing (Tab, Shift+Tab). PLEASE LET ME KNOW IF YOU USE THIS. + NavTabbingCounter = 0, -- >0 when counting items for tabbing + NavTabbingDir = 0, -- Generally -1 or +1, 0 when tabbing without a nav id + NavNextActivateId = 0, -- Set by ActivateItemByID(), queued until next frame. NavNextActivateFlags = ImGuiActivateFlags.None, - NavActivateId = 0, NavActivateDownId = 0, NavActivatePressedId = 0, + NavActivateId = 0, NavActivateDownId = 0, NavActivatePressedId = 0, -- ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey.Space) || IsKeyDown(ImGuiKey.Enter) || IsKeyPressed(ImGuiKey.NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItemByID() NavActivateFlags = ImGuiActivateFlags.None, FrameCount = -1, @@ -42962,67 +48047,67 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct Time = 0, - NextItemData = ImGuiNextItemData(), - LastItemData = ImGuiLastItemData(), - NextWindowData = ImGuiNextWindowData(), + NextItemData = ImGuiNextItemData(), -- Storage for SetNextItem** functions + LastItemData = ImGuiLastItemData(), -- Storage for last submitted item (setup by ItemAdd) + NextWindowData = ImGuiNextWindowData(), -- Storage for SetNextWindow** functions - Viewports = ImVector(), + Viewports = ImVector(), -- Active viewports (always 1+, and generally 1 unless multi-viewports are enabled). Each viewports hold their copy of ImDrawData. - FallbackMonitor = nil, + FallbackMonitor = nil, -- Virtual monitor used as fallback if backend doesn't provide monitor information. - GcCompactAll = false, + GcCompactAll = false, -- Request full GC CurrentViewport = nil, MouseViewport = nil, MouseLastHoveredViewport = nil, PlatformLastFocusedViewportId = 1, - ViewportCreatedCount = 0, PlatformWindowsCreatedCount = 0, - ViewportFocusedStampCount = 0, + ViewportCreatedCount = 0, PlatformWindowsCreatedCount = 0, -- Unique sequential creation counter (mostly for testing/debugging) + ViewportFocusedStampCount = 0, -- Every time the front-most window changes, we stamp its viewport with an incrementing counter - Font = nil, - FontSize = 0.0, - FontSizeBase = 0.0, - CurrentDpiScale = 0.0, + Font = nil, -- Currently bound font. (== FontStack.back().Font) + FontSize = 0.0, -- Currently bound font size == line height (== FontSizeBase + externals scales applied in the UpdateCurrentFontSize() function). + FontSizeBase = 0.0, -- Font size before scaling == style.FontSizeBase == value passed to PushFont() when specified. + CurrentDpiScale = 0.0, -- Current window/viewport DpiScale == CurrentViewport.DpiScale FontRefSize = 0.0, FontRasterizerDensity = 1.0, - FontAtlases = ImVector(), + FontAtlases = ImVector(), -- List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas) - FontStack = ImVector(), + FontStack = ImVector(), -- Stack for PushFont()/PopFont() - inherited by Begin() - OpenPopupStack = ImVector(), - BeginPopupStack = ImVector(), + OpenPopupStack = ImVector(), -- Which popups are open (persistent) + BeginPopupStack = ImVector(), -- Which level of BeginPopup() we are in (reset every frame) TreeNodeStack = ImVector(ImGuiTreeNodeStackData), - WithinEndChildID = 0, WithinEndPopupID = 0, + WithinEndChildID = 0, WithinEndPopupID = 0, -- Set within EndChild() BeginMenuDepth = 0, BeginComboDepth = 0, - ColorEditCurrentID = 0, ColorEditSavedID = 0, - ColorEditSavedHue = 0.0, ColorEditSavedSat = 0.0, - ColorEditSavedColor = 0, - ColorPickerRef = ImVec4(), + ColorEditCurrentID = 0, ColorEditSavedID = 0, -- Set temporarily while inside of the parent-most ColorEdit4/ColorPicker4 (because they call each others). + ColorEditSavedHue = 0.0, ColorEditSavedSat = 0.0, -- Backup of last Hue associated to LastColor, so we can restore Hue in lossy RGB<>HSV round trips + ColorEditSavedColor = 0, -- RGB value with alpha set to 0. + ColorPickerRef = ImVec4(), -- Initial/reference color at the time of opening the color picker. - MenusIdSubmittedThisFrame = ImVector(), + MenusIdSubmittedThisFrame = ImVector(), -- A list of menu IDs that were rendered at least once DrawListSharedData = ImDrawListSharedData(), StackSizesInBeginForCurrentWindow = nil, MouseCursor = ImGuiMouseCursor.Arrow, - MouseStationaryTimer = 0.0, + MouseStationaryTimer = 0.0, -- Time the mouse has been stationary (with some loose heuristic) InputTextState = ImGuiInputTextState(), - InputTextLineIndex = ImGuiTextIndex(), + InputTextLineIndex = ImGuiTextIndex(), -- Temporary storage InputTextDeactivatedState = ImGuiInputTextDeactivatedState(), InputTextPasswordFontBackupBaked = ImFontBaked(), - InputTextReactivateId = 0, - TempInputId = 0, + InputTextReactivateId = 0, -- ID of InputText to reactivate on next frame (for io.ConfigInputTextEnterKeepActive behavior) + TempInputId = 0, -- Temporary text input when using Ctrl+Click on a slider, etc. - ActiveIdValueOnActivation = 0, - DataTypeZeroValue = 0, + ActiveIdValueOnActivation = 0, -- Backup of initial value at the time of activation. ONLY SET BY SPECIFIC WIDGETS: DragXXX and SliderXXX. + DataTypeZeroValue = 0, -- 0 for all data types ComboPreviewData = ImGuiComboPreviewData(), @@ -43031,97 +48116,97 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct -- Docking DockContext = ImGuiDockContext(), DockNodeWindowMenuHandler = nil, - DebugHoveredDockNode = nil, + DebugHoveredDockNode = nil, -- Hovered dock node. CurrentTabBarStack = ImVector(), -- holds ImGuiTabBar references directly (no ImGuiPtrOrIndex needed in Lua) ShrinkWidthBuffer = ImVector(), -- ImGuiShrinkWidthItem - WindowResizeBorderExpectedRect = ImRect(), + WindowResizeBorderExpectedRect = ImRect(), -- Expected border rect, switch to relative edit if moving WindowResizeRelativeMode = false, - ScrollbarSeekMode = 0, - ScrollbarClickDeltaToGrabCenter = 0.0, + ScrollbarSeekMode = 0, -- 0: scroll to clicked location, -1/+1: prev/next page. + ScrollbarClickDeltaToGrabCenter = 0.0, -- When scrolling to mouse location: distance between mouse and center of grab box, normalized in parent space. SliderGrabClickOffset = 0.0, - SliderCurrentAccum = 0.0, - SliderCurrentAccumDirty = false, + SliderCurrentAccum = 0.0, -- Accumulated slider delta when using navigation controls. + SliderCurrentAccumDirty = false, -- Has the accumulated slider delta changed since last time we tried to apply it? DragCurrentAccumDirty = false, - DragCurrentAccum = 0.0, - DragSpeedDefaultRatio = 1.0 / 100.0, + DragCurrentAccum = 0.0, -- Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings + DragSpeedDefaultRatio = 1.0 / 100.0, -- If speed == 0.0, uses (max-min) * DragSpeedDefaultRatio TooltipOverrideCount = 0, - TooltipPreviousWindow = nil, + TooltipPreviousWindow = nil, -- Window of last tooltip submitted during the frame - FocusScopeStack = ImVector(), - CurrentFocusScopeId = 0, - CurrentItemFlags = ImGuiItemFlags.None, + FocusScopeStack = ImVector(), -- Stack for PushFocusScope()/PopFocusScope() - inherited by BeginChild(), pushed into by Begin() + CurrentFocusScopeId = 0, -- Value for currently appending items == g.FocusScopeStack.back(). Not to be mistaken with g.NavFocusScopeId. + CurrentItemFlags = ImGuiItemFlags.None, -- Value for currently appending items == g.ItemFlagsStack.back() - DisabledAlphaBackup = 0.0, + DisabledAlphaBackup = 0.0, -- Backup for style.Alpha for BeginDisabled() DisabledStackSize = 0, - ItemFlagsStack = ImVector(), - GroupStack = ImVector(), + ItemFlagsStack = ImVector(), -- Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() + GroupStack = ImVector(), -- Stack for BeginGroup()/EndGroup() - not inherited by Begin() - PlatformImeData = ImGuiPlatformImeData(), - PlatformImeDataPrev = ImGuiPlatformImeData(), + PlatformImeData = ImGuiPlatformImeData(), -- 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. + PlatformImeDataPrev = ImGuiPlatformImeData(), -- Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. -- Extensions - UserTextures = ImVector(), + UserTextures = ImVector(), -- List of textures created/managed by user or third-party extension. Automatically appended into platform_io.Textures[]. -- Settings SettingsLoaded = false, - SettingsDirtyTimer = 0.0, + SettingsDirtyTimer = 0.0, -- Save .ini Settings to memory when time reaches zero SettingsIniData = "", -- In memory .ini settings (string) SettingsHandlers = ImVector(), -- List of .ini settings handlers - SettingsWindows = ImVector(), - SettingsTables = ImVector(), + SettingsWindows = ImVector(), -- ImGuiWindow .ini settings entries + SettingsTables = ImVector(), -- ImGuiTable .ini settings entries -- Hooks - Hooks = ImVector(), - HookIdNext = 0, + Hooks = ImVector(), -- Hooks for extensions (e.g. test engine) + HookIdNext = 0, -- Next available HookId -- Drag and Drop DragDropActive = false, - DragDropWithinSource = false, - DragDropWithinTarget = false, + DragDropWithinSource = false, -- Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source. + DragDropWithinTarget = false, -- Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target. DragDropSourceFlags = 0, DragDropSourceFrameCount = -1, DragDropMouseButton = -1, DragDropPayload = ImGuiPayload(), - DragDropTargetRect = ImRect(), - DragDropTargetClipRect = ImRect(), + DragDropTargetRect = ImRect(), -- Store rectangle of current target candidate (we favor small targets when overlapping) + DragDropTargetClipRect = ImRect(), -- Store ClipRect at the time of item's drawing DragDropTargetId = 0, DragDropTargetFullViewport = 0, DragDropAcceptFlagsCurr = 0, DragDropAcceptFlagsPrev = 0, - DragDropAcceptIdCurrRectSurface = 0.0, - DragDropAcceptFrameCount = -1, - DragDropHoldJustPressedId = 0, + DragDropAcceptIdCurrRectSurface = 0.0, -- Target item surface (we resolve overlapping targets by prioritizing the smaller surface) + DragDropAcceptFrameCount = -1, -- Last time a target expressed a desire to accept the source + DragDropHoldJustPressedId = 0, -- Set when holding a payload just made ButtonBehavior() return a press. - DragDropAcceptIdPrev = 0, DragDropAcceptIdCurr = 0, + DragDropAcceptIdPrev = 0, DragDropAcceptIdCurr = 0, -- Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets) -- Clipper ClipperTempDataStacked = 0, ClipperTempData = ImVector(), -- Logging - LogEnabled = false, + LogEnabled = false, -- Currently capturing LogLineFirstItem = false, - LogFlags = 0, + LogFlags = 0, -- Capture flags/type LogWindow = nil, - LogFile = nil, - LogBuffer = ImGuiTextBuffer(), - LogNextPrefix = nil, LogNextSuffix = nil, + LogFile = nil, -- If ~= nil log to stdout/ file + LogBuffer = ImGuiTextBuffer(), -- Accumulation buffer when log to clipboard. + LogNextPrefix = nil, LogNextSuffix = nil, -- See comment in LogSetNextTextDecoration(): doesn't copy underlying data, use carefully! LogLinePosY = FLT_MAX, LogDepthRef = 0, LogDepthToExpand = 2, LogDepthToExpandDefault = 2, -- Error handling - ErrorCallback = nil, ErrorCallbackUserData = nil, + ErrorCallback = nil, ErrorCallbackUserData = nil, -- = nil. May be exposed in public API eventually. ErrorTooltipLockedPos = ImVec2(), ErrorFirst = true, - ErrorCountCurrentFrame = 0, - StackSizesInNewFrame = nil, - ContextName = "", - DebugBreakInWindow = 0, + ErrorCountCurrentFrame = 0, -- [Internal] Number of errors submitted this frame. + StackSizesInNewFrame = nil, -- [Internal] + ContextName = "", -- Storage for a context name (to facilitate debugging multi-context setups) + DebugBreakInWindow = 0, -- Set to break in Begin() call. LocalizationTable = {}, @@ -43129,7 +48214,7 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct DebugFlashStyleColorIdx = nil, DebugMetricsConfig = ImGuiMetricsConfig(), - DebugHookIdInfoId = 0, + DebugHookIdInfoId = 0, -- Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool DebugAllocInfo = ImGuiDebugAllocInfo(), --- Misc @@ -43138,16 +48223,16 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct FramerateSecPerFrameCount = 0, FramerateSecPerFrameAccum = 0, - WantCaptureMouseNextFrame = -1, - WantCaptureKeyboardNextFrame = -1, - WantTextInputNextFrame = -1, - TempBuffer = ImVector(), + WantCaptureMouseNextFrame = -1, -- Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1. + WantCaptureKeyboardNextFrame = -1, -- " + WantTextInputNextFrame = -1, -- Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. + TempBuffer = ImVector(), -- Temporary text buffer -- Tables (imgui_tables.lua) CurrentTable = nil, - DebugBreakInTable = 0, - TablesTempDataStacked = 0, - TablesTempData = ImVector(), + DebugBreakInTable = 0, -- Set to break in BeginTable() call. + TablesTempDataStacked = 0, -- Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) + TablesTempData = ImVector(), -- Temporary table data (buffers reused/shared across instances, support nesting) Tables = ImPool(), -- ImPool, 0-based indices (imgui_tables.lua) TablesLastTimeActive = ImVector(), -- [table_idx + 1] = float DrawChannelsTempMergeBuffer = ImVector(), @@ -43173,6 +48258,11 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct return this end +------------------------------------------------------------------------------- +-- [SECTION] Settings support +------------------------------------------------------------------------------- + +-- Windows data saved in imgui.ini file --- @class ImGuiWindowSettings --- @field ID int # Window ID --- @field Pos ImVec2 # Window position @@ -43192,22 +48282,23 @@ end function ImGuiWindowSettings() return setmetatable({ ID = 0, - Pos = ImVec2(0, 0), + Pos = ImVec2(0, 0), -- NB: Settings position are stored RELATIVE to the viewport! Whereas runtime ones are absolute positions. Size = ImVec2(0, 0), Collapsed = false, IsChild = false, - WantApply = false, - WantDelete = false, + WantApply = false, -- Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) + WantDelete = false, -- Set to invalidate/delete the settings entry Name = "", ViewportId = 0, ViewportPos = ImVec2(0, 0), - DockId = 0, - DockOrder = -1, - ClassId = 0, + DockId = 0, -- ID of last known DockNode (even if the DockNode is invisible because it has only 1 active window), or 0 if none. + DockOrder = -1, -- Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. + ClassId = 0, -- ID of window class if specified LastUsedDate = 0, }, IMGUI_WINDOW_SETTINGS) end +-- Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper. --- @class ImGuiMenuColumns --- @field TotalWidth ImU32 --- @field NextTotalWidth ImU32 @@ -43226,14 +48317,20 @@ local function ImGuiMenuColumns() TotalWidth = 0, NextTotalWidth = 0, Spacing = 0, - OffsetIcon = 0, - OffsetLabel = 0, + OffsetIcon = 0, -- Always zero for now + OffsetLabel = 0, -- Offsets are locked in Update() OffsetShortcut = 0, OffsetMark = 0, - Widths = {0, 0, 0, 0} + Widths = {0, 0, 0, 0} -- Width of: Icon, Label, Shortcut, Mark (accumulators for current frame) }, MT.ImGuiMenuColumns) end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiWindowTempData, ImGuiWindow +------------------------------------------------------------------------------- + +-- Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. +-- (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..) --- @class ImGuiWindowTempData --- @field CursorPos ImVec2 --- @field CursorPosPrevLine ImVec2 @@ -43267,48 +48364,49 @@ local function ImGuiWindowTempData() return { DockTabItemStatusFlags = 0, DockTabItemRect = ImRect(), - CursorPos = ImVec2(), + CursorPos = ImVec2(), -- Current emitting position, in absolute coordinates. CursorPosPrevLine = ImVec2(), - CursorStartPos = ImVec2(), - CursorMaxPos = ImVec2(), - IdealMaxPos = ImVec2(), + CursorStartPos = ImVec2(), -- Initial position after Begin(), generally ~ window position + WindowPadding. + CursorMaxPos = ImVec2(), -- Used to implicitly calculate ContentSize at the beginning of next frame, for scrolling range and auto-resize. Always growing during the frame. + IdealMaxPos = ImVec2(), -- Used to implicitly calculate ContentSizeIdeal at the beginning of next frame, for auto-resize only. Always growing during the frame. CurrLineSize = ImVec2(), PrevLineSize = ImVec2(), - CurrLineTextBaseOffset = 0, + CurrLineTextBaseOffset = 0, -- Baseline offset (0.0 by default on a new line, generally == style.FramePadding.y when a framed item has been added). PrevLineTextBaseOffset = 0, IsSameLine = false, IsSetPos = false, - NavLayersActiveMask = 0, NavLayersActiveMaskNext = 0, + NavLayersActiveMask = 0, NavLayersActiveMaskNext = 0, -- Which layers have been written to (result from previous frame) - Indent = ImVec1(), - ColumnsOffset = ImVec1(), + Indent = ImVec1(), -- Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + ColumnsOffset = ImVec1(), -- Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree.Column.Tree. Need revamp columns API. GroupOffset = ImVec1(), - CursorStartPosLossyness = ImVec2(), + CursorStartPosLossyness = ImVec2(), -- Record the loss of precision of CursorStartPos due to really large scrolling amount. This is used by clipper to compensate and fix the most common use case of large scroll area. - ItemWidth = 0, + ItemWidth = 0, -- Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window). ItemWidthDefault = 0, - TextWrapPos = 0, - ItemWidthStack = ImVector(), - TextWrapPosStack = ImVector(), + TextWrapPos = 0, -- Current text wrap pos. + ItemWidthStack = ImVector(), -- Store item widths to restore (attention: .back() is not == ItemWidth) + TextWrapPosStack = ImVector(), -- Store text wrap pos to restore (attention: .back() is not == TextWrapPos) MenuBarAppending = false, -- FIXME: Remove this - MenuBarOffset = ImVec2(), - MenuColumns = ImGuiMenuColumns(), - TreeDepth = 0, - TreeHasStackDataDepthMask = nil, - TreeRecordsClippedNodesY2Mask = nil, + MenuBarOffset = ImVec2(), -- 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. + MenuColumns = ImGuiMenuColumns(), -- Simplified columns storage for menu items measurement + TreeDepth = 0, -- Current tree depth. + TreeHasStackDataDepthMask = nil, -- Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. Sync any changes with TREE_NODE_MAX_DEPTH/TREE_NODE_GET_DEPTH_MASK! + TreeRecordsClippedNodesY2Mask = nil, -- Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. ChildWindows = ImVector(), CurrentTableIdx = -1, -- 0-based index into g.Tables, -1 if none CurrentColumns = nil, -- ImGuiOldColumns (legacy Columns API) - StateStorage = nil, + StateStorage = nil, -- Current persistent per-window storage (store e.g. tree node open/close state) LayoutType = nil } end +-- Storage for one window --- @class ImGuiWindow --- @field Ctx ImGuiContext --- @field Name string @@ -43352,6 +48450,7 @@ end MT.ImGuiWindow = {} MT.ImGuiWindow.__index = MT.ImGuiWindow +-- We don't use g.FontSize because the window may be != g.CurrentWindow. --- @return ImRect --- @nodiscard function MT.ImGuiWindow:Rect() @@ -43375,58 +48474,58 @@ end --- @nodiscard function ImGuiWindow(ctx, name) local this = { - ID = 0, + ID = 0, -- == ImHashStr(Name) - MoveId = 0, + MoveId = 0, -- == window.GetID("#MOVE") - Ctx = ctx, - Name = name, + Ctx = ctx, -- Parent UI context (needs to be set explicitly by parent). + Name = name, -- Window name Flags = 0, - ChildFlags = 0, - WindowClass = ImGuiWindowClass(), + ChildFlags = 0, -- Set when window is a child window. See enum ImGuiChildFlags + WindowClass = ImGuiWindowClass(), -- Advanced users only. Set with SetNextWindowClass() - Pos = ImVec2(), + Pos = ImVec2(), -- Position (always rounded-up to nearest pixel) Size = ImVec2(), -- Current size (==SizeFull or collapsed title bar size) - SizeFull = ImVec2(), + SizeFull = ImVec2(), -- Size when non collapsed - Active = false, + Active = false, -- Set to true on Begin(), unless Collapsed WasActive = false, - Collapsed = false, + Collapsed = false, -- Set when collapsing window to become only title-bar - SkipItems = false, + SkipItems = false, -- Set when items can safely be all clipped (e.g. window not visible or collapsed) - SkipRefresh = false, + SkipRefresh = false, -- [EXPERIMENTAL] Reuse previous frame drawn contents, Begin() returns false. CacheSnap = nil, -- [Port] SetNextWindowCached(): state at the last refresh CacheSkipItemsBackup = nil, - Appearing = false, + Appearing = false, -- Set during the frame where the window is appearing (or re-appearing) - Hidden = false, - IsFallbackWindow = false, + Hidden = false, -- Do not display (== HiddenFrames*** > 0) + IsFallbackWindow = false, -- Set on the "Debug##Default" window. - IsExplicitChild = nil, + IsExplicitChild = nil, -- Set when passed _ChildWindow, left to false by BeginDocked() - ResizeBorderHovered = -1, - ResizeBorderHeld = -1, + ResizeBorderHovered = -1, -- Current border being hovered for resize (-1: none, otherwise 0-3) + ResizeBorderHeld = -1, -- Current border being held for resize (-1: none, otherwise 0-3) - BeginCount = 0, - BeginCountPreviousFrame = 0, - BeginOrderWithinParent = 0, - BeginOrderWithinContext = 0, + BeginCount = 0, -- Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) + BeginCountPreviousFrame = 0, -- Number of Begin() during the previous frame + BeginOrderWithinParent = 0, -- Begin() order within immediate parent window, if we are a child window. Otherwise 0. + BeginOrderWithinContext = 0, -- Begin() order within entire imgui context. This is mostly used for debugging submission order related issues. - FocusOrder = nil, + FocusOrder = nil, -- Order within WindowsFocusOrder[], altered when windows are focused. - HiddenFramesCanSkipItems = 0, - HiddenFramesCannotSkipItems = 0, - HiddenFramesForRenderOnly = 0, + HiddenFramesCanSkipItems = 0, -- Hide the window for N frames + HiddenFramesCannotSkipItems = 0, -- Hide the window for N frames while allowing items to be submitted so we can measure their size + HiddenFramesForRenderOnly = 0, -- Hide the window until frame N at Render() time only - DisableInputsFrames = 0, + DisableInputsFrames = 0, -- Disable window interactions for N frames - WindowRounding = 0, - WindowBorderSize = 1, + WindowRounding = 0, -- Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc. + WindowBorderSize = 1, -- Window border size at the time of Begin(). TitleBarHeight = 0, MenuBarHeight = 0, @@ -43434,83 +48533,83 @@ function ImGuiWindow(ctx, name) DecoOuterSizeX2 = 0, DecoOuterSizeY2 = 0, DecoInnerSizeX1 = 0, DecoInnerSizeY1 = 0, - ContentSize = ImVec2(), + ContentSize = ImVec2(), -- Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. ContentSizeIdeal = ImVec2(), - ContentSizeExplicit = ImVec2(), + ContentSizeExplicit = ImVec2(), -- Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). AutoFitFramesX = -1, AutoFitFramesY = -1, AutoFitOnlyGrows = false, - HasCloseButton = true, + HasCloseButton = true, -- Set when the window has a close button (p_open ~= nil) - BgClickFlags = 0, + BgClickFlags = 0, -- Configure behavior of click+dragging on window bg/void or over items. Default sets by io.ConfigWindowsMoveFromTitleBarOnly. If you use this please report in #3379. - SetWindowPosAllowFlags = 0, SetWindowSizeAllowFlags = 0, SetWindowCollapsedAllowFlags = 0, - SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX), - SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX), + SetWindowPosAllowFlags = 0, SetWindowSizeAllowFlags = 0, SetWindowCollapsedAllowFlags = 0, -- store acceptable condition flags for SetNextWindowPos() use. + SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX), -- store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) + SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX), -- store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5, 0.5) for centering; ImVec2(1, 1) for bottom right. - SettingsOffset = -1, + SettingsOffset = -1, -- Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) - ScrollbarSizes = ImVec2(), + ScrollbarSizes = ImVec2(), -- 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. Scroll = ImVec2(), ScrollbarX = false, - ScrollbarY = false, + ScrollbarY = false, -- Are scrollbars visible? ScrollMax = ImVec2(), - ScrollTarget = ImVec2(FLT_MAX, FLT_MAX), - ScrollTargetCenterRatio = ImVec2(0.5, 0.5), - ScrollTargetEdgeSnapDist = ImVec2(), + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX), -- target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0. (FLT_MAX for no change) + ScrollTargetCenterRatio = ImVec2(0.5, 0.5), -- 0.0 = scroll so that target position is at top, 0.5 = scroll so that target position is centered + ScrollTargetEdgeSnapDist = ImVec2(), -- 0.0 = no snapping, >0.0 snapping threshold - ScrollbarXStabilizeToggledHistory = 0, + ScrollbarXStabilizeToggledHistory = 0, -- Used to stabilize scrollbar visibility in case of feedback loops - DrawList = nil, + DrawList = nil, -- == DrawListInst DrawListInst = ImDrawList(ctx.DrawListSharedData), - RootWindow = nil, - RootWindowPopupTree = nil, - RootWindowDockTree = nil, + RootWindow = nil, -- Point to ourself or first ancestor that is not a child window. Doesn't cross through popups/dock nodes. + RootWindowPopupTree = nil, -- Point to ourself or first ancestor that is not a child window. Cross through popups parent<>child. + RootWindowDockTree = nil, -- Point to ourself or first ancestor that is not a child window. Cross through dock nodes. - ParentWindow = nil, + ParentWindow = nil, -- If we are a child _or_ popup _or_ docked window, this is pointing to our parent. Otherwise nil. ParentWindowInBeginStack = nil, - IDStack = ImVector(), + IDStack = ImVector(), -- ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure) - ViewportAllowPlatformMonitorExtend = -1, - Viewport = nil, - ViewportId = 0, - ViewportPos = ImVec2(FLT_MAX, FLT_MAX), + ViewportAllowPlatformMonitorExtend = -1, -- Reset to -1 every frame (index is guaranteed to be valid between NewFrame..EndFrame), only used in the Appearing frame of a tooltip/popup to enforce clamping to a given monitor + Viewport = nil, -- Always set in Begin(). Inactive windows may have a nil value here if their viewport was discarded. + ViewportId = 0, -- We backup the viewport id (since the viewport may disappear or never be created if the window is inactive) + ViewportPos = ImVec2(FLT_MAX, FLT_MAX), -- We backup the viewport position (since the viewport may disappear or never be created if the window is inactive) ViewportOwned = nil, - DC = ImGuiWindowTempData(), + DC = ImGuiWindowTempData(), -- Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. - OuterRectClipped = ImRect(), - InnerRect = ImRect(), - InnerClipRect = ImRect(), - WorkRect = ImRect(), - ParentWorkRect = ImRect(), - ContentRegionRect = ImRect(), + OuterRectClipped = ImRect(), -- == Window.Rect() just after setup in Begin(). == window.Rect() for root window. + InnerRect = ImRect(), -- Inner rectangle (omit title bar, menu bar, scroll bar) + InnerClipRect = ImRect(), -- == InnerRect shrunk by WindowPadding*0.5 on each side, clipped within viewport or parent clip rect. + WorkRect = ImRect(), -- Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0 on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). + ParentWorkRect = ImRect(), -- Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. -- FIXME-WORKRECT: Could be a stack? + ContentRegionRect = ImRect(), -- FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. - ClipRect = ImRect(), + ClipRect = ImRect(), -- Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList.clip_rect_stack.back(). - LastFrameActive = -1, - LastFrameJustFocused = -1, - LastTimeActive = -1.0, + LastFrameActive = -1, -- Last frame number the window was Active. + LastFrameJustFocused = -1, -- Last frame number the window was made Focused. + LastTimeActive = -1.0, -- Last timestamp the window was Active (using float as we don't need high precision there) StateStorage = {}, ColumnsStorage = ImVector(), -- ImVector - WriteAccessed = false, + WriteAccessed = false, -- Set to true when any widget access the current window - FontWindowScale = 1.0, + FontWindowScale = 1.0, -- User scale multiplier per-window, via SetWindowFontScale() FontWindowScaleParents = 1.0, - HitTestHoleSize = ImVec2(), + HitTestHoleSize = ImVec2(), -- Define an optional rectangular hole where mouse will pass-through the window. - NavLastChildNavWindow = nil, + NavLastChildNavWindow = nil, -- When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) NavLastIds = {[0] = 0, [1] = 0}, -- FIXME: 1-based instead - NavRectRel = {[0] = ImRect(), [1] = ImRect()}, - NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, - NavRootFocusScopeId = 0 + NavRectRel = {[0] = ImRect(), [1] = ImRect()}, -- Reference rectangle, in window relative space + NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, -- Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX. + NavRootFocusScopeId = 0 -- Focus Scope ID at the time of Begin() } this.DrawList = this.DrawListInst @@ -43521,27 +48620,27 @@ function ImGuiWindow(ctx, name) this.ID = ImHashStr(name) this.IDStack:push_back(this.ID) this.MoveId = this:GetID("#MOVE") - this.TabId = this:GetID("#TAB") + this.TabId = this:GetID("#TAB") -- == window.GetID("#TAB") -- Docking - this.ChildId = this.ChildId or 0 - this.SetWindowDockAllowFlags = 0 - this.ParentWindowForFocusRoute = nil - this.DockIsActive = false + this.ChildId = this.ChildId or 0 -- ID of corresponding item in parent window (for navigation to return from child window to parent window) + this.SetWindowDockAllowFlags = 0 -- store acceptable condition flags for SetNextWindowDock() use. + this.ParentWindowForFocusRoute = nil -- Set to manual link a window to its logical parent so that Shortcut() chain are honored (e.g. Tool linked to Document) + this.DockIsActive = false -- When docking artifacts are actually visible. When this is set, DockNode is guaranteed to be != nil. ~~ (DockNode != nil) && (DockNode.Windows.Size > 1). this.DockNodeIsVisible = false - this.DockTabIsVisible = false + this.DockTabIsVisible = false -- Is our window visible this frame? ~~ is the corresponding tab selected? this.DockTabWantClose = false - this.DockOrder = -1 + this.DockOrder = -1 -- Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. this.DockStyle = { Colors = {} } for i = 0, 8 do this.DockStyle.Colors[i] = 0 end - this.DockNode = nil - this.DockNodeAsHost = nil - this.DockId = 0 + this.DockNode = nil -- 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. + this.DockNodeAsHost = nil -- Which node are we owning (for parent windows) + this.DockId = 0 -- Backup of last valid DockNode.ID, so single window remember their dock node id even when they are not bound any more return this end --- @class ImDrawDataBuilder ---- @field Layers [ImVector?, ImVector?] +--- @field Layers [ImVector?, ImVector?] # Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData. --- @field LayerData1 ImVector --- @return ImDrawDataBuilder @@ -43549,11 +48648,17 @@ end local function ImDrawDataBuilder() return { - Layers = {nil, nil}, + Layers = {nil, nil}, -- Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData. LayerData1 = ImVector() } end +------------------------------------------------------------------------------- +-- [SECTION] Viewport support +------------------------------------------------------------------------------- + +-- ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!) +-- Every instance of ImGuiViewport is in fact a ImGuiViewportP. --- @class ImGuiViewportP : ImGuiViewport --- @field Window? ImGuiWindow --- @field Idx int # Initial value = -1, then becomes 1-based index @@ -43588,6 +48693,7 @@ function IMGUI_VIEWPORT_P:ClearRequestFlags() self.PlatformRequestResize = false end +-- Calculate work rect pos/size given a set of offset (we have 1 pair of offset for rect locked from last frame data, and 1 pair for currently building rect) function IMGUI_VIEWPORT_P:CalcWorkRectPos(inset_min) return ImVec2(self.Pos.x + inset_min.x, self.Pos.y + inset_min.y) end @@ -43596,11 +48702,13 @@ function IMGUI_VIEWPORT_P:CalcWorkRectSize(inset_min, inset_max) return ImVec2(ImMax(0.0, self.Size.x - inset_min.x - inset_max.x), ImMax(0.0, self.Size.y - inset_min.y - inset_max.y)) end +-- Update public fields function IMGUI_VIEWPORT_P:UpdateWorkRect() self.WorkPos = self:CalcWorkRectPos(self.WorkInsetMin) self.WorkSize = self:CalcWorkRectSize(self.WorkInsetMin, self.WorkInsetMax) end +-- Helpers to retrieve ImRect (we don't need to store BuildWorkRect as every access tend to change it, hence the code asymmetry) --- @nodiscard function IMGUI_VIEWPORT_P:GetMainRect() return ImRect(self.Pos.x, self.Pos.y, @@ -43627,38 +48735,49 @@ end function ImGuiViewportP() local this = setmetatable(ImGuiViewport(), IMGUI_VIEWPORT_P) --- @cast this ImGuiViewportP - this.Window = nil + this.Window = nil -- Set when the viewport is owned by a window (and ImGuiViewportFlags.CanHostOtherWindows is NOT set) this.Idx = -1 - this.LastFrameActive = -1 - this.LastFocusedStampCount = -1 + this.LastFrameActive = -1 -- Last frame number this viewport was activated by a window + this.LastFocusedStampCount = -1 -- Last stamp number from when a window hosted by this viewport was focused (by comparing this value between two viewport we have an implicit viewport z-order we use as fallback) this.LastNameHash = 0 this.LastPos = ImVec2() -- ImGuiViewport() { memset(this, 0, sizeof(*this)); } this.LastSize = ImVec2() - this.Alpha = 1.0 + this.Alpha = 1.0 -- Window opacity (when dragging dockable windows/viewports we make them transparent) this.LastAlpha = 1.0 - this.LastFocusedHadNavWindow = false + this.LastFocusedHadNavWindow = false -- Instead of maintaining a LastFocusedWindow (which may harder to correctly maintain), we merely store weither NavWindow ~= nil last time the viewport was focused. this.PlatformMonitor = -1 - this.BgFgDrawListsLastTimeActive = {-1, -1} - this.BgFgDrawLists = {nil, nil} + this.BgFgDrawListsLastTimeActive = {-1, -1} -- Timestamps for Gc. + this.BgFgDrawLists = {nil, nil} -- Convenience background [1] and foreground [2] draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays. this.DrawDataP = ImDrawData() - this.DrawDataBuilder = ImDrawDataBuilder() + this.DrawDataBuilder = ImDrawDataBuilder() -- Temporary data while building final ImDrawData this.LastPlatformPos = ImVec2(FLT_MAX, FLT_MAX) this.LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX) this.LastRendererSize = ImVec2(FLT_MAX, FLT_MAX) - this.WorkInsetMin = ImVec2(0, 0) - this.WorkInsetMax = ImVec2(0, 0) - this.BuildWorkInsetMin = ImVec2(0, 0) - this.BuildWorkInsetMax = ImVec2(0, 0) + -- Per-viewport work area + -- - Insets are >= 0.0 values, distance from viewport corners to work area. + -- - BeginMainMenuBar() and DockspaceOverViewport() tend to use work area to avoid stepping over existing contents. + -- - Generally 'safeAreaInsets' in iOS land, 'DisplayCutout' in Android land. + this.WorkInsetMin = ImVec2(0, 0) -- Work Area inset locked for the frame. GetWorkRect() always fits within GetMainRect(). + this.WorkInsetMax = ImVec2(0, 0) -- " + this.BuildWorkInsetMin = ImVec2(0, 0) -- Work Area inset accumulator for current frame, to become next frame's WorkInset + this.BuildWorkInsetMax = ImVec2(0, 0) -- " return this end +------------------------------------------------------------------------------- +-- [SECTION] ImFontLoader +------------------------------------------------------------------------------- + +-- 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. --- @class ImFontLoader --- @field Name string --- @field LoaderInit? fun(atlas: ImFontAtlas): bool @@ -43687,13 +48806,24 @@ function ImFontLoader() this.FontSrcContainsGlyph = nil this.FontBakedInit = nil this.FontBakedDestroy = nil - this.FontBakedLoadGlyph = nil + this.FontBakedLoadGlyph = nil -- Required + -- 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? this.FontBakedSrcLoaderDataSize = 0 return this end +------------------------------------------------------------------------------- +-- [SECTION] ImFontAtlas internal API +------------------------------------------------------------------------------- + +-- 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. --- @class ImFontAtlasRectEntry --- @field TargetIndex int # 0-based! When IsUsed = true, TargetIndex = this rect's index in Rects; IsUsed = false, TargetIndex = the next unused RectsIndex entry's index --- @field Generation unsigned_int # How many times this entry is reused @@ -43709,8 +48839,9 @@ function ImFontAtlasRectEntry() } end -local ImFontAtlasRectId_IndexMask_ = 0x0007FFFF -local ImFontAtlasRectId_GenerationMask_ = 0x3FF00000 +-- Refer to ImFontAtlasPackGetRect() to better understand how this works. +local ImFontAtlasRectId_IndexMask_ = 0x0007FFFF -- 20-bits signed: index to access builder.RectsIndex[]. +local ImFontAtlasRectId_GenerationMask_ = 0x3FF00000 -- 10-bits: entry generation, so each ID is unique and get can safely detected old identifiers. local ImFontAtlasRectId_GenerationShift_ = 20 --- @param id ImFontAtlasRectId # Expects 0-based! @@ -43729,6 +48860,7 @@ function ImFontAtlasRectId_Make(index_idx, gen_idx) return bitOr(index_idx, bitLShift(gen_idx, ImFontAtlasRectId_GenerationShift_)) end +-- Data available to potential texture post-processing functions --- @class ImFontAtlasPostProcessData --- @field FontAtlas ImFontAtlas --- @field Font ImFont @@ -43763,6 +48895,7 @@ function ImFontAtlasPostProcessData(atlas, font, font_src, font_baked, glyph, pi FontBaked = font_baked, Glyph = glyph, + -- Pixel data Pixels = pixels, _PixelsBase = pixels_base, Format = format, @@ -43772,10 +48905,14 @@ function ImFontAtlasPostProcessData(atlas, font, font_src, font_baked, glyph, pi } end +------------------------------------------------------------------------------- +-- [SECTION] Inputs support +------------------------------------------------------------------------------- + --- @enum ImGuiInputSource ImGuiInputSource = { None = 0, - Mouse = 1, + Mouse = 1, -- Note: may be Mouse or TouchScreen or Pen. See io.MouseSource to distinguish them. Keyboard = 2, Gamepad = 3, COUNT = 4 @@ -43860,7 +48997,7 @@ function ImGuiInputEvent() return { Type = 0, Source = 0, - EventId = 0, + EventId = 0, -- Unique, sequential increasing integer to identify an event (if you need to correlate them to other data). -- union MousePos = nil, -- if Type == ImGuiInputEventType.MousePos @@ -43873,6 +49010,7 @@ function ImGuiInputEvent() } end +-- [Internal] Key ranges ImGuiKey_Keyboard_BEGIN = ImGuiKey.NamedKey_BEGIN ImGuiKey_Keyboard_END = ImGuiKey.GamepadStart ImGuiKey_Gamepad_BEGIN = ImGuiKey.GamepadStart @@ -43882,12 +49020,13 @@ ImGuiKey_Mouse_END = ImGuiKey.MouseWheelY + 1 ImGuiKey_Aliases_BEGIN = ImGuiKey_Mouse_BEGIN ImGuiKey_Aliases_END = ImGuiKey_Mouse_END +-- [Internal] Named shortcuts for Navigation ImGuiKey.NavKeyboardTweakSlow = ImGuiMod_Ctrl ImGuiKey.NavKeyboardTweakFast = ImGuiMod_Shift ImGuiKey.NavGamepadTweakSlow = ImGuiKey.GamepadL1 ImGuiKey.NavGamepadTweakFast = ImGuiKey.GamepadR1 -ImGuiKey.NavGamepadMenu = ImGuiKey.GamepadFaceLeft -ImGuiKey.NavGamepadContextMenu = ImGuiKey.GamepadFaceUp +ImGuiKey.NavGamepadMenu = ImGuiKey.GamepadFaceLeft -- Toggle menu layer. Hold to enable Windowing. +ImGuiKey.NavGamepadContextMenu = ImGuiKey.GamepadFaceUp -- Open context menu (same as Shift+F10) --- @enum ImGuiInputEventType ImGuiInputEventType = { @@ -43902,19 +49041,33 @@ ImGuiInputEventType = { COUNT = 8 } -ImGuiInputFlags.RepeatRateDefault = bitLShift(1, 1) -ImGuiInputFlags.RepeatRateNavMove = bitLShift(1, 2) -ImGuiInputFlags.RepeatRateNavTweak = bitLShift(1, 3) -ImGuiInputFlags.RepeatUntilRelease = bitLShift(1, 4) -ImGuiInputFlags.RepeatUntilKeyModsChange = bitLShift(1, 5) -ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone = bitLShift(1, 6) -ImGuiInputFlags.RepeatUntilOtherKeyPress = bitLShift(1, 7) -ImGuiInputFlags.LockThisFrame = bitLShift(1, 20) -ImGuiInputFlags.LockUntilRelease = bitLShift(1, 21) -ImGuiInputFlags.CondHovered = bitLShift(1, 22) -ImGuiInputFlags.CondActive = bitLShift(1, 23) +-- Extend ImGuiInputFlags +-- Flags for extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() +-- Don't mistake with ImGuiInputTextFlags! (which is for ImGui.InputText() function) + +-- Flags for IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(), Shortcut() +-- - Repeat mode: Repeat rate selection +ImGuiInputFlags.RepeatRateDefault = bitLShift(1, 1) -- Repeat rate: Regular (default) +ImGuiInputFlags.RepeatRateNavMove = bitLShift(1, 2) -- Repeat rate: Fast +ImGuiInputFlags.RepeatRateNavTweak = bitLShift(1, 3) -- Repeat rate: Faster +-- - Repeat mode: Specify when repeating key pressed can be interrupted. +-- - In theory ImGuiInputFlags.RepeatUntilOtherKeyPress may be a desirable default, but it would break too many behavior so everything is opt-in. +ImGuiInputFlags.RepeatUntilRelease = bitLShift(1, 4) -- Stop repeating when released (default for all functions except Shortcut). This only exists to allow overriding Shortcut() default behavior. +ImGuiInputFlags.RepeatUntilKeyModsChange = bitLShift(1, 5) -- Stop repeating when released OR if keyboard mods are changed (default for Shortcut) +ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone = bitLShift(1, 6) -- Stop repeating when released OR if keyboard mods are leaving the None state. Allows going from Mod+Key to Key by releasing Mod. +ImGuiInputFlags.RepeatUntilOtherKeyPress = bitLShift(1, 7) -- Stop repeating when released OR if any other keyboard key is pressed during the repeat + +-- Flags for SetKeyOwner(), SetItemKeyOwner() +-- - Locking key away from non-input aware code. Locking is useful to make input-owner-aware code steal keys from non-input-owner-aware code. If all code is input-owner-aware locking would never be necessary. +ImGuiInputFlags.LockThisFrame = bitLShift(1, 20) -- Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared at end of frame. +ImGuiInputFlags.LockUntilRelease = bitLShift(1, 21) -- Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared when the key is released or at end of each frame if key is released. + +-- - Condition for SetItemKeyOwner() +ImGuiInputFlags.CondHovered = bitLShift(1, 22) -- Only set if item is hovered (default to both) +ImGuiInputFlags.CondActive = bitLShift(1, 23) -- Only set if item is active (default to both) ImGuiInputFlags.CondDefault_ = bitOr(ImGuiInputFlags.CondHovered, ImGuiInputFlags.CondActive) +-- [Internal] Mask of which function support which flags ImGuiInputFlags.RepeatRateMask_ = bitOr(ImGuiInputFlags.RepeatRateDefault, ImGuiInputFlags.RepeatRateNavMove, ImGuiInputFlags.RepeatRateNavTweak) ImGuiInputFlags.RepeatUntilMask_ = bitOr(ImGuiInputFlags.RepeatUntilRelease, ImGuiInputFlags.RepeatUntilKeyModsChange, ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone, ImGuiInputFlags.RepeatUntilOtherKeyPress) ImGuiInputFlags.RepeatMask_ = bitOr(ImGuiInputFlags.Repeat, ImGuiInputFlags.RepeatRateMask_, ImGuiInputFlags.RepeatUntilMask_) @@ -43943,32 +49096,39 @@ ImGuiPlotType = Histogram = 1 } +------------------------------------------------------------------------------- +-- [SECTION] Navigation support +------------------------------------------------------------------------------- + --- @enum ImGuiActivateFlags ImGuiActivateFlags = { None = 0, - PreferInput = bitLShift(1, 0), - PreferTweak = bitLShift(1, 1), - TryToPreserveState = bitLShift(1, 2), - FromTabbing = bitLShift(1, 3), - FromShortcut = bitLShift(1, 4), - FromFocusApi = bitLShift(1, 5) + PreferInput = bitLShift(1, 0), -- Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default for Enter key. + PreferTweak = bitLShift(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. + TryToPreserveState = bitLShift(1, 2), -- Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection) + FromTabbing = bitLShift(1, 3), -- Activation requested by a tabbing request (ImGuiNavMoveFlags.IsTabbing) + FromShortcut = bitLShift(1, 4), -- Activation requested by an item shortcut via SetNextItemShortcut() function. + FromFocusApi = bitLShift(1, 5) -- Activation requested by an api request (ImGuiNavMoveFlags.FocusApi) } +-- Early work-in-progress API for ScrollToItem() +-- FIXME: Missing flags to request making both edges visible when possible. --- @enum ImGuiScrollFlags ImGuiScrollFlags = { None = 0, - KeepVisibleEdgeX = bitLShift(1, 0), - KeepVisibleEdgeY = bitLShift(1, 1), - KeepVisibleCenterX = bitLShift(1, 2), - KeepVisibleCenterY = bitLShift(1, 3), - AlwaysCenterX = bitLShift(1, 4), - AlwaysCenterY = bitLShift(1, 5), - NoScrollParent = bitLShift(1, 6), + KeepVisibleEdgeX = bitLShift(1, 0), -- If item is not visible: scroll as little as possible on X axis to bring item back into view [default for X axis] + KeepVisibleEdgeY = bitLShift(1, 1), -- If item is not visible: scroll as little as possible on Y axis to bring item back into view [default for Y axis for windows that are already visible] + KeepVisibleCenterX = bitLShift(1, 2), -- If item is not visible: scroll to make the item centered on X axis [rarely used] + KeepVisibleCenterY = bitLShift(1, 3), -- If item is not visible: scroll to make the item centered on Y axis + AlwaysCenterX = bitLShift(1, 4), -- Always center the result item on X axis [rarely used] + AlwaysCenterY = bitLShift(1, 5), -- Always center the result item on Y axis [default for Y axis for appearing window) + NoScrollParent = bitLShift(1, 6), -- Disable forwarding scrolling to parent window if required to keep item/rect visible (only scroll window the function was applied to). } ImGuiScrollFlags.MaskX_ = bitOr(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleCenterX, ImGuiScrollFlags.AlwaysCenterX) ImGuiScrollFlags.MaskY_ = bitOr(ImGuiScrollFlags.KeepVisibleEdgeY, ImGuiScrollFlags.KeepVisibleCenterY, ImGuiScrollFlags.AlwaysCenterY) +-- Stacked storage data for BeginGroup()/EndGroup() --- @class ImGuiGroupData --- @field WindowID ImGuiID --- @field BackupCursorPos ImVec2 @@ -44011,9 +49171,13 @@ end ImGuiTooltipFlags = { None = 0, - OverridePrevious = bitLShift(1, 1) + OverridePrevious = bitLShift(1, 1) -- Clear/ignore previously submitted tooltip (defaults to append) } +------------------------------------------------------------------------------- +-- [SECTION] Popup support +------------------------------------------------------------------------------- + --- @enum ImGuiPopupPositionPolicy ImGuiPopupPositionPolicy = { @@ -44022,6 +49186,7 @@ ImGuiPopupPositionPolicy = Tooltip = 2 } +-- Storage for popup stacks (g.OpenPopupStack and g.BeginPopupStack) --- @class ImGuiPopupData --- @field PopupId ImGuiID --- @field Window ImGuiWindow @@ -44036,32 +49201,38 @@ ImGuiPopupPositionPolicy = --- @nodiscard function ImGuiPopupData() return { - PopupId = 0, - Window = nil, - RestoreNavWindow = nil, - ParentNavLayer = -1, - OpenFrameCount = -1, - OpenParentId = 0, - OpenPopupPos = ImVec2(), - OpenMousePos = ImVec2() + PopupId = 0, -- Set on OpenPopup() + Window = nil, -- Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() + RestoreNavWindow = nil, -- Set on OpenPopup(), a NavWindow that will be restored on popup close + ParentNavLayer = -1, -- Resolved on BeginPopup(). Actually a ImGuiNavLayer type (declared down below), initialized to -1 which is not part of an enum, but serves well-enough as "not any of layers" value + OpenFrameCount = -1, -- Set on OpenPopup() + OpenParentId = 0, -- Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) + OpenPopupPos = ImVec2(), -- Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) + OpenMousePos = ImVec2() -- Set on OpenPopup(), copy of mouse position at the time of opening popup } end --- @enum ImGuiWindowRefreshFlags ImGuiWindowRefreshFlags = { None = 0, - TryToAvoidRefresh = bitLShift(1, 0), - RefreshOnHover = bitLShift(1, 1), - RefreshOnFocus = bitLShift(1, 2) + TryToAvoidRefresh = bitLShift(1, 0), -- [EXPERIMENTAL] Try to keep existing contents, USER MUST NOT HONOR BEGIN() RETURNING FALSE AND NOT APPEND. + RefreshOnHover = bitLShift(1, 1), -- [EXPERIMENTAL] Always refresh on hover + RefreshOnFocus = bitLShift(1, 2) -- [EXPERIMENTAL] Always refresh on focus + -- Refresh policy/frequency, Load Balancing etc. } --- @enum ImGuiNavRenderCursorFlags ImGuiNavRenderCursorFlags = { None = 0, Compact = bitLShift(1, 1), -- Compact highlight, no padding/distance from focused item - AlwaysDraw = bitLShift(1, 2), -- Draw rectangular highlight if (g.NavId == id) even when g.NavCursorVisible == false, aka even when using the mouse + AlwaysDraw = bitLShift(1, 2), -- Draw rectangular highlight if (g.NavId == id) even when g.NavCursorVisible == false, aka even when using the mouse. } +------------------------------------------------------------------------------- +-- [SECTION] Metrics, Debug Tools +------------------------------------------------------------------------------- + +-- See IMGUI_DEBUG_LOG() and IMGUI_DEBUG_LOG_XXX() macros. --- @enum ImGuiDebugLogFlags ImGuiDebugLogFlags = { -- Event types @@ -44080,7 +49251,7 @@ ImGuiDebugLogFlags = { EventViewport = bitLShift(1, 11), EventTable = bitLShift(1, 12), - OutputToTTY = bitLShift(1, 20), + OutputToTTY = bitLShift(1, 20), -- Also send output to TTY OutputToDebugger = bitLShift(1, 21), OutputToTestEngine = bitLShift(1, 22), } @@ -44101,6 +49272,11 @@ ImGuiDebugLogFlags.EventMask_ = bitOr( ImGuiDebugLogFlags.EventViewport ) +------------------------------------------------------------------------------- +-- [SECTION] Localization support +------------------------------------------------------------------------------- + +-- This is experimental and not officially supported, it'll probably fall short of features, if/when it does we may backtrack. --- @enum ImGuiLocKey ImGuiLocKey = { VersionStr = 1, @@ -44139,6 +49315,7 @@ function ImGui.TempInputIsActive(id) return (g.TempInputId == id and g.ActiveId == id) or (g.InputTextDeactivatedState.ID == id) end +-- Get input text state if active --- @param id ImGuiID --- @return ImGuiInputTextState? function ImGui.GetInputTextState(id) @@ -44164,9 +49341,183 @@ end __FILES['imgui_tables.lua'] = function() --- Dear ImGui WIP --- (Tables and Columns Code) +-- (tables and columns code) -- 1:1 port of imgui_tables.cpp (docking branch, 1.93 WIP) + +-- Index of this file: -- +-- [SECTION] Commentary +-- [SECTION] Structs (port: struct constructors from imgui_internal.h / imgui.h) +-- [SECTION] Tables: Main code +-- [SECTION] Tables: Simple accessors +-- [SECTION] Tables: Row changes +-- [SECTION] Tables: Columns changes +-- [SECTION] Tables: Columns width management +-- [SECTION] Tables: Drawing +-- [SECTION] Tables: Sorting +-- [SECTION] Tables: Headers +-- [SECTION] Tables: Context Menu +-- [SECTION] Tables: Settings (.ini data) +-- [SECTION] Tables: Garbage Collection +-- [SECTION] Columns, BeginColumns, EndColumns, etc. + +------------------------------------------------------------------------------- +-- [SECTION] Commentary +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- Typical tables call flow: (root level is generally public API): +------------------------------------------------------------------------------- +-- - BeginTable() user begin into a table +-- | BeginChild() - (if ScrollX/ScrollY is set) +-- | TableBeginInitMemory() - first time table is used +-- | TableResetSettings() - on settings reset +-- | TableLoadSettings() - on settings load +------------------------------------------------------------------------------- +-- - TableSetupColumn() user submit columns details (optional) +-- - TableSetupScrollFreeze() user submit scroll freeze information (optional) +------------------------------------------------------------------------------- +-- - TableUpdateLayout() [Internal] followup to BeginTable(): setup everything: widths, columns positions, clipping rectangles. Automatically called by the FIRST call to TableNextRow() or TableHeadersRow(). +-- | TableApplyQueuedRequests() - apply queued resizing/reordering/hiding requests +-- | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame) +-- | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width +-- | - TableSetColumnDisplayOrder() - apply reordering a column +-- | TableSetupDrawChannels() - setup ImDrawList channels +-- | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission +-- | TableBeginContextMenuPopup() +-- | - TableDrawDefaultContextMenu() - draw right-click context menu contents +------------------------------------------------------------------------------- +-- - TableHeadersRow() or TableHeader() user submit a headers row (optional) +-- | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction +-- | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu +-- - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers) +-- - TableNextRow() user begin into a new row (also automatically called by TableHeadersRow()) +-- | TableEndRow() - finish existing row +-- | TableBeginRow() - add a new row +-- - TableSetColumnIndex() / TableNextColumn() user begin into a cell +-- | TableEndCell() - close existing column/cell +-- | TableBeginCell() - enter into current column/cell +-- - [...] user emit contents +------------------------------------------------------------------------------- +-- - EndTable() user ends the table +-- | TableDrawBorders() - draw outer borders, inner vertical borders +-- | TableMergeDrawChannels() - merge draw channels if clipping isn't required +-- | EndChild() - (if ScrollX/ScrollY is set) +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- TABLE SIZING +------------------------------------------------------------------------------- +-- (Read carefully because this is subtle but it does make sense!) +------------------------------------------------------------------------------- +-- About 'outer_size': +-- Its meaning needs to differ slightly depending on if we are using ScrollX/ScrollY flags. +-- Default value is ImVec2(0.0, 0.0). +-- X +-- - outer_size.x <= 0.0 -> Right-align from window/work-rect right-most edge. With -FLT_MIN or 0.0 will align exactly on right-most edge. +-- - outer_size.x > 0.0 -> Set Fixed width. +-- Y with ScrollX/ScrollY disabled: we output table directly in current window +-- - outer_size.y < 0.0 -> Bottom-align (but will auto extend, unless _NoHostExtendY is set). Not meaningful if parent window can vertically scroll. +-- - outer_size.y = 0.0 -> No minimum height (but will auto extend, unless _NoHostExtendY is set) +-- - outer_size.y > 0.0 -> Set Minimum height (but will auto extend, unless _NoHostExtendY is set) +-- Y with ScrollX/ScrollY enabled: using a child window for scrolling +-- - outer_size.y < 0.0 -> Bottom-align. Not meaningful if parent window can vertically scroll. +-- - outer_size.y = 0.0 -> Bottom-align, consistent with BeginChild(). Not recommended unless table is last item in parent window. +-- - outer_size.y > 0.0 -> Set Exact height. Recommended when using Scrolling on any axis. +------------------------------------------------------------------------------- +-- Outer size is also affected by the NoHostExtendX/NoHostExtendY flags. +-- Important to note how the two flags have slightly different behaviors! +-- - ImGuiTableFlags.NoHostExtendX -> Make outer width auto-fit to columns (overriding outer_size.x value). Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. +-- - ImGuiTableFlags.NoHostExtendY -> Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY is disabled. Data below the limit will be clipped and not visible. +-- In theory ImGuiTableFlags.NoHostExtendY could be the default and any non-scrolling tables with outer_size.y ~= 0.0 would use exact height. +-- This would be consistent but perhaps less useful and more confusing (as vertically clipped items are not useful and not easily noticeable). +------------------------------------------------------------------------------- +-- About 'inner_width': +-- With ScrollX disabled: +-- - inner_width -> *ignored* +-- With ScrollX enabled: +-- - inner_width < 0.0 -> *illegal* fit in known width (right align from outer_size.x) <-- weird +-- - inner_width = 0.0 -> fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns. +-- - inner_width > 0.0 -> override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space! +------------------------------------------------------------------------------- +-- Details: +-- - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept +-- of "available space" doesn't make sense. +-- - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding +-- of what the value does. +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- COLUMNS SIZING POLICIES +-- (Reference: ImGuiTableFlags.SizingXXX flags and ImGuiTableColumnFlags.WidthXXX flags) +------------------------------------------------------------------------------- +-- About overriding column sizing policy and width/weight with TableSetupColumn(): +-- We use a default parameter of -1 for 'init_width'/'init_weight'. +-- - with ImGuiTableColumnFlags.WidthFixed, init_width <= 0 (default) --> width is automatic +-- - with ImGuiTableColumnFlags.WidthFixed, init_width > 0 (explicit) --> width is custom +-- - with ImGuiTableColumnFlags.WidthStretch, init_weight <= 0 (default) --> weight is 1.0 +-- - with ImGuiTableColumnFlags.WidthStretch, init_weight > 0 (explicit) --> weight is custom +-- Widths are specified _without_ CellPadding. If you specify a width of 100.0, the column will be cover (100.0 + Padding * 2.0) +-- and you can fit a 100.0 wide item in it without clipping and with padding honored. +------------------------------------------------------------------------------- +-- About default sizing policy (if you don't specify a ImGuiTableColumnFlags.WidthXXXX flag) +-- - with Table policy ImGuiTableFlags.SizingFixedFit --> default Column policy is ImGuiTableColumnFlags.WidthFixed, default Width is equal to contents width +-- - with Table policy ImGuiTableFlags.SizingFixedSame --> default Column policy is ImGuiTableColumnFlags.WidthFixed, default Width is max of all contents width +-- - with Table policy ImGuiTableFlags.SizingStretchSame --> default Column policy is ImGuiTableColumnFlags.WidthStretch, default Weight is 1.0 +-- - with Table policy ImGuiTableFlags.SizingStretchWeight --> default Column policy is ImGuiTableColumnFlags.WidthStretch, default Weight is proportional to contents +-- Default Width and default Weight can be overridden when calling TableSetupColumn(). +------------------------------------------------------------------------------- +-- About mixing Fixed/Auto and Stretch columns together: +-- - the typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +-- - using mixed policies with ScrollX does not make much sense, as using Stretch columns with ScrollX does not make much sense in the first place! +-- that is, unless 'inner_width' is passed to BeginTable() to explicitly provide a total width to layout columns in. +-- - when using ImGuiTableFlags.SizingFixedSame with mixed columns, only the Fixed/Auto columns will match their widths to the width of the maximum contents. +-- - when using ImGuiTableFlags.SizingStretchSame with mixed columns, only the Stretch columns will match their weights/widths. +------------------------------------------------------------------------------- +-- About using column width: +-- If a column is manually resizable or has a width specified with TableSetupColumn(): +-- - you may use GetContentRegionAvail().x to query the width available in a given column. +-- - right-side alignment features such as SetNextItemWidth(-x) or PushItemWidth(-x) will rely on this width. +-- If the column is not resizable and has no width specified with TableSetupColumn(): +-- - its width will be automatic and be set to the max of items submitted. +-- - therefore you generally cannot have ALL items of the columns use e.g. SetNextItemWidth(-FLT_MIN). +-- - but if the column has one or more items of known/fixed size, this will become the reference width used by SetNextItemWidth(-FLT_MIN). +------------------------------------------------------------------------------- + + +------------------------------------------------------------------------------- +-- TABLES CLIPPING/CULLING +------------------------------------------------------------------------------- +-- About clipping/culling of Rows in Tables: +-- - For large numbers of rows, it is recommended you use ImGuiListClipper to submit only visible rows. +-- ImGuiListClipper is reliant on the fact that rows are of equal height. +-- See 'Demo->Tables->Vertical Scrolling' or 'Demo->Tables->Advanced' for a demo of using the clipper. +-- - Note that auto-resizing columns don't play well with using the clipper. +-- By default a table with _ScrollX but without _Resizable will have column auto-resize. +-- So, if you want to use the clipper, make sure to either enable _Resizable, either setup columns width explicitly with _WidthFixed. +------------------------------------------------------------------------------- +-- About clipping/culling of Columns in Tables: +-- - Both TableSetColumnIndex() and TableNextColumn() return true when the column is visible or performing +-- width measurements. Otherwise, you may skip submitting the contents of a cell/column, BUT ONLY if you know +-- it is not going to contribute to row height. +-- In many situations, you may skip submitting contents for every column but one (e.g. the first one). +-- - Case A: column is not hidden by user, and at least partially in sight (most common case). +-- - Case B: column is clipped / out of sight (because of scrolling or parent ClipRect): TableNextColumn() return false as a hint but we still allow layout output. +-- - Case C: column is hidden explicitly by the user (e.g. via the context menu, or _DefaultHide column flag, etc.). +-- +-- [A] [B] [C] +-- TableNextColumn(): true false false -> [userland] when TableNextColumn() / TableSetColumnIndex() returns false, user can skip submitting items but only if the column doesn't contribute to row height. +-- SkipItems: false false true -> [internal] when SkipItems is true, most widgets will early out if submitted, resulting is no layout output. +-- ClipRect: normal zero-width zero-width -> [internal] when ClipRect is zero, ItemAdd() will return false and most widgets will early out mid-way. +-- ImDrawList output: normal dummy dummy -> [internal] when using the dummy channel, ImDrawList submissions (if any) will be wasted (because cliprect is zero-width anyway). +-- +-- - We need to distinguish those cases because non-hidden columns that are clipped outside of scrolling bounds should still contribute their height to the row. +-- However, in the majority of cases, the contribution to row height is the same for all columns, or the tallest cells are known by the programmer. +------------------------------------------------------------------------------- +-- About clipping/culling of whole Tables: +-- - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false. +------------------------------------------------------------------------------- + -- Port notes: -- - Column indices / display orders / draw channel indices are 0-based VALUES like upstream. -- Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys. @@ -44192,32 +49543,40 @@ end local bit32 = bit32 local band, bor, bnot, lshift, rshift = bit32.band, bit32.bor, bit32.bnot, bit32.lshift, bit32.rshift -IM_COL32_DISABLE = IM_COL32(0, 0, 0, 1) -IMGUI_TABLE_MAX_COLUMNS = 512 +IM_COL32_DISABLE = IM_COL32(0, 0, 0, 1) -- Special sentinel code which cannot be used as a regular color. +IMGUI_TABLE_MAX_COLUMNS = 512 -- Arbitrary "safety" maximum, may be lifted in the future if needed. Must fit in ImGuiTableColumnIdx/ImGuiTableDrawChannelIdx. local function IMGUI_DEBUG_LOG_TABLE(fmt, ...) local g = GImGui if band(g.DebugLogFlags, ImGuiDebugLogFlags.EventTable) ~= 0 then ImGui.DebugLog(fmt, ...) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Structs ----------------------------------------------------------------- +------------------------------------------------------------------------------- local function BitArrayClearAll(arr) table.clear(arr) end local function BitArraySet(arr, n) arr[n] = true end local function BitTest(arr, n) return arr[n] == true end +-- Sorting specification for one column of a table --- @class ImGuiTableColumnSortSpecs function ImGuiTableColumnSortSpecs() return { ColumnUserID = 0, ColumnIndex = 0, SortOrder = 0, SortDirection = ImGuiSortDirection.None } end +-- Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +-- Obtained by calling TableGetSortSpecs(). +-- When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. +-- Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! --- @class ImGuiTableSortSpecs function ImGuiTableSortSpecs() return { Specs = nil, SpecsCount = 0, SpecsDirty = false } end +-- We use the terminology "Enabled" to refer to a column that is not Hidden by user/api. +-- We use the terminology "Clipped" to refer to a column that is out of sight because of scrolling/clipping. +-- This is in contrast with some user-facing api such as IsItemVisible() / IsRectVisible() which use "Visible" to mean "not clipped". --- @class ImGuiTableColumn function ImGuiTableColumn() return { @@ -44248,11 +49607,16 @@ local function TableColumnClone(src) return TableColumnCopy(ImGuiTableColumn(), src) end +-- Per-instance data that needs preserving across frames (seemingly most others do not need to be preserved aside from debug needs. Does that means they could be moved to ImGuiTableTempData?) --- @class ImGuiTableInstanceData function ImGuiTableInstanceData() return { TableInstanceID = 0, LastOuterHeight = 0.0, LastTopHeadersRowHeight = 0.0, LastFrozenHeight = 0.0, HoveredRowLast = -1, HoveredRowNext = -1 } end +-- Transient data that are only needed between BeginTable() and EndTable(), those buffers are shared (1 per level of stacked table). +-- - Accessing those requires chasing an extra pointer so for very frequently used data we leave them in the main table structure. +-- - We also leave out of this structure data that tend to be particularly useful for debugging/metrics. +-- FIXME-TABLE: more transient data could be stored in a stacked ImGuiTableTempData: e.g. SortSpecs. --- @class ImGuiTableTempData function ImGuiTableTempData() return { @@ -44266,6 +49630,7 @@ function ImGuiTableTempData() } end +-- Storage for a table --- @class ImGuiTable function ImGuiTable() return { @@ -44305,11 +49670,13 @@ function ImGuiTableColumnSettings() IsEnabled = -1, IsStretch = 0, IsLoaded = false } end +-- Storage for a table .ini settings --- @class ImGuiTableSettings function ImGuiTableSettings() return { ID = 0, SaveFlags = 0, RefScale = 0.0, ColumnsCount = 0, ColumnsCountMax = 0, LastUsedDate = 0, WantApply = false, Columns = {} } end +-- Storage data for a single column for legacy Columns() api --- @class ImGuiOldColumnData function ImGuiOldColumnData() return { OffsetNorm = 0.0, OffsetNormBeforeResize = 0.0, Flags = 0, ClipRect = ImRect() } @@ -44322,28 +49689,42 @@ function ImGuiOldColumns() HostBackupClipRect = ImRect(), HostBackupParentWorkRect = ImRect(), Columns = ImVector(), Splitter = ImDrawListSplitter() } end +-- Flags for internal's BeginColumns(). This is an obsolete API. Prefer using BeginTable() nowadays! ImGuiOldColumnFlags = ImGuiOldColumnFlags or { None = 0, - NoBorder = lshift(1, 0), - NoResize = lshift(1, 1), - NoPreserveWidths = lshift(1, 2), - NoForceWithinWindow = lshift(1, 3), - GrowParentContentsSize = lshift(1, 4), + NoBorder = lshift(1, 0), -- Disable column dividers + NoResize = lshift(1, 1), -- Disable resizing columns when clicking on the dividers + NoPreserveWidths = lshift(1, 2), -- Disable column width preservation when adjusting columns + NoForceWithinWindow = lshift(1, 3), -- Disable forcing columns to fit within window + GrowParentContentsSize = lshift(1, 4), -- Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. } -ImGuiTableColumnFlags.NoDirectResize_ = ImGuiTableColumnFlags.NoDirectResize_ or lshift(1, 30) +ImGuiTableColumnFlags.NoDirectResize_ = ImGuiTableColumnFlags.NoDirectResize_ or lshift(1, 30) -- [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) local function Rect(r) return ImRect(r.Min.x, r.Min.y, r.Max.x, r.Max.y) end local function V2(v) return ImVec2(v.x, v.y) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Main code ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableFixFlags() [Internal] +-- - TableFindByID() [Internal] +-- - BeginTable() +-- - BeginTableEx() [Internal] +-- - TableBeginInitMemory() [Internal] +-- - TableApplyQueuedRequests() [Internal] +-- - TableSetupColumnFlags() [Internal] +-- - TableUpdateLayout() [Internal] +-- - TableUpdateBorders() [Internal] +-- - EndTable() +-- - TableSetupColumn() +-- - TableSetupScrollFreeze() +------------------------------------------------------------------------------- -- Configuration local TABLE_DRAW_CHANNEL_BG0 = 0 local TABLE_DRAW_CHANNEL_BG2_FROZEN = 1 -local TABLE_DRAW_CHANNEL_NOCLIP = 2 -- When using ImGuiTableFlags_NoClip (this becomes the last visible channel) +local TABLE_DRAW_CHANNEL_NOCLIP = 2 -- When using ImGuiTableFlags.NoClip (this becomes the last visible channel) local TABLE_BORDER_SIZE = 1.0 -- FIXME-TABLE: Currently hard-coded because of clipping assumptions with outer borders rendering. local TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0 -- Extend outside inner borders. local TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06 -- Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped. @@ -44355,7 +49736,7 @@ local function TableFixFlags(flags, outer_window) flags = bor(flags, (band(flags, ImGuiTableFlags.ScrollX) ~= 0 or band(outer_window.Flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0) and ImGuiTableFlags.SizingFixedFit or ImGuiTableFlags.SizingStretchSame) end - -- Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags_SizingFixedSame + -- Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags.SizingFixedSame if band(flags, ImGuiTableFlags.SizingMask_) == ImGuiTableFlags.SizingFixedSame then flags = bor(flags, ImGuiTableFlags.NoKeepColumnsVisible) end @@ -44435,6 +49816,12 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi end -- If an outer size is specified ahead we will be able to early out when not visible. Exact clipping criteria may evolve. + -- FIXME: coarse clipping because access to table data causes two issues: + -- - instance numbers varying/unstable. may not be a direct problem for users, but could make outside access broken or confusing, e.g. TestEngine. + -- - can't implement support for ImGuiChildFlags.ResizeY as we need to somehow pull the height data from somewhere. this also needs stable instance numbers. + -- The side-effects of accessing table data on coarse clip would be: + -- - always reserving the pooled ImGuiTable data ahead for a fully clipped table (minor IMHO). Also the 'outer_window_is_measuring_size' criteria may already be defeating this in some situations. + -- - always performing the GetOrAddByKey() O(log N) query in g.Tables.Map[]. local use_child_window = band(flags, bor(ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY)) ~= 0 local avail_size = ImGui.GetContentRegionAvail() local actual_outer_size = ImTrunc(ImGui.CalcItemSize(outer_size, ImMax(avail_size.x, IMGUI_WINDOW_HARD_MIN_SIZE), use_child_window and ImMax(avail_size.y, IMGUI_WINDOW_HARD_MIN_SIZE) or 0.0)) @@ -44462,7 +49849,7 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi local temp_data = g.TablesTempData.Data[g.TablesTempDataStacked] table_.TempData = temp_data temp_data.TableIndex = table_idx - temp_data.ReconcileColumnsRequests:resize(0) + temp_data.ReconcileColumnsRequests:resize(0) -- FIXME: Use shrink(0) everywhere? table_.DrawSplitter = table_.TempData.DrawSplitter table_.DrawSplitter:Clear() @@ -44504,12 +49891,16 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi -- When not using a child window, WorkRect.Max will grow as we append contents. if use_child_window then -- Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent + -- (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing) local override_content_size = ImVec2(FLT_MAX, FLT_MAX) if band(flags, ImGuiTableFlags.ScrollX) ~= 0 and band(flags, ImGuiTableFlags.ScrollY) == 0 then override_content_size.y = FLT_MIN end - -- Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and never lead to any scrolling). + -- Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and + -- never lead to any scrolling). We don't handle inner_width < 0.0, we could potentially use it to right-align + -- based on the right side of the child window work rect, which would require knowing ahead if we are going to + -- have decoration taking horizontal spaces (typically a vertical scrollbar). if band(flags, ImGuiTableFlags.ScrollX) ~= 0 and inner_width > 0.0 then override_content_size.x = inner_width end @@ -44547,18 +49938,19 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi table_.HasScrollbarYCurr = table_.HasScrollbarYCurr or table_.InnerWindow.ScrollbarY else -- For non-scrolling tables, WorkRect == OuterRect == InnerRect. + -- But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable(). ImRect_Copy(table_.WorkRect, outer_rect) ImRect_Copy(table_.OuterRect, outer_rect) ImRect_Copy(table_.InnerRect, outer_rect) table_.HasScrollbarYPrev = false table_.HasScrollbarYCurr = false - table_.InnerWindow.DC.TreeDepth = table_.InnerWindow.DC.TreeDepth + 1 -- This is designed to always linking ImGuiTreeNodeFlags_DrawLines linking across a table + table_.InnerWindow.DC.TreeDepth = table_.InnerWindow.DC.TreeDepth + 1 -- This is designed to always linking ImGuiTreeNodeFlags.DrawLines linking across a table end -- Push a standardized ID for both child-using and not-child-using tables ImGui.PushOverrideID(id) if instance_no > 0 then - ImGui.PushOverrideID(instance_id) + ImGui.PushOverrideID(instance_id) -- FIXME: Somehow this is not resolved by stack-tool, even tho GetIDWithSeed() submitted the symbol. end -- Backup a copy of host window members we will modify @@ -44579,7 +49971,13 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi inner_window.DC.CurrLineSize.x = 0.0; inner_window.DC.CurrLineSize.y = 0.0 -- Make borders not overlap our contents by offsetting HostClipRect (#6765, #7428, #3752) + -- (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the + -- limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap + -- problem only affect scrolling tables in this case we can get away with doing it without extra cost). if inner_window ~= outer_window then + -- FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window.WindowBorderSize, + -- it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with + -- different x/y values to BeginChild(). local border_size = TABLE_BORDER_SIZE if band(flags, ImGuiTableFlags.BordersOuterV) ~= 0 then table_.HostClipRect.Min.x = ImMin(table_.HostClipRect.Min.x + border_size, table_.HostClipRect.Max.x) @@ -44596,6 +49994,10 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi end -- Padding and Spacing + -- - None ........Content..... Pad .....Content........ + -- - PadOuter | Pad ..Content..... Pad .....Content.. Pad | + -- - PadInner ........Content.. Pad | Pad ..Content........ + -- - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad | local pad_outer_x if band(flags, ImGuiTableFlags.NoPadOuterX) ~= 0 then pad_outer_x = false elseif band(flags, ImGuiTableFlags.PadOuterX) ~= 0 then pad_outer_x = true @@ -44716,9 +50118,12 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi end -- Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call.. + -- This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user. + -- Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. inner_window.SkipItems = true -- Clear names + -- At this point the .NameOffset field of each column will be invalid until TableUpdateLayout() or the first call to TableSetupColumn() if #table_.ColumnsNames > 0 then table.clear(table_.ColumnsNames) end @@ -44746,6 +50151,8 @@ end -- Apply queued resizing/reordering/hiding requests function ImGui.TableApplyQueuedRequests(table_) -- Handle resizing request + -- (We process this in the TableBegin() of the first instance of each table) + -- FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling? if table_.InstanceCurrent == 0 then if table_.ResizedColumn ~= -1 and table_.ResizedColumnNextWidth ~= FLT_MAX then ImGui.TableSetColumnWidth(table_.ResizedColumn, table_.ResizedColumnNextWidth) @@ -44755,6 +50162,7 @@ function ImGui.TableApplyQueuedRequests(table_) table_.ResizedColumn = -1 -- Process auto-fit for single column, which is a special case for stretch columns and fixed columns with FixedSame policy. + -- FIXME-TABLE: Would be nice to redistribute available stretch space accordingly to other weights, instead of giving it all to siblings. if table_.AutoFitSingleColumn ~= -1 then ImGui.TableSetColumnWidth(table_.AutoFitSingleColumn, table_.Columns[table_.AutoFitSingleColumn].WidthAuto) table_.AutoFitSingleColumn = -1 @@ -44762,6 +50170,7 @@ function ImGui.TableApplyQueuedRequests(table_) end -- Handle reordering request + -- Note: we don't clear ReorderColumn after handling the request (FIXME: clarify why or add a test). if table_.InstanceCurrent == 0 then table_.LastHeldHeaderColumn = table_.HeldHeaderColumn table_.HeldHeaderColumn = -1 @@ -44775,6 +50184,8 @@ function ImGui.TableApplyQueuedRequests(table_) if g.ActiveId == 0 then -- FIXME: Need to revisit. See 38f5e5a. table_.ReorderColumn = -1 end + --if (table.HeldHeaderColumn == -1 and table.ReorderColumn ~= -1) + -- table.ReorderColumn = -1 end -- Handle display order / visibility reset requests @@ -44816,8 +50227,10 @@ function ImGui.TableSetColumnDisplayOrder(table_, column_n, dst_order) c.DisplayOrder = c.DisplayOrder - reorder_dir order_n = order_n + reorder_dir end + --IM_ASSERT(dst_column.DisplayOrder == dst_order - reorder_dir) - -- Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[]. Rebuild later from the former. + -- Display order is stored in both columns.IndexDisplayOrder and table.DisplayOrder[]. Rebuild later from the former. + -- FIXME-OPT: If this is called multiple times we'd effectively have a O(N^2) thing going on. for n = 0, table_.ColumnsCount - 1 do table_.DisplayOrderToIndex[table_.Columns[n].DisplayOrder] = n end @@ -44831,11 +50244,12 @@ local function TableGetMaxDisplayOrderAllowed(table_, src_order, dst_order) end -- Cannot cross over the frozen column limit when interactively reordering. + -- TableSetupScrollFreeze() enforce a display order range for frozen columns. Reordering across the frozen column barrier is illegal and will be undone. if table_.FreezeColumnsRequest > 0 then dst_order = (src_order < table_.FreezeColumnsRequest) and ImMin(dst_order, table_.FreezeColumnsRequest - 1) or ImMax(dst_order, table_.FreezeColumnsRequest) end - -- Cannot cross over a column with the ImGuiTableColumnFlags_NoReorder flag. + -- Cannot cross over a column with the ImGuiTableColumnFlags.NoReorder flag. local reorder_dir = (src_order < dst_order) and 1 or -1 local order_n = src_order while (src_order < dst_order and order_n <= dst_order) or (dst_order < src_order and order_n >= dst_order) do @@ -44891,6 +50305,11 @@ local function TableSetupColumnFlags(table_, column, column_n, flags_in) flags = bor(flags, (column_n == 0) and ImGuiTableColumnFlags.IndentEnable or ImGuiTableColumnFlags.IndentDisable) end + -- Alignment + --if (flags & ImGuiTableColumnFlags.AlignMask_) == 0 then + -- flags = bor(flags, ImGuiTableColumnFlags.AlignCenter) + --IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags.AlignMask_)) -- Check that only 1 of each set is used. + -- Preserve status flags column.Flags = bor(flags, band(column.Flags, ImGuiTableColumnFlags.StatusMask_)) @@ -44913,6 +50332,8 @@ end -- Layout columns for the frame. This is in essence the followup to BeginTable() and this is our largest function. -- Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() and other TableSetupXXXXX() functions to be called first. +-- FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns. +-- Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns? function ImGui.TableUpdateLayout(table_) local g = GImGui local temp_data = table_.TempData @@ -44952,7 +50373,11 @@ function ImGui.TableUpdateLayout(table_) ImGui.TableApplyQueuedRequests(table_) -- Handle DPI/font resize - local new_ref_scale_unit = g.FontSize + -- This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well. + -- It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition. + -- FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory. + -- This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path. + local new_ref_scale_unit = g.FontSize -- g.Font.GetCharAdvance('A') ? if table_.RefScale ~= 0.0 and table_.RefScale ~= new_ref_scale_unit then local scale_factor = new_ref_scale_unit / table_.RefScale for n = 0, columns_count - 1 do @@ -44967,11 +50392,12 @@ function ImGui.TableUpdateLayout(table_) BitArrayClearAll(table_.EnabledMaskByIndex) BitArrayClearAll(table_.EnabledMaskByDisplayOrder) table_.LeftMostEnabledColumn = -1 - table_.MinColumnWidth = ImMax(1.0, g.Style.FramePadding.x * 1.0) -- g.Style.ColumnsMinSpacing; // FIXME-TABLE + table_.MinColumnWidth = ImMax(1.0, g.Style.FramePadding.x * 1.0) -- g.Style.ColumnsMinSpacing -- FIXME-TABLE -- [Part 1] Apply/lock Enabled and Order states. Calculate auto/ideal width for columns. Count fixed/stretch columns. - local count_fixed = 0 - local count_stretch = 0 + -- Process columns in their visible orders as we are building the Prev/Next indices. + local count_fixed = 0 -- Number of columns that have fixed sizing policies + local count_stretch = 0 -- Number of columns that have stretch sizing policies local prev_visible_column_idx = -1 local has_auto_fit_request = false local has_resizable = false @@ -44982,6 +50408,8 @@ function ImGui.TableUpdateLayout(table_) local column = table_.Columns[column_n] -- Clear column setup if not submitted by user. Currently we make it mandatory to call TableSetupColumn() every frame. + -- It would easily work without but we're not ready to guarantee it since e.g. names need resubmission anyway. + -- We take a slight shortcut but in theory we could be calling TableSetupColumn() here with dummy values, it should yield the same effect. if table_.DeclColumnsCount <= column_n then TableSetupColumnFlags(table_, column, column_n, ImGuiTableColumnFlags.None) column.NameOffset = -1 @@ -45045,6 +50473,7 @@ function ImGui.TableUpdateLayout(table_) IM_ASSERT(column.IndexWithinEnabledSet <= column.DisplayOrder) -- Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping) + -- Combine width from regular rows + width from headers unless requested not to. if not column.IsPreserveWidthAuto and table_.InstanceCurrent == 0 then column.WidthAuto = ImGui.TableGetColumnWidthAuto(table_, column) end @@ -45076,7 +50505,9 @@ function ImGui.TableUpdateLayout(table_) table_.RightMostEnabledColumn = prev_visible_column_idx IM_ASSERT(table_.LeftMostEnabledColumn >= 0 and table_.RightMostEnabledColumn >= 0) - -- [Part 2] Disable child window clipping while fitting columns. + -- [Part 2] Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid + -- the column fitting having to wait until the first visible frame of the child container (may or not be a good thing). Also see #6510. + -- FIXME-TABLE: for always auto-resizing columns may not want to do that all the time. if has_auto_fit_request and table_.OuterWindow ~= table_.InnerWindow then table_.InnerWindow.SkipItems = false end @@ -45085,8 +50516,8 @@ function ImGui.TableUpdateLayout(table_) end -- [Part 3] Fix column flags and record a few extra information. - local sum_width_requests = 0.0 - local stretch_sum_weights = 0.0 + local sum_width_requests = 0.0 -- Sum of all width for fixed and auto-resize columns, excluding width contributed by Stretch columns but including spacing/padding. + local stretch_sum_weights = 0.0 -- Sum of all weights for stretch columns. table_.LeftMostStretchedColumn = -1; table_.RightMostStretchedColumn = -1 for column_n = 0, columns_count - 1 do if BitTest(table_.EnabledMaskByIndex, column_n) then @@ -45101,6 +50532,7 @@ function ImGui.TableUpdateLayout(table_) end -- Apply automatic width + -- Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!) if column.AutoFitQueue ~= 0x00 then column.WidthRequest = width_auto elseif band(column.Flags, ImGuiTableColumnFlags.WidthFixed) ~= 0 and not column_is_resizable and column.IsRequestOutput then @@ -45108,6 +50540,11 @@ function ImGui.TableUpdateLayout(table_) end -- FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets + -- (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very + -- large height (= first frame scrollbar display very off + clipper would skip lots of items). + -- This is merely making the side-effect less extreme, but doesn't properly fixes it. + -- FIXME: Move this to .WidthGiven to avoid temporary lossyness? + -- FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller. if column.AutoFitQueue > 0x01 and table_.IsInitializing and not column.IsPreserveWidthAuto then column.WidthRequest = ImMax(column.WidthRequest, table_.MinColumnWidth * 4.0) -- FIXME-TABLE: Another constant/scale? end @@ -45159,6 +50596,7 @@ function ImGui.TableUpdateLayout(table_) end -- [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column + -- See additional comments in TableSetColumnWidth(). if column.NextEnabledColumn == -1 and table_.LeftMostStretchedColumn ~= -1 then column.Flags = bor(column.Flags, ImGuiTableColumnFlags.NoDirectResize_) end @@ -45169,7 +50607,8 @@ function ImGui.TableUpdateLayout(table_) end end - -- [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0f * number of Stretch column). + -- [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0 * number of Stretch column). + -- Using right-to-left distribution (more likely to match resizing cursor). if width_remaining_for_stretched_columns >= 1.0 and band(table_.Flags, ImGuiTableFlags.PreciseWidths) == 0 then local order_n = columns_count - 1 while stretch_sum_weights > 0.0 and width_remaining_for_stretched_columns >= 1.0 and order_n >= 0 do @@ -45186,6 +50625,10 @@ function ImGui.TableUpdateLayout(table_) end -- Determine if table is hovered which will be used to flag columns as hovered. + -- - In principle we'd like to use the equivalent of IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem), + -- but because our item is partially submitted at this point we use ItemHoverable() and a workaround (temporarily + -- clear ActiveId, which is equivalent to the change provided by _AllowWhenBLockedByActiveItem). + -- - This allows columns to be marked as hovered when e.g. clicking a button inside the column, or using drag and drop. local table_instance = ImGui.TableGetInstanceData(table_, table_.InstanceCurrent) table_instance.HoveredRowLast = table_instance.HoveredRowNext table_instance.HoveredRowNext = -1 @@ -45205,10 +50648,12 @@ function ImGui.TableUpdateLayout(table_) end -- [Part 6] Setup final position, offset, skip/clip states and clipping rectangles, detect hovered column + -- Process columns in their visible orders as we are comparing the visible order and adjusting host_clip_rect while looping. local has_at_least_one_column_requesting_output = false local offset_x_frozen = (table_.FreezeColumnsCount > 0) local offset_x = ((table_.FreezeColumnsCount > 0) and table_.OuterRect.Min.x or work_rect.Min.x) + table_.OuterPaddingX - table_.CellSpacingX1 local host_clip_rect = Rect(table_.InnerClipRect) + --host_clip_rect.Max.x += table.CellPaddingX + table.CellSpacingX2 BitArrayClearAll(table_.VisibleMaskByIndex) for order_n = 0, columns_count - 1 do local column_n = table_.DisplayOrderToIndex[order_n] @@ -45227,6 +50672,7 @@ function ImGui.TableUpdateLayout(table_) if not BitTest(table_.EnabledMaskByDisplayOrder, order_n) then -- Hidden column: clear a few fields and we are done with it for the remainder of the function. + -- We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper. column.MinX = offset_x; column.MaxX = offset_x; column.WorkMinX = offset_x column.ClipRect.Min.x = offset_x; column.ClipRect.Max.x = offset_x column.WidthGiven = 0.0 @@ -45247,20 +50693,30 @@ function ImGui.TableUpdateLayout(table_) column.MaxX = offset_x + column.WidthGiven + table_.CellSpacingX1 + table_.CellSpacingX2 + table_.CellPaddingX * 2.0 -- Lock other positions + -- - ClipRect.Min.x: Because merging draw commands doesn't compare min boundaries, we make ClipRect.Min.x match left bounds to be consistent regardless of merging. + -- - ClipRect.Max.x: using WorkMaxX instead of MaxX (aka including padding) makes things more consistent when resizing down, tho slightly detrimental to visibility in very-small column. + -- - ClipRect.Max.x: using MaxX makes it easier for header to receive hover highlight with no discontinuity and display sorting arrow. + -- - FIXME-TABLE: We want equal width columns to have equal (ClipRect.Max.x - WorkMinX) width, which means ClipRect.max.x cannot stray off host_clip_rect.Max.x else right-most column may appear shorter. local previous_instance_work_min_x = column.WorkMinX column.WorkMinX = column.MinX + table_.CellPaddingX + table_.CellSpacingX1 column.WorkMaxX = column.MaxX - table_.CellPaddingX - table_.CellSpacingX2 -- Expected max column.ItemWidth = ImTrunc(column.WidthGiven * 0.65) column.ClipRect.Min.x = column.MinX column.ClipRect.Min.y = work_rect.Min.y - column.ClipRect.Max.x = column.MaxX --column->WorkMaxX; + column.ClipRect.Max.x = column.MaxX --column.WorkMaxX column.ClipRect.Max.y = FLT_MAX column.ClipRect:ClipWithFull(host_clip_rect) -- Mark column as Clipped (not in sight) + -- Note that scrolling tables (where inner_window ~= outer_window) handle Y clipped earlier in BeginTable() so IsVisibleY really only applies to non-scrolling tables. + -- FIXME-TABLE: Because InnerClipRect.Max.y is conservatively ==outer_window.ClipRect.Max.y, we never can mark columns _Above_ the scroll line as not IsVisibleY. + -- Taking advantage of LastOuterHeight would yield good results there... + -- FIXME-TABLE: Y clipping is disabled because it effectively means not submitting will reduce contents width which is fed to outer_window.DC.CursorMaxPos.x, + -- and this may be used (e.g. typically by outer_window using AlwaysAutoResize or outer_window's horizontal scrollbar, but could be something else). + -- Possible solution to preserve last known content width for clipped column. Test 'table_reported_size' fails when enabling Y clipping and window is resized small. column.IsVisibleX = (column.ClipRect.Max.x > column.ClipRect.Min.x) - column.IsVisibleY = true -- (column->ClipRect.Max.y > column->ClipRect.Min.y); - local is_visible = column.IsVisibleX --&& column->IsVisibleY; + column.IsVisibleY = true -- (column.ClipRect.Max.y > column.ClipRect.Min.y) + local is_visible = column.IsVisibleX --and column.IsVisibleY if is_visible then BitArraySet(table_.VisibleMaskByIndex, column_n) end @@ -45269,6 +50725,7 @@ function ImGui.TableUpdateLayout(table_) column.IsRequestOutput = is_visible or column.AutoFitQueue ~= 0 or column.CannotSkipItemsQueue ~= 0 -- Mark column as SkipItems (ignoring all items/layout) + -- (table.HostSkipItems is a copy of inner_window.SkipItems before we cleared it above in Part 2) column.IsSkipItems = not column.IsEnabled or table_.HostSkipItems if column.IsSkipItems then IM_ASSERT(not is_visible) @@ -45292,6 +50749,15 @@ function ImGui.TableUpdateLayout(table_) table_.HoveredColumnBody = column_n end + -- Alignment + -- FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in + -- many cases (to be able to honor this we might be able to store a log of cells width, per row, for + -- visible rows, but nav/programmatic scroll would have visible artifacts.) + --if (column.Flags & ImGuiTableColumnFlags.AlignRight) + -- column.WorkMinX = ImMax(column.WorkMinX, column.MaxX - column.ContentWidthRowsUnfrozen) + --else if (column.Flags & ImGuiTableColumnFlags.AlignCenter) + -- column.WorkMinX = ImLerp(column.WorkMinX, ImMax(column.StartX, column.MaxX - column.ContentWidthRowsUnfrozen), 0.5) + -- Reset content width variables if table_.InstanceCurrent == 0 then column.ContentMaxXFrozen = column.WorkMinX @@ -45322,12 +50788,15 @@ function ImGui.TableUpdateLayout(table_) end -- In case the table is visible (e.g. decorations) but all columns clipped, we keep a column visible. + -- Else if give no chance to a clipper-savvy user to submit rows and therefore total contents height used by scrollbar. if has_at_least_one_column_requesting_output == false then table_.Columns[table_.LeftMostEnabledColumn].IsRequestOutput = true table_.Columns[table_.LeftMostEnabledColumn].IsSkipItems = false end -- [Part 7] Detect/store when we are hovering the unused space after the right-most column (so e.g. context menus can react on it) + -- Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either + -- because of using _WidthAuto/_WidthStretch). This will hide the resizing option from the context menu. local unused_x1 = ImMax(table_.WorkRect.Min.x, table_.Columns[table_.RightMostEnabledColumn].ClipRect.Max.x) if is_hovering_table and table_.HoveredColumnBody == -1 then if mouse_skewed_x >= unused_x1 then @@ -45341,6 +50810,8 @@ function ImGui.TableUpdateLayout(table_) table_.IsActiveIdAliveBeforeTable = (g.ActiveIdIsAlive ~= 0) -- [Part 8] Lock actual OuterRect/WorkRect right-most position. + -- This is done late to handle the case of fixed-columns tables not claiming more widths that they need. + -- Because of this we are careful with uses of WorkRect and InnerClipRect before this point. if table_.RightMostStretchedColumn ~= -1 then table_.Flags = band(table_.Flags, bnot(ImGuiTableFlags.NoHostExtendX)) end @@ -45383,12 +50854,17 @@ function ImGui.TableUpdateLayout(table_) end -- [Part 11] Default context menu + -- - To append to this menu: you can 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 and ImGui.TableBeginContextMenuPopup(table_) then ImGui.TableDrawDefaultContextMenu(table_, table_.Flags) ImGui.EndPopup() end -- [Part 12] Sanitize and build sort specs before we have a chance to use them for display. + -- This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change) if table_.IsSortSpecsDirty and band(table_.Flags, ImGuiTableFlags.Sortable) ~= 0 then ImGui.TableSortSpecsBuild(table_) end @@ -45412,7 +50888,7 @@ function ImGui.TableUpdateLayout(table_) if band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0 then table_.DrawSplitter:SetCurrentChannel(inner_window.DrawList, TABLE_DRAW_CHANNEL_NOCLIP) else - inner_window.DrawList:PushClipRect(inner_window.InnerClipRect.Min, inner_window.InnerClipRect.Max, false) -- FIXME: use table->InnerClipRect? + inner_window.DrawList:PushClipRect(inner_window.InnerClipRect.Min, inner_window.InnerClipRect.Max, false) -- FIXME: use table.InnerClipRect? end end @@ -45432,10 +50908,15 @@ function ImGui.TableApplyExternalUnclipRect(table_, rect) end -- Process hit-testing on resizing borders. Actual size change will be applied in EndTable() +-- - Set table.HoveredColumnBorder with a short delay/timer to reduce visual feedback noise. function ImGui.TableUpdateBorders(table_) local g = GImGui IM_ASSERT(band(table_.Flags, ImGuiTableFlags.Resizable) ~= 0) + -- At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and + -- use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not + -- really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height). + -- Actual columns highlight/render will be performed in EndTable() and not be affected. local table_instance = ImGui.TableGetInstanceData(table_, table_.InstanceCurrent) local hit_half_width = ImTrunc(TABLE_RESIZE_SEPARATOR_HALF_THICKNESS * g.CurrentDpiScale) local hit_y1 = ((table_.FreezeRowsCount >= 1) and table_.OuterRect.Min.y or table_.WorkRect.Min.y) + table_.AngledHeadersHeight @@ -45454,7 +50935,7 @@ function ImGui.TableUpdateBorders(table_) break end - -- ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders() + -- ImGuiTableFlags.NoBordersInBodyUntilResize will be honored in TableDrawBorders() local border_y2_hit = (band(table_.Flags, ImGuiTableFlags.NoBordersInBody) ~= 0) and hit_y2_head or hit_y2_body if band(table_.Flags, ImGuiTableFlags.NoBordersInBody) ~= 0 and table_.IsUsingHeaders == false then break @@ -45467,6 +50948,7 @@ function ImGui.TableUpdateBorders(table_) local column_id = ImGui.TableGetColumnResizeID(table_, column_n, table_.InstanceCurrent) local hit_rect = ImRect(column.MaxX - hit_half_width, hit_y1, column.MaxX + hit_half_width, border_y2_hit) ImGui.ItemAdd(hit_rect, column_id, nil, ImGuiItemFlags.NoNav) + --ImGui.GetForegroundDrawList():AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100)) local pressed, hovered, held = ImGui.ButtonBehavior(hit_rect, column_id, bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.PressedOnClick, ImGuiButtonFlags.PressedOnDoubleClick, ImGuiButtonFlags.NoNavFocus)) if pressed and ImGui.IsMouseDoubleClicked(0) then @@ -45494,7 +50976,12 @@ function ImGui.EndTable() local table_ = g.CurrentTable IM_ASSERT_USER_ERROR_RET(table_ ~= nil, "EndTable() call should only be done while in BeginTable() scope!") - -- If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves. + -- This assert would be very useful to catch a common error... unfortunately it would probably trigger in some + -- cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) + --IM_ASSERT(table.IsLayoutLocked, "Table unused: never called TableNextRow(), is that the intent?") + + -- If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our + -- code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc. if not table_.IsLayoutLocked then ImGui.TableUpdateLayout(table_) end @@ -45522,7 +51009,7 @@ function ImGui.EndTable() ImVec2_Copy(inner_window.DC.PrevLineSize, temp_data.HostBackupPrevLineSize) ImVec2_Copy(inner_window.DC.CurrLineSize, temp_data.HostBackupCurrLineSize) ImVec2_Copy(inner_window.DC.CursorMaxPos, temp_data.HostBackupCursorMaxPos) - local inner_content_max_y = ImCeil(table_.RowPosY2) -- Rounding final position is important as we currently don't round row height + local inner_content_max_y = ImCeil(table_.RowPosY2) -- Rounding final position is important as we currently don't round row height ('Demo->Tables->Outer Size' demo uses non-integer heights) IM_ASSERT(table_.RowPosY2 == inner_window.DC.CursorPos.y) if inner_window ~= outer_window then inner_window.DC.CursorMaxPos.y = inner_content_max_y @@ -45534,6 +51021,8 @@ function ImGui.EndTable() table_instance.LastOuterHeight = table_.OuterRect:GetHeight() -- Setup inner scrolling range + -- FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window.DC.CursorMaxPos.y, + -- but since the later is likely to be impossible to do we'd rather update both axes together. if band(table_.Flags, ImGuiTableFlags.ScrollX) ~= 0 then local outer_padding_for_border = (band(table_.Flags, ImGuiTableFlags.BordersOuterV) ~= 0) and TABLE_BORDER_SIZE or 0.0 local max_pos_x = inner_window.DC.CursorMaxPos.x @@ -45634,6 +51123,8 @@ function ImGui.EndTable() outer_window.DC.ColumnsOffset.x = temp_data.HostBackupColumnsOffset -- Layout in outer window + -- (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding + -- CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414) if inner_window ~= outer_window then local backup_nav_layers_active_mask = inner_window.DC.NavLayersActiveMask inner_window.DC.NavLayersActiveMask = bor(inner_window.DC.NavLayersActiveMask, lshift(1, table_.NavLayer)) -- So empty table don't appear to navigate differently. @@ -45649,9 +51140,13 @@ function ImGui.EndTable() -- Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar if band(table_.Flags, ImGuiTableFlags.NoHostExtendX) ~= 0 then + -- FIXME-TABLE: Could we remove this section? + -- ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents IM_ASSERT(band(table_.Flags, ImGuiTableFlags.ScrollX) == 0) outer_window.DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table_.OuterRect.Min.x + table_.ColumnsAutoFitWidth) elseif temp_data.UserOuterSize.x <= 0.0 then + -- Some references for this: #7651 + tests "table_reported_size", "table_reported_size_outer" equivalent Y block, #9352 + -- - FIXME-TABLE: Would make sense to pre-compute expected scrollbar visibility/sizes to generally save a frame of feedback? See broken test in 'table_reported_size_outer' local outer_content_max_x = table_.OuterRect.Min.x + table_.ColumnsAutoFitWidth local decoration_size = table_.TempData.AngledHeadersExtraWidth + ((inner_window ~= outer_window) and inner_window.ScrollbarSizes.x or 0.0) outer_window.DC.IdealMaxPos.x = ImMax(outer_window.DC.IdealMaxPos.x, outer_content_max_x + decoration_size - temp_data.UserOuterSize.x) @@ -45660,13 +51155,14 @@ function ImGui.EndTable() outer_window.DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table_.OuterRect.Max.x) end if temp_data.UserOuterSize.y <= 0.0 then + -- (same comment as above) local outer_content_size_y = (inner_window == outer_window) and (inner_content_max_y - table_.InnerRect.Min.y) or (inner_content_max_y - inner_window.DC.CursorStartPos.y) local outer_content_max_y = table_.OuterRect.Min.y + outer_content_size_y local decoration_size = (inner_window ~= outer_window) and inner_window.ScrollbarSizes.y or 0.0 outer_window.DC.IdealMaxPos.y = ImMax(outer_window.DC.IdealMaxPos.y, outer_content_max_y + decoration_size - temp_data.UserOuterSize.y) outer_window.DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, ImMin(table_.OuterRect.Max.y, outer_content_max_y + decoration_size)) else - -- OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set) + -- OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags.NoHostExtendY is set) outer_window.DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, table_.OuterRect.Max.y) end @@ -45722,16 +51218,18 @@ function ImGui.TableInitColumnDefaults(table_, column, column_n, init_mask) end -- See "COLUMNS SIZING POLICIES" comments at the top of this file --- If (init_width_or_weight <= 0.0f) it is ignored +-- If (init_width_or_weight <= 0.0) it is ignored local function TableSetupColumnApply(table_, idx, id, name_offset, flags, init_width_or_weight, user_data) local column = table_.Columns[idx] -- Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa. + -- Give a grace to users of ImGuiTableFlags.ScrollX. if table_.IsDefaultSizingPolicy and band(flags, ImGuiTableColumnFlags.WidthMask_) == 0 and band(flags, ImGuiTableFlags.ScrollX) == 0 then IM_ASSERT_USER_ERROR_RET(init_width_or_weight <= 0.0, "TableSetupColumn(): can only specify width/weight if sizing policy is set explicitly in either Table or Column.") end -- When passing a width automatically enforce WidthFixed policy + -- (whereas TableSetupColumnFlags would default to WidthAuto if table is not resizable) if band(flags, ImGuiTableColumnFlags.WidthMask_) == 0 and init_width_or_weight > 0.0 then if band(table_.Flags, ImGuiTableFlags.SizingMask_) == ImGuiTableFlags.SizingFixedFit or band(table_.Flags, ImGuiTableFlags.SizingMask_) == ImGuiTableFlags.SizingFixedSame then flags = bor(flags, ImGuiTableColumnFlags.WidthFixed) @@ -45762,10 +51260,11 @@ function ImGui.TableSetupColumn(label, flags, init_width_or_weight, user_data) local table_ = g.CurrentTable IM_ASSERT_USER_ERROR_RET(table_ ~= nil, "Call should only be done while in BeginTable() scope!") IM_ASSERT_USER_ERROR_RET(table_.DeclColumnsCount < table_.ColumnsCount, "TableSetupColumn(): called too many times!") - IM_ASSERT_USER_ERROR_RET(table_.IsLayoutLocked == false, "TableSetupColumn(): need to call before first row!") + IM_ASSERT_USER_ERROR_RET(table_.IsLayoutLocked == false, "TableSetupColumn(): need to call before first row!") -- Table layout is locked when submitting a row or when calling BeginMultiSelect() with box-select. IM_ASSERT(band(flags, ImGuiTableColumnFlags.StatusMask_) == 0, "Illegal to pass StatusMask values to TableSetupColumn()") -- Store name + -- FIXME: If we recorded the number of \n in names we could compute header row height local name_offset = -1 if label ~= nil and label ~= "" then name_offset = #table_.ColumnsNames @@ -45795,6 +51294,9 @@ function ImGui.TableSetupColumn(label, flags, init_width_or_weight, user_data) end -- Reconcile path: defer applying data to TableUpdateLayout() -> TableReconcileMovedColumns() -> TableSetupColumnApply(). + -- On column count change: search the previous columns: + -- - the live Columns[] array is truncated on shrink, so a moved column may only exist in old data. + -- - the live Columns[] array may already be partially reset. local reconcile_data = { ID = column_id, NameOffset = name_offset, Flags = flags, InitWidthOrWeight = init_width_or_weight, UserData = user_data, ColumnNewIdx = column_idx, ColumnOldIdx = -1, ColumnOldData = ImGuiTableColumn(), @@ -45859,9 +51361,9 @@ function ImGui.TableReconcileColumns(table_) end end - -- Apply in the final pass. Because it is possible that src_columns == table->Columns we went through a temporary copy. + -- Apply in the final pass. Because it is possible that src_columns == table.Columns we went through a temporary copy. for _, reconcile_data in reconcile_requests:iter() do - TableColumnCopy(table_.Columns[reconcile_data.ColumnNewIdx], reconcile_data.ColumnOldData) + TableColumnCopy(table_.Columns[reconcile_data.ColumnNewIdx], reconcile_data.ColumnOldData) -- When old column was not found clear anyway with default-constructed data (which will set IsJustCreated=true) TableSetupColumnApply(table_, reconcile_data.ColumnNewIdx, reconcile_data.ID, reconcile_data.NameOffset, reconcile_data.Flags, reconcile_data.InitWidthOrWeight, reconcile_data.UserData) end ImGui.TableFixDisplayOrder(table_) @@ -45886,10 +51388,25 @@ function ImGui.TableSetupScrollFreeze(columns, rows) table_.IsUnfrozenRows = (table_.FreezeRowsCount == 0) -- Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it. end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Simple accessors ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetColumnCount() +-- - TableGetColumnName() +-- - TableGetColumnName() [Internal] +-- - TableSetColumnEnabled() +-- - TableGetColumnFlags() +-- - TableGetCellBgRect() [Internal] +-- - TableGetColumnResizeID() [Internal] +-- - TableGetHoveredColumn() [Internal] +-- - TableGetHoveredRow() [Internal] +-- - TableSetBgColor() +------------------------------------------------------------------------------- +-- [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences, +-- they would meddle many times with the underlying ImDrawCmd. +-- Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let +-- the subsequent single call to SetCurrentChannel() does it things once. function ImGui.SetWindowClipRectBeforeSetChannel(window, clip_rect) local clip_rect_vec4 = clip_rect:ToVec4() ImRect_Copy(window.ClipRect, clip_rect) @@ -45930,6 +51447,11 @@ function ImGui.TableGetColumnName(a, b) end -- Change user accessible enabled/disabled state of a column (often perceived as "showing/hiding" from users point of view) +-- Note that end-user can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags.ContextMenuInBody) +-- - Require table to have the ImGuiTableFlags.Hideable flag because we are manipulating user accessible state. +-- - Request will be applied during next layout, which happens on the first call to TableNextRow() after BeginTable(). +-- - For the getter you can test (TableGetColumnFlags() & ImGuiTableColumnFlags.IsEnabled) ~= 0. +-- - Alternative: the ImGuiTableColumnFlags.Disabled is an overriding/master disable flag which will also hide the column from context menu. function ImGui.TableSetColumnEnabled(column_n, enabled) local g = GImGui local table_ = g.CurrentTable @@ -45961,10 +51483,19 @@ function ImGui.TableGetColumnFlags(column_n) end -- Return the cell rectangle based on currently known height. +-- - Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations. +-- The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it, or in TableEndRow() when we locked that height. +-- - Important: if ImGuiTableFlags.PadOuterX is set but ImGuiTableFlags.PadInnerX is not set, the outer-most left and right +-- columns report a small offset so their CellBgRect can extend up to the outer border. +-- FIXME: But the rendering code in TableEndRow() nullifies that with clamping required for scrolling. function ImGui.TableGetCellBgRect(table_, column_n) local column = table_.Columns[column_n] local x1 = column.MinX local x2 = column.MaxX + --if column.PrevEnabledColumn == -1 then + -- x1 = x1 - table.OuterPaddingX + --if column.NextEnabledColumn == -1 then + -- x2 = x2 + table.OuterPaddingX x1 = ImMax(x1, table_.WorkRect.Min.x) x2 = ImMin(x2, table_.WorkRect.Max.x) return ImRect(x1, table_.RowPosY1, x2, table_.RowPosY2) @@ -45989,6 +51520,8 @@ function ImGui.TableGetHoveredColumn() end -- Return -1 when table is not hovered. Return maxrow+1 if in table but below last submitted row. +-- *IMPORTANT* Unlike TableGetHoveredColumn(), this has a one frame latency in updating the value. +-- This difference with is the reason why this is not public yet. function ImGui.TableGetHoveredRow() local g = GImGui local table_ = g.CurrentTable @@ -46039,11 +51572,16 @@ function ImGui.TableSetBgColor(target, color, column_n) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Row changes ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetRowIndex() +-- - TableNextRow() +-- - TableBeginRow() [Internal] +-- - TableEndRow() [Internal] +------------------------------------------------------------------------------- --- [Public] Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows +-- [Public] Note: for row coloring we use .RowBgColorCounter which is the same value without counting header rows function ImGui.TableGetRowIndex() local g = GImGui local table_ = g.CurrentTable @@ -46111,7 +51649,7 @@ function ImGui.TableBeginRow(table_) window.DC.PrevLineTextBaseOffset = 0.0 window.DC.CursorPosPrevLine.x = window.DC.CursorPos.x window.DC.CursorPosPrevLine.y = window.DC.CursorPos.y + table_.RowCellPaddingY -- This allows users to call SameLine() to share LineSize between columns. - window.DC.PrevLineSize.x = 0.0; window.DC.PrevLineSize.y = 0.0 + window.DC.PrevLineSize.x = 0.0; window.DC.PrevLineSize.y = 0.0 -- This allows users to call SameLine() to share LineSize between columns, and to call it from first column too. window.DC.CurrLineSize.x = 0.0; window.DC.CurrLineSize.y = 0.0 window.DC.IsSameLine = false; window.DC.IsSetPos = false window.DC.CursorMaxPos.y = next_y1 @@ -46142,7 +51680,8 @@ function ImGui.TableEndRow(table_) ImGui.LogRenderedText(nil, "|") end - -- Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. + -- Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is + -- likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding. window.DC.CursorPos.y = table_.RowPosY2 -- Row background fill @@ -46210,6 +51749,7 @@ function ImGui.TableEndRow(table_) for cell_n = 0, table_.RowCellDataCurrent do local cell_data = table_.RowCellData[cell_n] -- As we render the BG here we need to clip things (for layout we would not) + -- FIXME: This cancels the OuterPadding addition done by TableGetCellBgRect(), need to keep it while rendering correctly while scrolling. local column = table_.Columns[cell_data.Column] local cell_bg_rect = ImGui.TableGetCellBgRect(table_, cell_data.Column) cell_bg_rect:ClipWith(table_.BgClipRect) @@ -46233,6 +51773,8 @@ function ImGui.TableEndRow(table_) end -- End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) + -- - We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark + -- end of row and get the new cursor position. if unfreeze_rows_request then IM_ASSERT(table_.FreezeRowsRequest > 0) for column_n = 0, table_.ColumnsCount - 1 do @@ -46245,7 +51787,7 @@ function ImGui.TableEndRow(table_) IM_ASSERT(table_.IsUnfrozenRows == false) table_.IsUnfrozenRows = true - -- BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect + -- BgClipRect starts as table.InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect local min_y = ImMin(y0, table_.InnerClipRect.Max.y) table_.BgClipRect.Min.y = min_y; table_.Bg2ClipRectForDrawCmd.Min.y = min_y table_.BgClipRect.Max.y = table_.InnerClipRect.Max.y; table_.Bg2ClipRectForDrawCmd.Max.y = table_.InnerClipRect.Max.y @@ -46262,7 +51804,7 @@ function ImGui.TableEndRow(table_) column.ClipRect.Min.y = table_.Bg2ClipRectForDrawCmd.Min.y end - -- Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y + -- Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect.Min.y ImGui.SetWindowClipRectBeforeSetChannel(window, table_.Columns[0].ClipRect) table_.DrawSplitter:SetCurrentChannel(window.DrawList, table_.Columns[0].DrawChannelCurrent) end @@ -46274,9 +51816,15 @@ function ImGui.TableEndRow(table_) table_.IsInsideRow = false end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Columns changes ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetColumnIndex() +-- - TableSetColumnIndex() +-- - TableNextColumn() +-- - TableBeginCell() [Internal] +-- - TableEndCell() [Internal] +------------------------------------------------------------------------------- function ImGui.TableGetColumnIndex() local g = GImGui @@ -46336,6 +51884,7 @@ end -- [Internal] Called by TableSetColumnIndex()/TableNextColumn() -- This is called very frequently, so we need to be mindful of unnecessary overhead. +-- FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns. function ImGui.TableBeginCell(table_, column_n) local g = GImGui local column = table_.Columns[column_n] @@ -46345,7 +51894,7 @@ function ImGui.TableBeginCell(table_, column_n) -- Start position is roughly ~~ CellRect.Min + CellPadding + Indent local start_x = column.WorkMinX if band(column.Flags, ImGuiTableColumnFlags.IndentEnable) ~= 0 then - start_x = start_x + table_.RowIndentOffsetX -- ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row. + start_x = start_x + table_.RowIndentOffsetX -- ~~ += window.DC.Indent.x - table.HostIndentX, except we locked it for the row. end window.DC.CursorPos.x = start_x @@ -46372,6 +51921,7 @@ function ImGui.TableBeginCell(table_, column_n) if band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0 then -- FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed. table_.DrawSplitter:SetCurrentChannel(window.DrawList, TABLE_DRAW_CHANNEL_NOCLIP) + --IM_ASSERT(table.DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP) else -- FIXME-TABLE: Could avoid this if draw channel is dummy channel? ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect) @@ -46409,27 +51959,43 @@ function ImGui.TableEndCell(table_) column.ItemWidth = window.DC.ItemWidth -- Propagate text baseline for the entire row + -- FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one. table_.RowTextBaseline = ImMax(table_.RowTextBaseline, window.DC.PrevLineTextBaseOffset) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Columns width management ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetMaxColumnWidth() [Internal] +-- - TableGetColumnWidthAuto() [Internal] +-- - TableSetColumnWidth() +-- - TableSetColumnWidthAutoSingle() [Internal] +-- - TableSetColumnWidthAutoAll() [Internal] +-- - TableUpdateColumnsWeightFromWidth() [Internal] +------------------------------------------------------------------------------- +-- Note that actual columns widths are computed in TableUpdateLayout(). +------------------------------------------------------------------------------- --- Maximum column content width given current layout. Use column->MinX so this value differs on a per-column basis. +-- Maximum column content width given current layout. Use column.MinX so this value differs on a per-column basis. function ImGui.TableCalcMaxColumnWidth(table_, column_n) local column = table_.Columns[column_n] local max_width = FLT_MAX local min_column_distance = table_.MinColumnWidth + table_.CellPaddingX * 2.0 + table_.CellSpacingX1 + table_.CellSpacingX2 if band(table_.Flags, ImGuiTableFlags.ScrollX) ~= 0 then -- Frozen columns can't reach beyond visible width else scrolling will naturally break. + -- (we use DisplayOrder as within a set of multiple frozen column reordering is possible) if column.DisplayOrder < table_.FreezeColumnsRequest then max_width = (table_.InnerClipRect.Max.x - (table_.FreezeColumnsRequest - column.DisplayOrder) * min_column_distance) - column.MinX max_width = max_width - table_.OuterPaddingX - table_.CellPaddingX - table_.CellSpacingX2 end elseif band(table_.Flags, ImGuiTableFlags.NoKeepColumnsVisible) == 0 then - -- If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make sure they are all visible. + -- If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make + -- sure they are all visible. Because of this we also know that all of the columns will always fit in + -- table.WorkRect and therefore in table.InnerRect (because ScrollX is off) + -- FIXME-TABLE: This is solved incorrectly but also quite a difficult problem to fix as we also want ClipRect width to match. + -- See "table_width_distrib" and "table_width_keep_visible" tests max_width = table_.WorkRect.Max.x - (table_.ColumnsEnabledCount - column.IndexWithinEnabledSet - 1) * min_column_distance - column.MinX + --max_width = max_width - table.CellSpacingX1 max_width = max_width - table_.CellSpacingX2 max_width = max_width - table_.CellPaddingX * 2.0 max_width = max_width - table_.OuterPaddingX @@ -46437,7 +52003,7 @@ function ImGui.TableCalcMaxColumnWidth(table_, column_n) return max_width end --- Note this is meant to be stored in column->WidthAuto, please generally use the WidthAuto field +-- Note this is meant to be stored in column.WidthAuto, please generally use the WidthAuto field function ImGui.TableGetColumnWidthAuto(table_, column) local content_width_body = ImMax(column.ContentMaxXFrozen, column.ContentMaxXUnfrozen) - column.WorkMinX local content_width_headers = column.ContentMaxXHeadersIdeal - column.WorkMinX @@ -46466,6 +52032,7 @@ function ImGui.TableSetColumnWidth(column_n, width) local column_0_width = width -- Apply constraints early + -- Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded) IM_ASSERT(table_.MinColumnWidth > 0.0) local min_width = table_.MinColumnWidth local max_width = ImMax(min_width, column_0.WidthMax) -- Don't use TableCalcMaxColumnWidth() here as it would rely on MinX from last instance (#7933) @@ -46474,8 +52041,41 @@ function ImGui.TableSetColumnWidth(column_n, width) return end + --IMGUI_DEBUG_PRINT("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0.WidthGiven, column_0_width) local column_1 = (column_0.NextEnabledColumn ~= -1) and table_.Columns[column_0.NextEnabledColumn] or nil + -- In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns. + -- - All fixed: easy. + -- - All stretch: easy. + -- - One or more fixed + one stretch: easy. + -- - One or more fixed + more than one stretch: tricky. + -- Qt when manual resize is enabled only supports a single _trailing_ stretch column, we support more cases here. + + -- When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1. + -- FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user. + -- Scenarios: + -- - F1 F2 F3 resize from F1| or F2| --> ok: alter .WidthRequested of Fixed column. Subsequent columns will be offset. + -- - F1 F2 F3 resize from F3| --> ok: alter .WidthRequested of Fixed column. If active, ScrollX extent can be altered. + -- - F1 F2 W3 resize from F1| or F2| --> ok: alter .WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size. + -- - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 W2 W3 resize from W1| or W2| --> ok + -- - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 W2 F3 resize from W1| or W2| --> ok + -- - W1 F2 W3 resize from W1| or F2| --> ok + -- - F1 W2 F3 resize from W2| --> ok + -- - F1 W3 F2 resize from W3| --> ok + -- - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move. + -- - W1 F2 F3 resize from F2| --> ok + -- All resizes from a Wx columns are locking other columns. + + -- Possible improvements: + -- - W1 W2 W3 resize W1| --> to not be stuck, both W2 and W3 would stretch down. Seems possible to fix. Would be most beneficial to simplify resize of all-weighted columns. + -- - W3 F1 F2 resize W3| --> to not be stuck past F1|, both F1 and F2 would need to stretch down, which would be lossy or ambiguous. Seems hard to fix. + + -- [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout(). + -- If we have all Fixed columns OR resizing a Fixed column that doesn't come after a Stretch one, we can do an offsetting resize. -- This is the preferred resize path if band(column_0.Flags, ImGuiTableColumnFlags.WidthFixed) ~= 0 then @@ -46508,6 +52108,7 @@ function ImGui.TableSetColumnWidth(column_n, width) end -- Disable clipping then auto-fit, will take 2 frames +-- (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns) function ImGui.TableSetColumnWidthAutoSingle(table_, column_n) -- Single auto width uses auto-fit local column = table_.Columns[column_n] @@ -46554,11 +52155,24 @@ function ImGui.TableUpdateColumnsWeightFromWidth(table_) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Drawing ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TablePushBackgroundChannel() [Internal] +-- - TablePopBackgroundChannel() [Internal] +-- - TableSetupDrawChannels() [Internal] +-- - TableMergeDrawChannels() [Internal] +-- - TableGetColumnBorderCol() [Internal] +-- - TableDrawBorders() [Internal] +------------------------------------------------------------------------------- + + +-- FIXME: This could be abstracted and merged with PushColumnsBackground(), by creating a generic struct +-- with storage for backup cliprect + backup channel + storage for splitter pointer, new clip rect. +-- This would slightly simplify caller code. -- Bg2 is used by Selectable (and possibly other widgets) to render to the background. +-- Unlike our Bg0/1 channel which we uses for RowBg/CellBg/Borders and where we guarantee all shapes to be CPU-clipped, the Bg2 channel being widgets-facing will rely on regular ClipRect. function ImGui.TablePushBackgroundChannel() local g = GImGui local window = g.CurrentWindow @@ -46610,6 +52224,21 @@ function ImGui.TablePopColumnChannel() end -- Allocate draw channels. Called by TableUpdateLayout() +-- - We allocate them following storage order instead of display order so reordering columns won't needlessly +-- increase overall dormant memory cost. +-- - We isolate headers draw commands in their own channels instead of just altering clip rects. +-- This is in order to facilitate merging of draw commands. +-- - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels. +-- - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other +-- channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged. +-- - We allocate 1 or 2 background draw channels. This is because we know TablePushBackgroundChannel() is only used for +-- horizontal spanning. If we allowed vertical spanning we'd need one background draw channel per merge group (1-4). +-- Draw channel allocation (before merging): +-- - NoClip --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call) +-- - Clip --> 2+D+N channels +-- - FreezeRows --> 2+D+N*2 (unless scrolling value is zero) +-- - FreezeRows || FreezeColumns --> 3+D+N*2 (unless scrolling value is zero) +-- Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0. function ImGui.TableSetupDrawChannels(table_) local freeze_row_multiplier = (table_.FreezeRowsCount > 0) and 2 or 1 local channels_for_row = (band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0) and 1 or table_.ColumnsEnabledCount @@ -46645,6 +52274,8 @@ function ImGui.TableSetupDrawChannels(table_) end -- Initial draw cmd starts with a BgClipRect that matches the one of its host, to facilitate merge draw commands by default. + -- All our cell highlight are manually clipped with BgClipRect. When unfreezing it will be made smaller to fit scrolling rect. + -- (This technically isn't part of setting up draw channels, but is reasonably related to be done here) ImRect_Copy(table_.BgClipRect, table_.InnerClipRect) ImRect_Copy(table_.Bg0ClipRectForDrawCmd, table_.OuterWindow.ClipRect) ImRect_Copy(table_.Bg2ClipRectForDrawCmd, table_.HostClipRect) @@ -46652,6 +52283,34 @@ function ImGui.TableSetupDrawChannels(table_) end -- This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable(). +-- For simplicity we call it TableMergeDrawChannels() but in fact it only reorder channels + overwrite ClipRect, +-- actual merging is done by table.DrawSplitter:Merge() which is called right after TableMergeDrawChannels(). +-- +-- Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve +-- this we merge their clip rect and make them contiguous in the channel list, so they can be merged +-- by the call to DrawSplitter:Merge() following to the call to this function. +-- We reorder draw commands by arranging them into a maximum of 4 distinct groups: +-- +-- 1 group: 2 groups: 2 groups: 4 groups: +-- [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze +-- [ .. ] or no scroll [ 2. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll +-- +-- Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled). +-- When the contents of a column didn't stray off its limit, we move its channels into the corresponding group +-- based on its position (within frozen rows/columns groups or not). +-- At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect. +-- This function assume that each column are pointing to a distinct draw channel, +-- otherwise merge_group.ChannelsCount will not match set bit count of merge_group.ChannelsMask. +-- +-- Column channels will not be merged into one of the 1-4 groups in the following cases: +-- - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value). +-- Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui.* bounds +-- matches, by e.g. calling SetCursorScreenPos(). +-- - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here.. +-- we could do better but it's going to be rare and probably not worth the hassle. +-- Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. +-- +-- This function is particularly tricky to understand.. take a breath. -- (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets) function ImGui.TableMergeDrawChannels(table_) local splitter = table_.DrawSplitter @@ -46690,6 +52349,7 @@ function ImGui.TableMergeDrawChannels(table_) end -- Find out the width of this merge group and check if it will fit in our column + -- (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it) if band(column.Flags, ImGuiTableColumnFlags.NoClip) == 0 then local content_max_x if not has_freeze_v then @@ -46719,6 +52379,7 @@ function ImGui.TableMergeDrawChannels(table_) end -- Invalidate current draw channel + -- (we don't clear DrawChannelFrozen/DrawChannelUnfrozen solely to facilitate debugging/later inspection of data) column.DrawChannelCurrent = -1 end end @@ -46734,6 +52395,7 @@ function ImGui.TableMergeDrawChannels(table_) remaining_mask[table_.Bg2DrawChannelUnfrozen] = nil IM_ASSERT(has_freeze_v == false or table_.Bg2DrawChannelUnfrozen ~= TABLE_DRAW_CHANNEL_BG2_FROZEN) local remaining_count = splitter._Count - (has_freeze_v and (LEADING_DRAW_CHANNELS + 1) or LEADING_DRAW_CHANNELS) + --local host_rect = (table.InnerWindow == table.OuterWindow) and table.InnerClipRect or table.HostClipRect local host_rect = table_.HostClipRect for merge_group_n = 0, 3 do local merge_channels_count = merge_groups[merge_group_n].ChannelsCount @@ -46743,6 +52405,11 @@ function ImGui.TableMergeDrawChannels(table_) -- Extend outer-most clip limits to match those of host, so draw calls can be merged even if -- outer-most columns have some outer padding offsetting them from their parent ClipRect. + -- The principal cases this is dealing with are: + -- - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge + -- - Columns can use padding and have left-most ClipRect.Min.x and right-most ClipRect.Max.x != from host ClipRect -> will extend and match host ClipRect -> will merge + -- FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit + -- within host clip rect, solely because of the half-padding difference between window.WorkRect and window.InnerClipRect. if band(merge_group_n, 1) == 0 or not has_freeze_h then merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x) end @@ -46755,6 +52422,9 @@ function ImGui.TableMergeDrawChannels(table_) if band(merge_group_n, 2) ~= 0 and band(table_.Flags, ImGuiTableFlags.NoHostExtendY) == 0 then merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y) end + --ImGui.GetForegroundDrawList():AddRect(merge_group.ClipRect.Min, merge_group.ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0, 0, 1.0) -- [DEBUG] + --ImGui.GetForegroundDrawList():AddLine(merge_group.ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200)) + --ImGui.GetForegroundDrawList():AddLine(merge_group.ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200)) remaining_count = remaining_count - merge_group.ChannelsCount for n in pairs(merge_group.ChannelsMask) do remaining_mask[n] = nil @@ -46871,7 +52541,13 @@ function ImGui.TableDrawBorders(table_) end -- Draw outer border + -- FIXME: could use AddRect or explicit VLine/HLine helper? if band(table_.Flags, ImGuiTableFlags.BordersOuter) ~= 0 then + -- Display outer border offset by 1 which is a simple way to display it without adding an extra draw call + -- (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their + -- parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part + -- of it in inner window, and the part that's over scrollbars in the outer window..) + -- Either solution currently won't allow us to use a larger border size: the border would clipped. local outer_border = table_.OuterRect local outer_col = table_.BorderColorStrong if band(table_.Flags, ImGuiTableFlags.BordersOuter) == ImGuiTableFlags.BordersOuter then @@ -46896,12 +52572,23 @@ function ImGui.TableDrawBorders(table_) inner_drawlist:PopClipRect() end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Sorting ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetSortSpecs() +-- - TableFixColumnSortDirection() [Internal] +-- - TableGetColumnNextSortDirection() [Internal] +-- - TableSetColumnSortDirection() [Internal] +-- - TableSortSpecsSanitize() [Internal] +-- - TableSortSpecsBuild() [Internal] +------------------------------------------------------------------------------- --- Return nil if no sort specs (most often when ImGuiTableFlags_Sortable is not set) --- When 'sort_specs.SpecsDirty == true' you should sort your data. Specs is a 1-based Lua array. +-- Return nil if no sort specs (most often when ImGuiTableFlags.Sortable is not set) +-- When 'sort_specs.SpecsDirty == true' you should sort your data. It will be true when sorting specs have +-- changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, +-- else you may wastefully sort your data every frame! +-- Lifetime: don't hold on this table over multiple frames or past any subsequent call to BeginTable()! +-- PORT: Specs is a 1-based Lua array. function ImGui.TableGetSortSpecs() local g = GImGui local table_ = g.CurrentTable @@ -46933,6 +52620,8 @@ function ImGui.TableFixColumnSortDirection(table_, column) end -- Calculate next sort direction that would be set after clicking the column +-- - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click. +-- - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op. function ImGui.TableGetColumnNextSortDirection(column) IM_ASSERT(column.SortDirectionsAvailCount > 0) if column.SortOrder == -1 then @@ -47016,6 +52705,7 @@ function ImGui.TableSortSpecsSanitize(table_) local fixed_mask = {} for sort_n = 0, sort_order_count - 1 do -- Fix: Rewrite sort order fields if needed so they have no gap or duplicate. + -- (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1) local column_with_smallest_sort_order = -1 for column_n = 0, table_.ColumnsCount - 1 do if not fixed_mask[column_n] and table_.Columns[column_n].SortOrder ~= -1 then @@ -47028,7 +52718,7 @@ function ImGui.TableSortSpecsSanitize(table_) fixed_mask[column_with_smallest_sort_order] = true table_.Columns[column_with_smallest_sort_order].SortOrder = sort_n - -- Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set. + -- Fix: Make sure only one column has a SortOrder if ImGuiTableFlags.MultiSortable is not set. if need_fix_single_sort_order then sort_order_count = 1 for column_n = 0, table_.ColumnsCount - 1 do @@ -47041,7 +52731,7 @@ function ImGui.TableSortSpecsSanitize(table_) end end - -- Fallback default sort order (if no column with the ImGuiTableColumnFlags_DefaultSort flag) + -- Fallback default sort order (if no column with the ImGuiTableColumnFlags.DefaultSort flag) if sort_order_count == 0 and band(table_.Flags, ImGuiTableFlags.SortTristate) == 0 then for column_n = 0, table_.ColumnsCount - 1 do local column = table_.Columns[column_n] @@ -47070,6 +52760,7 @@ function ImGui.TableSortSpecsBuild(table_) end -- Write output + -- May be able to move all SortSpecs data from table (48 bytes) to ImGuiTableTempData if we decide to write it back on every BeginTable() local sort_specs if table_.SortSpecsCount == 0 then sort_specs = nil @@ -47097,12 +52788,22 @@ function ImGui.TableSortSpecsBuild(table_) table_.SortSpecs.SpecsCount = table_.SortSpecsCount end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Headers ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetHeaderRowHeight() [Internal] +-- - TableGetHeaderAngledMaxLabelWidth() [Internal] +-- - TableHeadersRow() +-- - TableHeader() +-- - TableAngledHeadersRow() +-- - TableAngledHeadersRowEx() [Internal] +------------------------------------------------------------------------------- function ImGui.TableGetHeaderRowHeight() + -- Caring for a minor edge case: -- Calculate row height, for the unlikely case that some labels may be taller than others. + -- If we didn't do that, uneven header height would highlight but smaller one before the tallest wouldn't catch input for all height. + -- In your custom header row you may omit this all together and just call TableNextRow() without a height... local g = GImGui local table_ = g.CurrentTable local row_height = g.FontSize @@ -47131,6 +52832,12 @@ function ImGui.TableGetHeaderAngledMaxLabelWidth() end -- [Public] This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). +-- The intent is that advanced users willing to create customized headers would not need to use this helper +-- and can create their own! For example: TableHeader() may be preceded by Checkbox() or other custom widgets. +-- See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this. +-- This code is intentionally written to not make much use of internal functions, to give you better direction +-- if you need to write your own. +-- FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public. function ImGui.TableHeadersRow() local g = GImGui local table_ = g.CurrentTable @@ -47172,6 +52879,7 @@ end -- Emit a column header (text + optional sort order) -- We cpu-clip text here so that all columns headers can be merged into a same draw call. +-- Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader() function ImGui.TableHeader(label) local g = GImGui local window = g.CurrentWindow @@ -47194,6 +52902,7 @@ function ImGui.TableHeader(label) local label_pos = V2(window.DC.CursorPos) -- If we already got a row height, there's use that. + -- FIXME-TABLE: Padding problem if the correct outer-padding CellBgRect strays off our ClipRect? local cell_r = ImGui.TableGetCellBgRect(table_, column_n) local label_height = ImMax(label_size.y, table_.RowMinHeight - table_.RowCellPaddingY * 2.0) @@ -47227,11 +52936,15 @@ function ImGui.TableHeader(label) return end + --GetForegroundDrawList():AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)) -- [DEBUG] + --GetForegroundDrawList():AddRect(bb.Min, bb.Max, IM_COL32(255, 0, 0, 255)) -- [DEBUG] + -- Using AllowOverlap mode because we cover the whole cell, and we want user to be able to submit subsequent items. local highlight = (table_.HighlightColumnHeader == column_n) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, ImGuiButtonFlags.AllowOverlap) if held or hovered or highlight then local col = ImGui.GetColorU32(held and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header)) + --RenderFrame(bb.Min, bb.Max, col, false, 0.0) ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, col, table_.CurrentColumn) else -- Submit single cell bg color in the case we didn't submit a full header row @@ -47246,7 +52959,14 @@ function ImGui.TableHeader(label) window.DC.CursorPos.y = window.DC.CursorPos.y - g.Style.ItemSpacing.y * 0.5 -- Drag and drop to re-order columns. + -- FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone. if held and band(table_.Flags, ImGuiTableFlags.Reorderable) ~= 0 and ImGui.IsMouseDragging(0) and not g.DragDropActive then + -- - While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x + -- - We need to handle reordering across hidden columns. + -- In the configuration below, moving C to the right of E will lead to: + -- ... C [D] E ---> ... [D] E C (Column name/index) + -- ... 2 3 4 ... 2 3 4 (Display order) + -- - The other constraints are enforced by TableQueueSetColumnDisplayOrder() which might early out. table_.InstanceInteracted = table_.InstanceCurrent if g.IO.MouseDelta.x < 0.0 and g.IO.MousePos.x < cell_r.Min.x then local prev_column = (column.PrevEnabledColumn ~= -1) and table_.Columns[column.PrevEnabledColumn] or nil @@ -47263,6 +52983,8 @@ function ImGui.TableHeader(label) end -- Sort order arrow + -- - Only clip label for a visible arrow. Auto-fit still accounts for a possible arrow, but when + -- manually sized smaller we don't clip the label for the sake of an arrow that isn't displayed. local ellipsis_max = ImMax(cell_r.Max.x - (sort_arrow and (w_arrow + w_sort_text) or 0.0), label_pos.x) if band(table_.Flags, ImGuiTableFlags.Sortable) ~= 0 and band(column.Flags, ImGuiTableColumnFlags.NoSort) == 0 then if column.SortOrder ~= -1 then @@ -47286,6 +53008,7 @@ function ImGui.TableHeader(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) ImGui.RenderTextEllipsis(window.DrawList, label_pos, ImVec2(ellipsis_max, bb.Max.y), ellipsis_max, label, label_end, label_size) local text_clipped = label_size.x > (ellipsis_max - label_pos.x) @@ -47300,6 +53023,7 @@ function ImGui.TableHeader(label) end -- Unlike TableHeadersRow() it is not expected that you can reimplement or customize this with custom widgets. +-- FIXME: No hit-testing/button on the angled header. function ImGui.TableAngledHeadersRow() local g = GImGui local table_ = g.CurrentTable @@ -47323,7 +53047,7 @@ function ImGui.TableAngledHeadersRow() if BitTest(table_.EnabledMaskByDisplayOrder, order_n) then local column_n = table_.DisplayOrderToIndex[order_n] local column = table_.Columns[column_n] - if band(column.Flags, ImGuiTableColumnFlags.AngledHeader) ~= 0 then -- Note: can't rely on ImGuiTableColumnFlags_IsVisible test here. + if band(column.Flags, ImGuiTableColumnFlags.AngledHeader) ~= 0 then -- Note: can't rely on ImGuiTableColumnFlags.IsVisible test here. temp_data.AngledHeadersRequests:push_back({ Index = column_n, TextColor = col_text, BgColor0 = col_header_bg, BgColor1 = (column_n == highlight_column_n) and ImGui.GetColorU32(ImGuiCol.Header) or 0 }) end end @@ -47369,6 +53093,7 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat local unit_right = ImVec2(cos_a, sin_a) -- Calculate our base metrics and set angled headers data _before_ the first call to TableNextRow() + -- FIXME-STYLE: Would it be better for user to submit 'max_label_width' or 'row_height' ? One can be derived from the other. local header_height = g.FontSize + g.Style.CellPadding.x * 2.0 local row_height = ImTrunc(ImAbs(ImRotate(ImVec2(max_label_width, flip_label and header_height or -header_height), cos_a, sin_a).y)) table_.AngledHeadersHeight = row_height @@ -47376,6 +53101,7 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat local header_angled_vector = unit_right * (row_height / -sin_a) -- vector from bottom-left to top-left, and from bottom-right to top-right -- Declare row, override and draw our own background + -- FIXME-TABLE: Generally broken when overlapping frozen columns limit. ImGui.TableNextRow(ImGuiTableRowFlags.Headers, row_height) ImGui.TableNextColumn() local row_r = ImRect(table_.WorkRect.Min.x, table_.BgClipRect.Min.y, table_.WorkRect.Max.x, table_.RowPosY2) @@ -47417,6 +53143,8 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat max_x = ImMax(max_x, bg_shape[3].x) -- Draw label + -- - First draw at an offset where RenderTextXXX() function won't meddle with applying current ClipRect, then transform to final offset. + -- - Handle multiple lines manually, as we want each lines to follow on the horizontal border, rather than see a whole block rotated. local label_name = ImGui.TableGetColumnName(table_, column_n) local label_name_end = ImGui.FindRenderedTextEnd(label_name) local line_off_step_x = (g.FontSize / -sin_a) @@ -47464,6 +53192,7 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat end pivot_out.x = pivot_out.x + (flip_label and (line_off_curr_x + line_off_step_x) or line_off_curr_x) ImGui.ShadeVertsTransformPos(draw_list, vtx_idx_begin, vtx_idx_end, pivot_in, label_cos_a, label_sin_a, pivot_out) -- Rotate and offset + --if g.IO.KeyShift then local fg_dl = GetForegroundDrawList(); vtx_idx_begin = fg_dl._VtxCurrentIdx; fg_dl:AddRect(clip_r.Min, clip_r.Max, IM_COL32(0, 255, 0, 255), 0.0, 0, 1.0); ShadeVertsTransformPos(fg_dl, vtx_idx_begin, fg_dl._VtxCurrentIdx, pivot_in, label_cos_a, label_sin_a, pivot_out) end p = label_name_eol + 1 end @@ -47480,9 +53209,13 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat table_.TempData.AngledHeadersExtraWidth = ImMax(0.0, max_x - table_.Columns[table_.RightMostEnabledColumn].MaxX) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Context Menu ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableOpenContextMenu() [Internal] +-- - TableBeginContextMenuPopup() [Internal] +-- - TableDrawDefaultContextMenu() [Internal] +------------------------------------------------------------------------------- -- Use -1 to open menu not specific to a given column. function ImGui.TableOpenContextMenu(column_n) @@ -47536,8 +53269,8 @@ local function MenuItemForColumnReorder(label, selected, enabled) end local has_been_moved = (g.ActiveId == id) and g.ActiveIdHasBeenEditedBefore -- But disable toggling once moved. - ImGui.BeginDisabled(not enabled) -- Don't use ImGuiSelectableFlags_Disabled so that Check mark is also affected. - local ret = ImGui.Selectable(label, false, selectable_flags, ImVec2(min_w, label_size.y)) and not has_been_moved + ImGui.BeginDisabled(not enabled) -- Don't use ImGuiSelectableFlags.Disabled so that Check mark is also affected. + local ret = ImGui.Selectable(label, false, selectable_flags, ImVec2(min_w, label_size.y)) and not has_been_moved -- Can't use IsMouseDragging(0) as button is released already. if band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 and selected then ImGui.RenderCheckMark(window.DrawList, text_pos + ImVec2(offsets.OffsetMark + stretch_w + g.FontSize * 0.40, g.FontSize * 0.134 * 0.5), ImGui.GetColorU32(ImGuiCol.Text), g.FontSize * 0.866) end @@ -47547,6 +53280,13 @@ local function MenuItemForColumnReorder(label, selected, enabled) end -- Output context menu into current window (generally a popup) +-- FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data? +-- Sections to display are pulled from 'flags_for_section_to_display', which is typically == table.Flags. +-- - ImGuiTableFlags.Resizable -> display Sizing menu items +-- - ImGuiTableFlags.Reorderable -> display "Reset Order" +---- ImGuiTableFlags.Sortable -> display sorting options (disabled) +-- - ImGuiTableFlags.Hideable -> display columns visibility menu items +-- It means if you have a custom context menus you can call this section and omit some sections, and add your own. function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) local g = GImGui local window = g.CurrentWindow @@ -47582,6 +53322,9 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) -- Reset Order/Visibility etc. if band(flags_for_section_to_display, bor(ImGuiTableFlags.Reorderable, ImGuiTableFlags.Hideable)) ~= 0 then if ImGui.BeginMenu(ImGui.LocalizeGetMsg(ImGuiLocKey.TableReset)) then + --if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.TableResetAll)) then -- FIXME: Hiding because altering Sort Order + requesting auto-fit simultaneously has a tendency to exhibit a sizing glitch. + -- table_.IsResetAllRequest = true + --end if band(flags_for_section_to_display, ImGuiTableFlags.Reorderable) ~= 0 then if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.TableResetOrder), nil, false, not table_.IsDefaultDisplayOrder) then -- PS: cannot be hidden because it would mess with drag reordering. table_.IsResetDisplayOrderRequest = true @@ -47596,6 +53339,22 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end end + -- Sorting + -- (modify TableOpenContextMenu() to add _Sortable flag if enabling this) + -- #if 0 + --if band(flags_for_section_to_display, ImGuiTableFlags.Sortable) ~= 0 and column ~= nil and band(column.Flags, ImGuiTableColumnFlags.NoSort) == 0 then + -- if want_separator then ImGui.Separator() end + -- want_separator = true + -- local append_to_sort_specs = g.IO.KeyShift + -- if ImGui.MenuItem("Sort in Ascending Order", nil, column.SortOrder ~= -1 and column.SortDirection == ImGuiSortDirection.Ascending, band(column.Flags, ImGuiTableColumnFlags.NoSortAscending) == 0) then + -- ImGui.TableSetColumnSortDirection(table_, column_n, ImGuiSortDirection.Ascending, append_to_sort_specs) + -- end + -- if ImGui.MenuItem("Sort in Descending Order", nil, column.SortOrder ~= -1 and column.SortDirection == ImGuiSortDirection.Descending, band(column.Flags, ImGuiTableColumnFlags.NoSortDescending) == 0) then + -- ImGui.TableSetColumnSortDirection(table_, column_n, ImGuiSortDirection.Descending, append_to_sort_specs) + -- end + --end + -- #endif + -- Hiding / Visibility if band(flags_for_section_to_display, ImGuiTableFlags.Hideable) ~= 0 then if want_separator then @@ -47603,7 +53362,8 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end want_separator = true - -- While reordering: we calculate min/max allowed range once here so we can avoid a O(N log N) in the loop. + -- While reordering: we calculate min/max allowed range once here so we can avoid a O(N log N) in the loop (because the query itself does a sweep scan). + -- This assume that reordering constraints output a single range, otherwise would need to either call TableGetMaxDisplayOrderAllowed() for each item below, or cache this once per frame into columns. local is_reordering = (g.ActiveId ~= 0 and g.ActiveIdWindow == g.CurrentWindow and table_.ReorderColumn ~= -1 and g.ActiveIdHasBeenEditedBefore) -- FIXME: This is a bit of a hack. local reorder_src_order = is_reordering and table_.Columns[table_.ReorderColumn].DisplayOrder or -1 local reorder_min_order = is_reordering and TableGetMaxDisplayOrderAllowed(table_, reorder_src_order, 0) or 0 @@ -47631,6 +53391,7 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end -- Drag to reorder + -- FIXME: It is currently not possible to reorder columns marked with ImGuiTableColumnFlags.NoHide. if ImGui.IsItemActive() and ImGui.IsMouseDragging(0) and g.ActiveIdSource == ImGuiInputSource.Mouse and band(table_.Flags, ImGuiTableFlags.Reorderable) ~= 0 then g.ActiveIdHasBeenEditedBefore = true -- Disable toggle in MenuItemForColumnReorder() + start dimming to display allowed reorder targets. table_.ReorderColumn = column_n @@ -47647,9 +53408,31 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Settings (.ini data) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- FIXME: The binding/finding/creating flow are too confusing. +------------------------------------------------------------------------------- +-- - TableSettingsInit() [Internal] +-- - TableSettingsCreate() [Internal] +-- - TableSettingsFindByID() [Internal] +-- - TableGetBoundSettings() [Internal] +-- - TableResetSettings() +-- - TableSaveSettings() [Internal] +-- - TableLoadSettings() [Internal] +-- - TableLoadSettingsForColumns() [Internal] +-- - TableSettingsHandler_ClearAll() [Internal] +-- - TableSettingsHandler_ApplyAll() [Internal] +-- - TableSettingsHandler_ReadOpen() [Internal] +-- - TableSettingsHandler_ReadLine() [Internal] +-- - TableSettingsHandler_WriteAll() [Internal] +-- - TableSettingsAddSettingsHandler() [Internal] +------------------------------------------------------------------------------- +-- [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings. +-- [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table. +-- [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty. +-- [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file. +------------------------------------------------------------------------------- -- Clear and initialize empty settings instance local function TableSettingsInit(settings, id, columns_count, columns_count_max) @@ -47681,6 +53464,7 @@ end -- Find existing settings function ImGui.TableSettingsFindByID(id) + -- FIXME-OPT: Might want to store a lookup map for this? local g = GImGui for _, settings in g.SettingsTables:iter() do if settings.ID == id then @@ -47695,7 +53479,7 @@ local function SettingsTablesOffsetFromPtr(settings) return g.SettingsTables:find_index(settings) or -1 end --- Get settings for a given table, NULL if none +-- Get settings for a given table, nil if none function ImGui.TableGetBoundSettings(table_) if table_.SettingsOffset == -1 then return nil @@ -47755,6 +53539,8 @@ function ImGui.TableSaveSettings(table_) end -- We skip saving some data in the .ini file when they are unnecessary to restore our state. + -- Note that fixed width where initial width was derived from auto-fit will always be saved as InitStretchWeightOrWidth will be 0.0f. + -- FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present. if width_or_weight ~= column.InitStretchWeightOrWidth then settings.SaveFlags = bor(settings.SaveFlags, ImGuiTableFlags.Resizable) end @@ -47899,7 +53685,8 @@ function ImGui.TableFixDisplayOrder(table_) for n = 0, table_.ColumnsCount - 1 do fdo_columns[n + 1] = n end - -- Sort by DisplayOrder and then Index. -1 (unsigned short 0xFFFF) always sorts after. + -- Sort by DisplayOrder and then Index + -- Assume ImGuiTableColumnIdx == signed short, to turn -1 into a large value so that it always sort after. local function key(idx) local o = table_.Columns[idx].DisplayOrder if o < 0 then o = o + 0x10000 end @@ -47941,6 +53728,9 @@ local function TableSettingsHandler_ApplyAll(ctx, handler) end local function TableSettingsHandler_ReadOpen(ctx, handler, name) + -- FIXME: As topology changes are allowed, strictly speaking a >= IMGUI_TABLE_MAX_COLUMNS tables stored in .ini file + -- that was emitted with a higher max count could still be meaningful in some unlikely cases. + -- We might want to use another MAX defined as (1<<(sizeof(ImGuiTableColumnIdx)*8-1))-1. local id, columns_count = string.match(name, "^0x(%x+),(%-?%d+)") if id == nil then return nil @@ -47996,6 +53786,8 @@ local function TableSettingsHandler_WriteAll(ctx, handler, buf) local g = ctx for _, settings in g.SettingsTables:iter() do if settings.ID ~= 0 then -- Skip ditched settings + -- TableSaveSettings() may clear some of those flags when we establish that the data can be stripped + -- (e.g. Order was unchanged) local save_size = band(settings.SaveFlags, ImGuiTableFlags.Resizable) ~= 0 local save_visible = band(settings.SaveFlags, ImGuiTableFlags.Hideable) ~= 0 local save_order = band(settings.SaveFlags, ImGuiTableFlags.Reorderable) ~= 0 @@ -48008,6 +53800,7 @@ local function TableSettingsHandler_WriteAll(ctx, handler, buf) end for column_n = 0, settings.ColumnsCount - 1 do local column = settings.Columns[column_n] + -- "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" local save_column = save_size or save_visible or save_order or (save_sort and column.SortOrder ~= -1) if save_column then buf:appendf("Column %-2d", column_n) @@ -48040,12 +53833,17 @@ function ImGui.TableSettingsAddSettingsHandler() ImGui.AddSettingsHandler(ini_handler) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Garbage Collection ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableRemove() [Internal] +-- - TableGcCompactTransientBuffers() [Internal] +-- - TableGcCompactSettings() [Internal] +------------------------------------------------------------------------------- -- Remove Table data (currently only used by TestEngine) function ImGui.TableRemove(table_) + --IMGUI_DEBUG_PRINT("TableRemove() id=0x%08X\n", table_.ID) local g = GImGui local table_idx = g.Tables:GetIndex(table_) g.Tables:Remove(table_.ID, table_) @@ -48062,6 +53860,7 @@ function ImGui.TableGcCompactTransientBuffers(t) t.LastTimeActive = -1.0 return end + --IMGUI_DEBUG_PRINT("TableGcCompactTransientBuffers() id=0x%08X\n", t.ID) local g = GImGui local table_ = t IM_ASSERT(table_.MemoryCompacted == false) @@ -48076,7 +53875,7 @@ function ImGui.TableGcCompactTransientBuffers(t) g.TablesLastTimeActive.Data[g.Tables:GetIndex(table_) + 1] = -1.0 end --- Compact and remove unused or resize settings data +-- Compact and remove unused or resize settings data (only TestEngine mark unused, but resizing table down can lead to compaction) function ImGui.TableGcCompactSettings() local g = GImGui local has_dead = false @@ -48094,10 +53893,28 @@ function ImGui.TableGcCompactSettings() ForEachTable(g, function(t) t.SettingsOffset = -1 end) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Columns, BeginColumns, EndColumns, etc. -- (This is a legacy API, prefer using BeginTable/EndTable!) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- FIXME: sizing is lossy when columns width is very small (default width may turn negative etc.) +------------------------------------------------------------------------------- +-- - GetColumnIndex() +-- - GetColumnsCount() +-- - GetColumnOffset() +-- - GetColumnWidth() +-- - SetColumnOffset() +-- - SetColumnWidth() +-- - PushColumnClipRect() [Internal] +-- - PushColumnsBackground() [Internal] +-- - PopColumnsBackground() [Internal] +-- - FindOrCreateColumns() [Internal] +-- - GetColumnsID() [Internal] +-- - BeginColumns() +-- - NextColumn() +-- - EndColumns() +-- - Columns() +------------------------------------------------------------------------------- -- (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1]) function ImGui.GetColumnIndex() @@ -48121,7 +53938,8 @@ end local COLUMNS_HIT_RECT_HALF_THICKNESS = 4.0 local function GetDraggedColumnOffset(columns, column_index) - -- Active (dragged) column always follow mouse. + -- Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + -- window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. local g = GImGui local window = g.CurrentWindow IM_ASSERT(column_index > 0) -- We are not supposed to drag column 0. @@ -48275,6 +54093,7 @@ function ImGui.GetColumnsID(str_id, columns_count) local window = ImGui.GetCurrentWindow() -- Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + -- In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. ImGui.PushID(0x11223347 + (str_id and 0 or columns_count)) local id = window:GetID(str_id or "columns") ImGui.PopID() @@ -48307,6 +54126,7 @@ function ImGui.BeginColumns(str_id, columns_count, flags) ImRect_Copy(window.ParentWorkRect, window.WorkRect) -- Set state for first column + -- We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect local column_padding = g.Style.ItemSpacing.x local half_clip_extend_x = ImTrunc(ImMax(window.WindowPadding.x * 0.5, window.WindowBorderSize)) local max_1 = window.WorkRect.Max.x + column_padding - ImMax(column_padding - window.WindowPadding.x, 0.0) @@ -48380,6 +54200,7 @@ function ImGui.NextColumn() ImGui.PopItemWidth() -- Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect() + -- (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), local column = columns.Columns.Data[columns.Current + 1] ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect) columns.Splitter:SetCurrentChannel(window.DrawList, columns.Current + 1) @@ -48388,6 +54209,7 @@ function ImGui.NextColumn() columns.LineMaxY = ImMax(columns.LineMaxY, window.DC.CursorPos.y) if columns.Current > 0 then -- Columns 1+ ignore IndentX (by canceling it out) + -- FIXME-COLUMNS: Unnecessary, could be locked? window.DC.ColumnsOffset.x = ImGui.GetColumnOffset(columns.Current) - window.DC.Indent.x + column_padding else -- New row/line: column 0 honor IndentX. @@ -48400,6 +54222,7 @@ function ImGui.NextColumn() window.DC.CurrLineSize.x = 0.0; window.DC.CurrLineSize.y = 0.0 window.DC.CurrLineTextBaseOffset = 0.0 + -- FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. local offset_0 = ImGui.GetColumnOffset(columns.Current) local offset_1 = ImGui.GetColumnOffset(columns.Current + 1) local width = offset_1 - offset_0 @@ -48427,6 +54250,7 @@ function ImGui.EndColumns() end -- Draw columns borders and handle resize + -- The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy local is_being_resized = false if band(flags, ImGuiOldColumnFlags.NoBorder) == 0 and not window.SkipItems then -- We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. @@ -48492,6 +54316,7 @@ function ImGui.Columns(columns_count, id, borders) IM_ASSERT(columns_count >= 1) local flags = borders and 0 or ImGuiOldColumnFlags.NoBorder + --flags = bor(flags, ImGuiOldColumnFlags.NoPreserveWidths) -- NB: Legacy behavior local columns = window.DC.CurrentColumns if columns ~= nil and columns.Count == columns_count and columns.Flags == flags then return @@ -48511,7 +54336,30 @@ end __FILES['imgui_widgets.lua'] = function() --- Dear ImGui WIP --- (Widgets Code) +-- (widgets code) + +-- +-- Index of this file: +-- +-- [SECTION] Widgets: Text, etc. +-- [SECTION] Widgets: Value helpers +-- [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.) +-- [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.) +-- [SECTION] Widgets: ComboBox +-- [SECTION] Data Type and Data Formatting Helpers +-- [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +-- [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +-- [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +-- [SECTION] Widgets: InputText, InputTextMultiline +-- [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +-- [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +-- [SECTION] Widgets: Selectable +-- [SECTION] Widgets: ListBox +-- [SECTION] Widgets: PlotLines, PlotHistogram +-- [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc. +-- [SECTION] Widgets: BeginTabBar, EndTabBar, etc. +-- [SECTION] Widgets: BeginTabItem, EndTabItem, etc. +-- --- @type ImGuiContext? local GImGui @@ -48523,8 +54371,13 @@ function ImGui._SetCurrentContext_Widgets(ctx) GImGui = ctx end -local DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70 -- Time for drag-hold to activate items accepting the ImGuiButtonFlags.PressedOnDragDropHold button behavior -local DRAG_MOUSE_THRESHOLD_FACTOR = 0.50 -- Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags +------------------------------------------------------------------------------- +-- Data +------------------------------------------------------------------------------- + +-- Widgets +local DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70 -- Time for drag-hold to activate items accepting the ImGuiButtonFlags.PressedOnDragDropHold button behavior. +local DRAG_MOUSE_THRESHOLD_FACTOR = 0.50 -- Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags. local IM_S8_MIN = -128 local IM_S8_MAX = 127 @@ -48534,14 +54387,25 @@ local IM_S16_MIN = -32768 local IM_S16_MAX = 32767 local IM_U16_MIN = 0 local IM_U16_MAX = 0xFFFF -local IM_S32_MIN = INT_MIN -local IM_S32_MAX = INT_MAX +local IM_S32_MIN = INT_MIN -- (-2147483647 - 1), (0x80000000); +local IM_S32_MAX = INT_MAX -- (2147483647), (0x7FFFFFFF) local IM_U32_MIN = 0 -local IM_U32_MAX = UINT_MAX +local IM_U32_MAX = UINT_MAX -- (0xFFFFFFFF) ----------------------------------------------------------------- --- [SECTION] TEXT ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Text, etc. +------------------------------------------------------------------------------- +-- - TextEx() [Internal] +-- - TextUnformatted() +-- - Text() +-- - TextV() +-- - TextColored() +-- - TextDisabled() +-- - TextWrapped() +-- - TextAligned() +-- - LabelText() +-- - BulletText() +------------------------------------------------------------------------------- --- @param text string --- @param text_end? int @@ -48556,11 +54420,13 @@ function ImGui.TextEx(text, text_end, flags) return end + -- Accept null ranges if not text or text == "" then text = "" text_end = 1 end + -- Calculate length if text_end == nil then text_end = #text + 1 end @@ -48569,6 +54435,7 @@ function ImGui.TextEx(text, text_end, flags) local wrap_pos_x = window.DC.TextWrapPos local wrap_enabled = (wrap_pos_x >= 0.0) if (text_end - 1 <= 2000) or wrap_enabled then + -- Common case local wrap_width = wrap_enabled and ImGui.CalcWrapWidthForPos(window.DC.CursorPos, wrap_pos_x) or 0.0 local text_size = ImGui.CalcTextSize(text, text_end, false, wrap_width) @@ -48578,12 +54445,18 @@ function ImGui.TextEx(text, text_end, flags) return end + -- Render (we don't hide text after ## in this end-user function) ImGui.RenderTextWrapped(bb.Min, text, text_end, wrap_width) else + -- Long text! + -- Perform manual coarse clipping to optimize for long multi-line text + -- - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. + -- - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. local line = 1 local line_height = ImGui.GetTextLineHeight() local text_size = ImVec2(0, 0) + -- Lines to skip (can't skip when logging text) local pos = ImVec2(text_pos.x, text_pos.y) if not g.LogEnabled then local lines_skippable = ImFloor((window.ClipRect.Min.y - text_pos.y) / line_height) @@ -48605,6 +54478,7 @@ function ImGui.TextEx(text, text_end, flags) end end + -- Lines to render if line < text_end then local line_rect = ImRect(pos, pos + ImVec2(FLT_MAX, line_height)) while line < text_end do @@ -48626,6 +54500,7 @@ function ImGui.TextEx(text, text_end, flags) pos.y = pos.y + line_height end + -- Count remaining lines local lines_skipped = 0 while line < text_end do local line_end = ImMemchr(text, "\n", line) @@ -48701,7 +54576,7 @@ end --- @param ... any function ImGui.TextWrapped(fmt, ...) local g = GImGui - local need_backup = (g.CurrentWindow.DC.TextWrapPos < 0.0) + local need_backup = (g.CurrentWindow.DC.TextWrapPos < 0.0) -- Keep existing wrap position if one is already set if need_backup then ImGui.PushTextWrapPos(0.0) end @@ -48712,8 +54587,8 @@ function ImGui.TextWrapped(fmt, ...) end -- 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) +-- size_x < 0.0f (e.g. -FLT_MIN): shortcut for GetContentRegionAvail().x +-- FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024, #9455) --- @param align_x float --- @param size_x float --- @param fmt string @@ -48743,7 +54618,7 @@ function ImGui.TextAligned(align_x, size_x, fmt, ...) ImVec2_Copy(backup_max_pos, window.DC.CursorMaxPos) ImGui.ItemSize(size) ImGui.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 + window.DC.CursorMaxPos.x = backup_max_pos.x -- Cancel out extending content to 'size' to use 'text_size' allowing auto-resize to function with align_x > 0.0f if size_x < text_size.x and ImGui.IsItemHovered(bit32.bor(ImGuiHoveredFlags.NoNavOverride, ImGuiHoveredFlags.AllowWhenDisabled, ImGuiHoveredFlags.ForTooltip)) then ImGui.SetTooltip("%.*s", text_end - 1, text) @@ -48786,6 +54661,7 @@ function ImGui.LabelText(label, fmt, ...) end end +-- Text with a little bullet aligned to the typical tree node. --- @param fmt string --- @param ... any function ImGui.BulletText(fmt, ...) @@ -48824,6 +54700,13 @@ ImGui.TextAlignedV = ImGui.TextAligned ImGui.LabelTextV = ImGui.LabelText ImGui.BulletTextV = ImGui.BulletText +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Value helpers +-- Those is not very useful, legacy API. +------------------------------------------------------------------------------- +-- - Value() +------------------------------------------------------------------------------- + -- Value(prefix, b) / Value(prefix, int) / Value(prefix, float, float_format) -- Lua can't tell int from float: integers without float_format print as %d, otherwise %.3f function ImGui.Value(prefix, v, float_format) @@ -48838,10 +54721,94 @@ function ImGui.Value(prefix, v, float_format) end end ----------------------------------------------------------------- --- [SECTION] MAIN: BUTTONS, SCROLLBARS, ... ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Main +------------------------------------------------------------------------------- +-- - ButtonBehavior() [Internal] +-- - Button() +-- - SmallButton() +-- - InvisibleButton() +-- - ArrowButton() +-- - CloseButton() [Internal] +-- - CollapseButton() [Internal] +-- - GetWindowScrollbarID() [Internal] +-- - GetWindowScrollbarRect() [Internal] +-- - Scrollbar() [Internal] +-- - ScrollbarEx() [Internal] +-- - Image() +-- - ImageButton() +-- - Checkbox() +-- - CheckboxFlagsT() [Internal] +-- - CheckboxFlags() +-- - RadioButton() +-- - ProgressBar() +-- - Bullet() +-- - Hyperlink() +------------------------------------------------------------------------------- +-- The ButtonBehavior() function is key to many interactions and used by many/most widgets. +-- Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags), +-- this code is a little complex. +-- By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags.PressedOnClickRelease button behavior. +-- See the series of events below and the corresponding state reported by dear imgui: +------------------------------------------------------------------------------- +-- with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+0 (mouse is outside bb) - - - - - - +-- Frame N+1 (mouse moves inside bb) - true - - - - +-- Frame N+2 (mouse button is down) - true true true - true +-- Frame N+3 (mouse button is down) - true true - - - +-- Frame N+4 (mouse moves outside bb) - - true - - - +-- Frame N+5 (mouse moves inside bb) - true true - - - +-- Frame N+6 (mouse button is released) true true - - true - +-- Frame N+7 (mouse button is released) - true - - - - +-- Frame N+8 (mouse moves outside bb) - - - - - - +------------------------------------------------------------------------------- +-- with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+2 (mouse button is down) true true true true - true +-- Frame N+3 (mouse button is down) - true true - - - +-- Frame N+6 (mouse button is released) - true - - true - +-- Frame N+7 (mouse button is released) - true - - - - +------------------------------------------------------------------------------- +-- with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+2 (mouse button is down) - true - - - true +-- Frame N+3 (mouse button is down) - true - - - - +-- Frame N+6 (mouse button is released) true true - - - - +-- Frame N+7 (mouse button is released) - true - - - - +------------------------------------------------------------------------------- +-- with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+0 (mouse button is down) - true - - - true +-- Frame N+1 (mouse button is down) - true - - - - +-- Frame N+2 (mouse button is released) - true - - - - +-- Frame N+3 (mouse button is released) - true - - - - +-- Frame N+4 (mouse button is down) true true true true - true +-- Frame N+5 (mouse button is down) - true true - - - +-- Frame N+6 (mouse button is released) - true - - true - +-- Frame N+7 (mouse button is released) - true - - - - +------------------------------------------------------------------------------- +-- Note that some combinations are supported, +-- - 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 ImGuiItemFlags.ButtonRepeat is set: +-- Repeat+ Repeat+ Repeat+ Repeat+ +-- PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick +------------------------------------------------------------------------------- +-- Frame N+0 (mouse button is down) - true - true +-- ... - - - - +-- Frame N + RepeatDelay true true - true +-- ... - - - - +-- Frame N + RepeatDelay + RepeatRate*N true true - true +------------------------------------------------------------------------------- + +-- - FIXME: For refactor we could output flags, incl mouse hovered vs nav keyboard vs nav triggered etc. +-- 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 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() +-- Returns (pressed, hovered, held). --- @param bb ImRect --- @param id ImGuiID --- @param flags? ImGuiButtonFlags @@ -48853,6 +54820,8 @@ function ImGui.ButtonBehavior(bb, id, flags) local window = g.CurrentWindow + -- 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. local item_flags = (g.LastItemData.ID == id) and g.LastItemData.ItemFlags or g.CurrentItemFlags if bit32.band(flags, ImGuiButtonFlags.AllowOverlap) ~= 0 then item_flags = bit32.bor(item_flags, ImGuiItemFlags.AllowOverlap) @@ -48879,6 +54848,9 @@ function ImGui.ButtonBehavior(bb, id, flags) local pressed = false local hovered = ImGui.ItemHoverable(bb, id, item_flags) + + -- 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 then if (bit32.band(flags, ImGuiButtonFlags.PressedOnDragDropHold) ~= 0) and (bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceNoHoldToOpenOthers) == 0) and ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) then hovered = true @@ -48900,10 +54872,14 @@ function ImGui.ButtonBehavior(bb, id, flags) g.HoveredWindow = backup_hovered_window end + -- Mouse handling local test_owner_id = (bit32.band(flags, ImGuiButtonFlags.NoTestKeyOwner) ~= 0) and ImGuiKeyOwner_Any or id if hovered then - IM_ASSERT(id ~= 0) + IM_ASSERT(id ~= 0) -- Lazily check inside rare path. + -- Poll mouse buttons + -- - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId. + -- - Technically we only need some values in one code path, but since this is gated by hovered test this is fine. local mouse_button_clicked = -1 local mouse_button_released = -1 for button = 0, 2 do @@ -48913,6 +54889,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end end + -- Process initial action local mods_ok = (bit32.band(flags, ImGuiButtonFlags.NoKeyModsAllowed) == 0) or (not g.IO.KeyCtrl and not g.IO.KeyShift and not g.IO.KeyAlt) if mods_ok then if mouse_button_clicked ~= -1 and g.ActiveId ~= id then @@ -48930,7 +54907,7 @@ function ImGui.ButtonBehavior(bb, id, flags) ImGui.SetFocusID(id, window) ImGui.FocusWindow(window) elseif bit32.band(flags, ImGuiButtonFlags.NoFocus) == 0 then - ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) + ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) -- Still need to focus and bring to front, but try to avoid losing NavId when navigating a child end end @@ -48940,7 +54917,7 @@ function ImGui.ButtonBehavior(bb, id, flags) if bit32.band(flags, ImGuiButtonFlags.NoHoldingActiveId) ~= 0 then ImGui.ClearActiveID() else - ImGui.SetActiveID(id, window) + ImGui.SetActiveID(id, window) -- Hold on ID end g.ActiveIdMouseButton = mouse_button_clicked @@ -48949,12 +54926,12 @@ function ImGui.ButtonBehavior(bb, id, flags) ImGui.SetFocusID(id, window) ImGui.FocusWindow(window) elseif bit32.band(flags, ImGuiButtonFlags.NoFocus) == 0 then - ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) + ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) -- Still need to focus and bring to front, but try to avoid losing NavId when navigating a child end end if bit32.band(flags, ImGuiButtonFlags.PressedOnRelease) ~= 0 then - -- FIXME: Traditionally ImGuiButtonFlags.PressedOnRelease never took ActiveId. Adding it in 2026-03-20 since ImGuiButtonFlags_NoHoldingActiveId can always be added. + -- FIXME: Traditionally ImGuiButtonFlags.PressedOnRelease never took ActiveId. Adding it in 2026-03-20 since ImGuiButtonFlags.NoHoldingActiveId can always be added. -- We don't yet perform an explicit ClearActiveID() to reduce scope of change, but this possibility could be investigated. if bit32.band(flags, ImGuiButtonFlags.NoHoldingActiveId) == 0 then ImGui.SetActiveID(id, window) -- Hold on ID @@ -48965,14 +54942,14 @@ function ImGui.ButtonBehavior(bb, id, flags) if bit32.band(flags, ImGuiButtonFlags.PressedOnRelease) ~= 0 then if mouse_button_released ~= -1 then - local has_repeated_at_least_once = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay + local has_repeated_at_least_once = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay -- Repeat mode trumps on release behavior if not has_repeated_at_least_once then pressed = true end if bit32.band(flags, ImGuiButtonFlags.NoNavFocus) == 0 then - ImGui.SetFocusID(id, window) -- FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why. + ImGui.SetFocusID(id, window) -- FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why. end ImGui.ClearActiveID() @@ -48994,7 +54971,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end -- Keyboard/Gamepad navigation handling - -- We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse + -- We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse. if bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then if g.NavId == id and g.NavCursorVisible and g.NavHighlightItemUnderNav then if bit32.band(flags, ImGuiButtonFlags.NoHoveredOnFocus) == 0 then @@ -49027,6 +55004,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end end + -- Process while held local held = false if g.ActiveId == id then if g.ActiveIdSource == ImGuiInputSource.Mouse then @@ -49048,7 +55026,7 @@ function ImGui.ButtonBehavior(bb, id, flags) -- Report as pressed when releasing the mouse (this is the most common path) local is_double_click_release = (bit32.band(flags, ImGuiButtonFlags.PressedOnDoubleClick) ~= 0) and g.IO.MouseReleased[mouse_button] and g.IO.MouseClickedLastCount[mouse_button] == 2 - local is_repeating_already = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay + local is_repeating_already = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay -- Repeat mode trumps local is_button_avail_or_owned = ImGui.TestKeyOwner(ImGui.MouseButtonToKey(mouse_button), test_owner_id) @@ -49066,7 +55044,7 @@ function ImGui.ButtonBehavior(bb, id, flags) elseif g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad then -- When activated using Nav, we hold on the ActiveID until activation button is released if g.NavActivateDownId == id then - held = true -- hovered == true not true as we are already likely hovered on direct activation. + held = true -- hovered == true not true as we are already likely hovered on direct activation. else ImGui.ClearActiveID() end @@ -49077,6 +55055,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end end + -- Activation highlight (this may be a remote activation) if g.NavHighlightActivatedId == id and (bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0) then hovered = true end @@ -49106,7 +55085,7 @@ function ImGui.ButtonEx(label, size_arg, flags) local pos = ImVec2() -- Don't modify the cursor! ImVec2_Copy(pos, window.DC.CursorPos) - if bit32.band(flags, ImGuiButtonFlags.AlignTextBaseLine) ~= 0 and style.FramePadding.y < window.DC.CurrLineTextBaseOffset then + if bit32.band(flags, ImGuiButtonFlags.AlignTextBaseLine) ~= 0 and style.FramePadding.y < window.DC.CurrLineTextBaseOffset then -- Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y = pos.y + window.DC.CurrLineTextBaseOffset - style.FramePadding.y end local size = ImGui.CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0, label_size.y + style.FramePadding.y * 2.0) @@ -49119,6 +55098,7 @@ function ImGui.ButtonEx(label, size_arg, flags) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, flags) + -- Render local col if held and hovered then col = ImGui.GetColorU32(ImGuiCol.ButtonActive) @@ -49150,6 +55130,7 @@ function ImGui.Button(label, size_arg) return ImGui.ButtonEx(label, size_arg, ImGuiButtonFlags.None) end +-- Small buttons fits within text without additional vertical spacing. --- @param label string --- @return bool function ImGui.SmallButton(label) @@ -49161,6 +55142,8 @@ function ImGui.SmallButton(label) return pressed end +-- Tip: use ImGui.PushID()/PopID() to push indices or pointers in the ID stack. +-- Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) --- @param str_id string --- @param size_arg ImVec2 --- @param flags? ImGuiButtonFlags @@ -49232,6 +55215,7 @@ function ImGui.ArrowButton(str_id, dir) return ImGui.ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags.None) end +-- Button to close a window --- @param id ImGuiID --- @param pos ImVec2 --- @return bool @@ -49240,6 +55224,8 @@ function ImGui.CloseButton(id, pos) local window = g.CurrentWindow + -- Tweak 1: Shrink hit-testing area if button covers an abnormally large proportion of the visible region. That's in order to facilitate moving the window away. (#3825) + -- This may better be applied as a general hit-rect reduction mechanism for all widgets to ensure the area to move window is always accessible? local bb = ImRect(pos, pos + ImVec2(g.FontSize, g.FontSize)) local bb_interact = ImRect() ImRect_Copy(bb_interact, bb) @@ -49249,6 +55235,8 @@ function ImGui.CloseButton(id, pos) bb_interact:Expand(ImTrunc(bb_interact:GetSize() * -0.25)) end + -- Tweak 2: We intentionally allow interaction when clipped so that a mechanical Alt,Right,Activate sequence can always close a window. + -- (this isn't the common behavior of buttons, but it doesn't affect the user because navigation tends to keep items visible in scrolling layer). local is_clipped = not ImGui.ItemAdd(bb_interact, id) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id) @@ -49256,6 +55244,7 @@ function ImGui.CloseButton(id, pos) return pressed end + -- Render local bg_col if held then bg_col = ImGui.GetColorU32(ImGuiCol.ButtonActive) @@ -49289,6 +55278,7 @@ function ImGui.CollapseButton(id, pos) local pressed, hovered = ImGui.ButtonBehavior(bb, id) + -- Render if hovered then window.DrawList:AddRectFilled(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.ButtonHovered)) end @@ -49313,6 +55303,7 @@ function ImGui.GetWindowScrollbarID(window, axis) end end +-- Return scrollbar rectangle, must only be called for corresponding axis if window.ScrollbarX/Y is set. --- @param window ImGuiWindow --- @param axis ImGuiAxis --- @return ImRect @@ -49353,6 +55344,12 @@ function ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb, threshold, axis) end end +-- Vertical/Horizontal scrollbar +-- The entire piece of code below is rather confusing because: +-- - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) +-- - 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.. --- @param bb_frame ImRect --- @param id ImGuiID --- @param axis ImGuiAxis @@ -49375,6 +55372,7 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ return false, p_scroll_v end + -- 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) local alpha = 1.0 if axis == ImGuiAxis.Y and bb_frame_height < bb_frame_width then alpha = ImSaturate(bb_frame_height / ImMax(bb_frame_width * 2.0, 1.0)) @@ -49404,7 +55402,9 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ return false, p_scroll_v end - IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0) + -- Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount) + -- But we maintain a minimum size in pixel to allow for the user to still aim inside. + IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0) -- Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. local win_size_v = ImMax(ImMax(size_contents_v, size_visible_v), 1) local grab_h_minsize = ImMin(bb:GetSize()[axis], style.GrabMinSize) local grab_h_pixels = ImTrunc(ImClamp(scrollbar_size_v * (size_visible_v / win_size_v), grab_h_minsize, scrollbar_size_v)) @@ -49415,15 +55415,18 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ ImRect_Copy(bb_hit, bb_frame) ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb_hit, g.Style.WindowBorderSize, ImGuiAxis.X + ImGuiAxis.Y - axis) -- swap axis here + -- Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). ImGui.ItemAdd(bb_frame, id, nil, ImGuiItemFlags.NoNav) local pressed, hovered, held = ImGui.ButtonBehavior(bb_hit, id, ImGuiButtonFlags.NoNavFocus) local scroll_max = ImMax(1, size_contents_v - size_visible_v) local scroll_ratio = ImSaturate(p_scroll_v / scroll_max) - local grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v + local grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v -- Grab position in normalized space if held and allow_interaction and grab_h_norm < 1.0 then local scrollbar_pos_v = bb.Min[axis] local mouse_pos_v = g.IO.MousePos[axis] + + -- Click position in scrollbar normalized space (0.0f->1.0f) local clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v) local held_dir @@ -49435,6 +55438,7 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ held_dir = 0 end if g.ActiveIdIsJustActivated then + -- On initial click when held_dir == 0 (clicked over grab): calculate the distance between mouse and the center of the grab local scroll_to_clicked_location = (g.IO.ConfigScrollbarScrollByPage == false) or g.IO.KeyShift or held_dir == 0 if scroll_to_clicked_location then @@ -49450,10 +55454,14 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ end end + -- Apply scroll (p_scroll_v will generally point on one member of window.Scroll) + -- It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position if g.ScrollbarSeekMode == 0 then + -- Absolute seeking scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5) / (1.0 - grab_h_norm)) p_scroll_v = scroll_v_norm * scroll_max else + -- Page by page if ImGui.IsMouseClickedEx(ImGuiMouseButton.Left, ImGuiInputFlags.Repeat) and held_dir == g.ScrollbarSeekMode then local page_dir if g.ScrollbarSeekMode > 0.0 then @@ -49465,10 +55473,16 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ end end + -- Update values for rendering scroll_ratio = ImSaturate(p_scroll_v / scroll_max) grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v + + -- Update distance to grab now that we have seek'ed and saturated + --if (seek_absolute) + -- g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f; end + -- Render local bg_col = ImGui.GetColorU32(ImGuiCol.ScrollbarBg) local grab_col if held then @@ -49510,7 +55524,8 @@ function ImGui.Scrollbar(axis) window.Scroll[axis] = scroll end --- - `uv0` and `uv1` are texture coordinates +-- - 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. --- @param tex_ref ImTextureRef --- @param image_size ImVec2 --- @param uv0? ImVec2 @@ -49602,7 +55617,7 @@ function ImGui.ImageButtonEx(id, tex_ref, image_size, uv0, uv1, bg_col, tint_col return pressed end --- - ImageButton() adds style.FramePadding*2.0 to provided size. This is in order to facilitate fitting an image in a button. +-- - 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? --- @param str_id string --- @param tex_ref ImTextureRef @@ -49653,12 +55668,13 @@ function ImGui.Checkbox(label, v) local is_visible = ImGui.ItemAdd(total_bb, id) local is_multi_select = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0) if not is_visible then - if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(total_bb) then -- Extra layer of "no logic clip" for box-select support + if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(total_bb) then -- Extra layer of "no logic clip" for box-select support -- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)) return false, v end end + -- Range-Selection/Multi-selection support (header) local checked = v if is_multi_select then -- TODO: MultiSelectItemHeader() @@ -49666,6 +55682,7 @@ function ImGui.Checkbox(label, v) local pressed, hovered, held = ImGui.ButtonBehavior(total_bb, id) + -- Range-Selection/Multi-selection support (footer) if is_multi_select then -- TODO: MultiSelectItemFooter() elseif pressed then @@ -49674,7 +55691,7 @@ function ImGui.Checkbox(label, v) if v ~= checked then v = checked - pressed = true + pressed = true -- return value ImGui.MarkItemEdited(id) end @@ -49845,8 +55862,8 @@ function ImGui.ProgressBar(fraction, size_arg, overlay) return end - -- Fraction < 0.0 will display an indeterminate progress bar animation - -- The value must be animated along with time, so e.g. passing '-1.0 * ImGui.GetTime()' as fraction works + -- Fraction < 0.0f will display an indeterminate progress bar animation + -- The value must be animated along with time, so e.g. passing '-1.0f * ImGui.GetTime()' as fraction works. local is_indeterminate = (fraction < 0.0) if not is_indeterminate then fraction = ImSaturate(fraction) @@ -49910,6 +55927,10 @@ function ImGui.Bullet() ImGui.SameLine(0, style.FramePadding.x * 2.0) end +-- This is provided as a convenience for being an often requested feature. +-- FIXME-STYLE: we delayed adding as there is a larger plan to revamp the styling system. +-- Because of this we currently don't provide many styling options for this widget +-- (e.g. hovered/active colors are automatically inferred from a single color). --- @param label string function ImGui.TextLink(label) local window = ImGui.GetCurrentWindow() @@ -49954,7 +55975,7 @@ function ImGui.TextLink(label) end local line_y = bb.Max.y + ImFloor(g.FontBaked.Descent * g.FontBakedScale * 0.20) - window.DrawList:AddLineH(bb.Min.x, bb.Max.x, line_y, ImGui.GetColorU32(line_colf), 1.0 * ImTrunc(g.Style._MainScale)) -- FIXME-DPI + window.DrawList:AddLineH(bb.Min.x, bb.Max.x, line_y, ImGui.GetColorU32(line_colf), 1.0 * ImTrunc(g.Style._MainScale)) -- FIXME-TEXT: Underline mode -- FIXME-DPI ImGui.PushStyleColor(ImGuiCol.Text, ImGui.GetColorU32(text_colf)) ImGui.RenderText(bb.Min, label, 1, label_end, false) @@ -49976,7 +55997,7 @@ function ImGui.TextLinkOpenURL(label, url) g.PlatformIO.Platform_OpenInShellFn(g, url) end - ImGui.SetItemTooltip(ImGui.LocalizeGetMsg(ImGuiLocKey.OpenLink_s), url) + ImGui.SetItemTooltip(ImGui.LocalizeGetMsg(ImGuiLocKey.OpenLink_s), url) -- It is more reassuring for user to _always_ display URL when it is the same as the label. if ImGui.BeginPopupContextItem() then if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.CopyLink)) then @@ -49988,9 +56009,16 @@ function ImGui.TextLinkOpenURL(label, url) return pressed end ----------------------------------------------------------------- --- [SECTION] Low-level Layout helpers ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Low-level Layout helpers +------------------------------------------------------------------------------- +-- - Spacing() +-- - Dummy() +-- - NewLine() +-- - AlignTextToFramePadding() +-- - SeparatorEx() [Internal] +-- - Separator() +------------------------------------------------------------------------------- function ImGui.Spacing() local window = ImGui.GetCurrentWindow() @@ -50023,8 +56051,7 @@ function ImGui.NewLine() window.DC.LayoutType = ImGuiLayoutType.Vertical window.DC.IsSameLine = false - if window.DC.CurrLineSize.y > 0.0 then - -- In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + if window.DC.CurrLineSize.y > 0.0 then -- In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. ImGui.ItemSize(ImVec2(0, 0)) else ImGui.ItemSize(ImVec2(0.0, g.FontSize)) @@ -50044,6 +56071,9 @@ function ImGui.AlignTextToFramePadding() window.DC.CurrLineTextBaseOffset = ImMax(window.DC.CurrLineTextBaseOffset, g.Style.FramePadding.y) end +-- Horizontal/vertical separating line +-- FIXME: Surprisingly, this seemingly trivial widget is a victim of many different legacy/tricky layout issues. +-- Note how thickness == 1.0f is handled specifically as not moving CursorPos by 'thickness', but other values are. --- @param flags ImGuiSeparatorFlags --- @param thickness float function ImGui.SeparatorEx(flags, thickness) @@ -50083,13 +56113,18 @@ function ImGui.SeparatorEx(flags, thickness) -- We currently don't need to provide the same feature for tables because tables naturally have border features. local columns = (bit32.band(flags, ImGuiSeparatorFlags.SpanAllColumns) ~= 0) and window.DC.CurrentColumns or nil if columns then - x1 = window.Pos.x + window.DC.Indent.x -- Used to be Pos.x before 2023/10/03 + x1 = window.Pos.x + window.DC.Indent.x -- Used to be Pos.x before 2023/10/03 x2 = window.Pos.x + window.Size.x ImGui.PushColumnsBackground() end -- We don't provide our width to the layout so that it doesn't get feed back into AutoFit -- FIXME: This prevents ->CursorMaxPos based bounding box evaluation from working (e.g. TableEndCell) + + -- Between 1.71 and 1.92.7, we maintained a hack where a 1.0f thin Separator() would not impact layout. + -- This was mostly chosen to allow backward compatibility with user's code assuming zero-height when calculating height for layout (e.g. bottom alignment of a status bar). + -- In order to handle scaling we need to scale separator thickness and it would not makes sense to have a disparity depending on height. + ----float thickness_for_layout = (thickness == 1.0f) ? 0.0f : thickness; // FIXME: See 1.70/1.71 Separator() change: makes legacy 1-px separator not affect layout yet. Should change. local bb = ImRect(ImVec2(x1, window.DC.CursorPos.y), ImVec2(x2, window.DC.CursorPos.y + thickness)) ImGui.ItemSize(ImVec2(0.0, thickness)) @@ -50148,7 +56183,7 @@ function ImGui.SeparatorTextEx(id, label, label_end, extra_w) local min_size = ImVec2(label_size.x + extra_w + padding.x * 2.0, ImMax(label_size.y + padding.y * 2.0, separator_thickness)) local bb = ImRect(pos, ImVec2(window.WorkRect.Max.x, pos.y + min_size.y)) - local text_baseline_y = ImTrunc((bb:GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.999) -- ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f)) + local text_baseline_y = ImTrunc((bb:GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.999) --ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f)) ImGui.ItemSize(min_size, text_baseline_y) if not ImGui.ItemAdd(bb, id) then @@ -50160,7 +56195,7 @@ function ImGui.SeparatorTextEx(id, label, label_end, extra_w) local seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5 + 0.999) local label_avail_w = ImMax(0.0, sep2_x2 - sep1_x1 - padding.x * 2.0) - local label_pos = ImVec2(pos.x + padding.x + ImMax(0.0, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y) -- FIXME-ALIGN + local label_pos = ImVec2(pos.x + padding.x + ImMax(0.0, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y) -- FIXME-ALIGN -- This allows using SameLine() to position something in the 'extra_w' window.DC.CursorPosPrevLine.x = label_pos.x + label_size.x @@ -50202,12 +56237,26 @@ function ImGui.SeparatorText(label) return end + -- The SeparatorText() vs SeparatorTextEx() distinction is designed to be considerate that we may want: + -- - allow separator-text to be draggable items (would require a stable ID + a noticeable highlight) + -- - this high-level entry point to allow formatting? (which in turns may require ID separate from formatted string) + -- - because of this we probably can't turn 'string label' into 'string fmt, ...' + -- Otherwise, we can decide that users wanting to drag this would layout a dedicated drag-item, + -- and then we can turn this into a format function. ImGui.SeparatorTextEx(0, label, ImGui.FindRenderedTextEnd(label), 0.0) end ----------------------------------------------------------------- --- [SECTION] COMBO BOX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: ComboBox +------------------------------------------------------------------------------- +-- - CalcMaxPopupHeightFromItemCount() [Internal] +-- - BeginCombo() +-- - BeginComboPopup() [Internal] +-- - EndCombo() +-- - BeginComboPreview() [Internal] +-- - EndComboPreview() [Internal] +-- - Combo() +------------------------------------------------------------------------------- --- @param items_count float --- @return float @@ -50229,7 +56278,7 @@ function ImGui.BeginCombo(label, preview_value, flags) local window = ImGui.GetCurrentWindow() local backup_next_window_data_flags = g.NextWindowData.HasFlags - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values if window.SkipItems then return false end @@ -50276,6 +56325,7 @@ function ImGui.BeginCombo(label, preview_value, flags) return false end + -- Open on click local pressed, hovered, held = ImGui.ButtonBehavior(bb, id) local popup_id = ImHashStr("##ComboPopup", nil, id) local popup_open = ImGui.IsPopupOpen(popup_id, ImGuiPopupFlags.None) @@ -50344,6 +56394,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) return false end + -- Set popup size local w = bb:GetWidth() if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) ~= 0 then g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w) @@ -50351,7 +56402,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) if bit32.band(flags, ImGuiComboFlags.HeightMask_) == 0 then flags = bit32.bor(flags, ImGuiComboFlags.HeightRegular) end - IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiComboFlags.HeightMask_))) + IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiComboFlags.HeightMask_))) -- Only one local popup_max_height_in_items = -1 if bit32.band(flags, ImGuiComboFlags.HeightRegular) ~= 0 then popup_max_height_in_items = 8 @@ -50362,7 +56413,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) end local constraint_min = ImVec2(0.0, 0.0) local constraint_max = ImVec2(FLT_MAX, FLT_MAX) - if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.x <= 0.0 then + if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.x <= 0.0 then -- Don't apply constraints if user specified a size constraint_min.x = w end if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.y <= 0.0 then @@ -50372,7 +56423,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) end -- This is essentially a specialized version of BeginPopupEx() - local name = ImFormatString("##Combo_%02d", g.BeginComboDepth) + local name = ImFormatString("##Combo_%02d", g.BeginComboDepth) -- Recycle windows based on depth -- Set position given a custom constraint (peak into expected window size so we can position it) -- FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function? @@ -50382,7 +56433,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) if popup_window.WasActive then -- Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us. local size_expected = ImGui.CalcWindowNextAutoFitSize(popup_window) - popup_window.AutoPosLastDirection = (bit32.band(flags, ImGuiComboFlags.PopupAlignLeft) ~= 0) and ImGuiDir.Left or ImGuiDir.Down + popup_window.AutoPosLastDirection = (bit32.band(flags, ImGuiComboFlags.PopupAlignLeft) ~= 0) and ImGuiDir.Left or ImGuiDir.Down -- Left = "Below, Toward Left", Down = "Below, Toward Right (default)" local r_outer = ImGui.GetPopupAllowedExtentRect(popup_window) local pos pos, popup_window.AutoPosLastDirection = ImGui.FindBestWindowPosForPopupEx(bb:GetBL(), size_expected, popup_window.AutoPosLastDirection, r_outer, bb, ImGuiPopupPositionPolicy.ComboBox) @@ -50422,8 +56473,11 @@ function ImGui.EndCombo() ImGui.EndPopup() end --- Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements --- (Experimental, see GitHub issues: #1658, #4168) +-- Submit preview contents for BeginCombo()/EndCombo(), to display contents that's more than just a text label. +-- - [BETA] See GitHub issues: #1658, #4168. +-- - Call directly after the BeginCombo/EndCombo block (requires ImGuiComboFlags.CustomPreview). +-- - The preview is designed to only host non-interactive elements. +-- - Not compatible with ImGuiComboFlags.WidthFitPreview. function ImGui.BeginComboPreview() local g = GImGui local window = g.CurrentWindow @@ -50461,6 +56515,7 @@ function ImGui.EndComboPreview() local window = g.CurrentWindow local preview_data = g.ComboPreviewData + -- FIXME: Using CursorMaxPos approximation instead of correct AABB which we will store in ImDrawCmd in the future local draw_list = window.DrawList if window.DC.CursorMaxPos.x < preview_data.PreviewRect.Max.x and window.DC.CursorMaxPos.y < preview_data.PreviewRect.Max.y then if draw_list.CmdBuffer.Size > 1 then -- Unlikely case that the PushClipRect() didn't create a command @@ -50473,7 +56528,7 @@ function ImGui.EndComboPreview() ImGui.PopClipRect() ImVec2_Copy(window.DC.CursorPos, preview_data.BackupCursorPos) - ImVec2_Copy(window.DC.CursorMaxPos, ImMax(window.DC.CursorMaxPos, preview_data.BackupCursorMaxPos)) + ImVec2_Copy(window.DC.CursorMaxPos, ImMax(window.DC.CursorMaxPos, preview_data.BackupCursorMaxPos)) -- No need to do the same with IdealMaxPos ImVec2_Copy(window.DC.CursorPosPrevLine, preview_data.BackupCursorPosPrevLine) window.DC.PrevLineTextBaseOffset = preview_data.BackupPrevLineTextBaseOffset window.DC.LayoutType = preview_data.BackupLayout @@ -50536,6 +56591,7 @@ function ImGui.Combo(label, current_item, a, b, c, d) local getter, user_data, items_count, popup_max_height_in_items = Items_ResolveArgs(a, b, c, d) if popup_max_height_in_items == nil then popup_max_height_in_items = -1 end + -- Call the getter to obtain the preview string which is a parameter to BeginCombo() local preview_value = nil if bit32.band(bit32.bor(g.NextItemData.ItemFlagsSet, g.CurrentItemFlags), ImGuiItemFlags.MixedValue) ~= 0 then preview_value = "" @@ -50543,6 +56599,7 @@ function ImGui.Combo(label, current_item, a, b, c, d) preview_value = getter(user_data, current_item) end + -- 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 and bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) == 0 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))) end @@ -50551,6 +56608,7 @@ function ImGui.Combo(label, current_item, a, b, c, d) return current_item, false end + -- Display items local value_changed = false local clipper = ImGuiListClipper() clipper:Begin(items_count) @@ -50583,9 +56641,18 @@ function ImGui.Combo(label, current_item, a, b, c, d) return current_item, value_changed end ----------------------------------------------------------------- --- [SECTION] DATA TYPE & DATA FORMATTING [Internal] ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Data Type and Data Formatting Helpers [Internal] +------------------------------------------------------------------------------- +-- - DataTypeGetInfo() +-- - DataTypeFormatString() +-- - DataTypeApplyOp() +-- - DataTypeApplyFromText() +-- - DataTypeCompare() +-- - DataTypeClamp() +-- - GetMinimumStepAtDecimalPrecision +-- - RoundScalarWithFormat<>() +------------------------------------------------------------------------------- local function float(val) return val end local function double(val) return val end @@ -50606,16 +56673,16 @@ local function ImGuiDataTypeInfo(size, name, print_fmt, scan_fmt) end local GDataTypeInfo = { - ImGuiDataTypeInfo(1, "S8", "%d", "%d"), + ImGuiDataTypeInfo(1, "S8", "%d", "%d"), -- ImGuiDataType.S8 ImGuiDataTypeInfo(1, "U8", "%u", "%u"), - ImGuiDataTypeInfo(2, "S16", "%d", "%d"), + ImGuiDataTypeInfo(2, "S16", "%d", "%d"), -- ImGuiDataType.S16 ImGuiDataTypeInfo(2, "U16", "%u", "%u"), - ImGuiDataTypeInfo(4, "S32", "%d", "%d"), + ImGuiDataTypeInfo(4, "S32", "%d", "%d"), -- ImGuiDataType.S32 ImGuiDataTypeInfo(4, "U32", "%u", "%u"), - ImGuiDataTypeInfo(4, "float", "%.3f", "%f"), - ImGuiDataTypeInfo(8, "double", "%f", "%lf"), - ImGuiDataTypeInfo(1, "bool", "%d", "%d"), - ImGuiDataTypeInfo(0, "string", "%s", "%s") + ImGuiDataTypeInfo(4, "float", "%.3f", "%f"), -- ImGuiDataType.Float + ImGuiDataTypeInfo(8, "double", "%f", "%lf"), -- ImGuiDataType.Double + ImGuiDataTypeInfo(1, "bool", "%d", "%d"), -- ImGuiDataType.Bool + ImGuiDataTypeInfo(0, "string", "%s", "%s") -- ImGuiDataType.String } --- @param data_type ImGuiDataType @@ -50715,12 +56782,15 @@ end local ImParseFormatSanitizeForScanning +-- User can input math operators (e.g. +100) to edit a numerical values. +-- NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess.. --- @param buf char[] --- @param data_type ImGuiDataType --- @param data number --- @param format string --- @param data_when_empty? number function ImGui.DataTypeApplyFromText(buf, data_type, data, format, data_when_empty) + -- Copy the value so we can compare at the end of the function if it changed at all. local type_info = ImGui.DataTypeGetInfo(data_type) local data_backup = data @@ -50736,16 +56806,19 @@ function ImGui.DataTypeApplyFromText(buf, data_type, data, format, data_when_emp return data, false end + -- Sanitize format + -- - For float/double we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in, so force them into %f and %lf local format_sanitized, format_sanitized_size = {}, 32 if (data_type == ImGuiDataType.Float or data_type == ImGuiDataType.Double) then format = type_info.ScanFmt else format = ImParseFormatSanitizeForScanning(format, format_sanitized, format_sanitized_size) if format[1] == 0 then - format = type_info.ScanFmt + format = type_info.ScanFmt -- Format doesn't want us to show the number currently, but we still need to parse the resulting input end end + -- Small types need a 32-bit buffer to receive the result from scanf() local v32 = 0 local res = {} if ImStd.sscanf(buf, 1, format, res) < 1 then @@ -50806,6 +56879,7 @@ end --- @param v_max? T --- @return T, boolean local function DataTypeClampT(v, v_min, v_max) + -- Clamp, both sides are optional, return true if modified if v_min and v < v_min then return v_min, true end if v_max and v > v_max then return v_max, true end return v, false @@ -50870,16 +56944,37 @@ function ImGui.RoundScalarWithFormatT(format, data_type, v) -- TODO: Sanitize format + -- Format value with our rounding, and read back local str = ImFormatString(format, v) v = ImAtof(str) or v return v end ----------------------------------------------------------------- --- [SECTION] INPUTXXX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +------------------------------------------------------------------------------- +-- - ImParseFormatFindStart() [Internal] +-- - ImParseFormatFindEnd() [Internal] +-- - ImParseFormatTrimDecorations() [Internal] +-- - ImParseFormatSanitizeForScanning() [Internal] +-- - ImParseFormatPrecision() [Internal] +-- - TempInputText() [Internal] +-- - TempInputScalar() [Internal] +-- - InputScalar() +-- - InputScalarN() +-- - InputFloat() +-- - InputFloat2() +-- - InputFloat3() +-- - InputFloat4() +-- - InputInt() +-- - InputInt2() +-- - InputInt3() +-- - InputInt4() +-- - InputDouble() +------------------------------------------------------------------------------- +-- We don't use strchr() because our strings are usually very short and often start with '%' --- @param fmt string function ImParseFormatFindStart(fmt) local len = #fmt @@ -50900,7 +56995,7 @@ end --- @param fmt string --- @param pos int local function ImParseFormatFindEnd(fmt, pos) - -- Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format + -- Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format. if string.byte(fmt, pos) ~= 37 then -- '%' return pos end @@ -50920,6 +57015,10 @@ local function ImParseFormatFindEnd(fmt, pos) return len + 1 end +-- Extract the format out of a format string with leading or trailing decorations +-- fmt = "blah blah" -> return "" +-- fmt = "%.3f" -> return "%.3f" +-- fmt = "hello %.3f" -> return "%.3f" -- TODO: temporary patch. does not look good --- @param fmt string local function ImParseFormatTrimDecorations(fmt) @@ -50935,13 +57034,14 @@ local function ImParseFormatTrimDecorations(fmt) return string.sub(fmt, fmt_start, fmt_end) end +-- - For scanning we need to remove all width and precision fields and flags "%+3.7f" -> "%f". BUT don't strip types like "%I64d" which includes digits. ! "%07I64d" -> "%I64d" --- @param fmt_in string --- @param fmt_out char[] --- @param fmt_out_size size_t function ImParseFormatSanitizeForScanning(fmt_in, fmt_out, fmt_out_size) local fmt_end = ImParseFormatFindEnd(fmt_in, 1) -- IM_UNUSED(fmt_out_size) - IM_ASSERT(fmt_end < fmt_out_size) + IM_ASSERT(fmt_end < fmt_out_size) -- Format is too long, let us know if this happens to you! local has_type = false local fmt_in_begin = 1 local fmt_out_begin = 1 @@ -50954,15 +57054,15 @@ function ImParseFormatSanitizeForScanning(fmt_in, fmt_out, fmt_out_size) break end - has_type = has_type or ((c >= 97 and c <= 122) or (c >= 65 and c <= 90)) - if c ~= 39 and c ~= 36 and c ~= 95 then + has_type = has_type or ((c >= 97 and c <= 122) or (c >= 65 and c <= 90)) -- Stop skipping digits + if c ~= 39 and c ~= 36 and c ~= 95 then -- Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '. fmt_out[fmt_out_begin] = c fmt_out_begin = fmt_out_begin + 1 end until true end - -- fmt_out[fmt_out_begin] = 0 + -- fmt_out[fmt_out_begin] = 0 -- Zero-terminate return string.char(unpack(fmt_out)) -- FIXME: not ideal end @@ -50989,6 +57089,8 @@ local function ImAtoi(str, pos) return negative and -v or v, pos end +-- Parse display precision back from the display format string +-- FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed. --- @param fmt string --- @param default_precision int local function ImParseFormatPrecision(fmt, default_precision) @@ -51021,6 +57123,9 @@ local function ImParseFormatPrecision(fmt, default_precision) return (precision == INT_MAX) and default_precision or precision end +-- Create text input in place of another active widget (e.g. used when doing a Ctrl+Click on drag/slider widgets) +-- - This must be submitted right after the item it is overlaying. +-- FIXME: Facilitate using this in variety of other situations. --- @param bb ImRect --- @param id ImGuiID --- @param label string @@ -51032,6 +57137,8 @@ end function ImGui.TempInputText(bb, id, label, buf, buf_size, flags, callback, user_data) if flags == nil then flags = 0 end + -- On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id. + -- We clear ActiveID on the first frame to allow the InputText() taking it back. local g = GImGui local window = g.CurrentWindow @@ -51044,10 +57151,11 @@ function ImGui.TempInputText(bb, id, label, buf, buf_size, flags, callback, user local backup_pos = ImVec2() ImVec2_Copy(backup_pos, window.DC.CursorPos) ImVec2_Copy(window.DC.CursorPos, bb.Min) - g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowDuplicateId) + g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowDuplicateId) -- Using ImGuiInputTextFlags.MergedItem above will skip ItemAdd() so we poke here. local value_changed = ImGui.InputTextEx(label, nil, buf, buf_size, bb:GetSize(), bit32.bor(flags, ImGuiInputTextFlags.TempInput, ImGuiInputTextFlags.AutoSelectAll), callback, user_data) - ImGui.KeepAliveID(id) + ImGui.KeepAliveID(id) -- Not done because of ImGuiInputTextFlags.TempInput if (not is_active and not is_deactivated) then + -- First frame we started displaying the InputText widget, we expect it to take the active id. IM_ASSERT(g.ActiveId == id) g.TempInputId = g.ActiveId end @@ -51059,6 +57167,9 @@ function ImGui.TempInputText(bb, id, label, buf, buf_size, flags, callback, user return value_changed end +-- Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags.AlwaysClamp flag is set! +-- This is intended: this way we allow Ctrl+Click manual input to set a value out of bounds, for maximum flexibility. +-- However this may not be ideal for all uses, as some user code may break on out of bound values. --- @param bb ImRect --- @param id ImGuiID --- @param label string @@ -51068,6 +57179,8 @@ end --- @param clamp_min? number --- @param clamp_max? number function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min, clamp_max) + -- FIXME: May need to clarify display behavior if format doesn't contain %. + -- "%d" -> "%d" / "There are %d items" -> "%d" / "items" -> "%d" (fallback). Also see #6405 local g = GImGui local type_info = ImGui.DataTypeGetInfo(data_type) local data_buf, data_buf_size = {}, 32 @@ -51079,14 +57192,16 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min ImStd.ImStrTrimBlanks(data_buf) local flags = bit32.bor(ImGuiInputTextFlags.AutoSelectAll, ImGuiInputTextFlags.LocalizeDecimalPoint) - g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited) + g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited) -- Because TempInputText() uses ImGuiInputTextFlags.MergedItem it doesn't submit a new item, so we poke LastItemData. g.LastItemData.ItemFlags = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0) and bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputText) or bit32.band(g.LastItemData.ItemFlags, bit32.bnot(ImGuiItemFlags.LiveEditOnInputText)) if not ImGui.TempInputText(bb, id, label, data_buf, data_buf_size, flags) then return data, false end + -- Backup old value local data_backup = data + -- Apply new value (or operations) then clamp data = ImGui.DataTypeApplyFromText(data_buf, data_type, data, format, nil) if clamp_min or clamp_max then if clamp_min and clamp_max and ImGui.DataTypeCompare(data_type, clamp_min, clamp_max) > 0 then @@ -51095,6 +57210,7 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min data = ImGui.DataTypeClamp(data_type, data, clamp_min, clamp_max) end + -- Only mark as edited if new value is different g.LastItemData.ItemFlags = bit32.band(g.LastItemData.ItemFlags, bit32.bnot(ImGuiItemFlags.NoMarkEdited)) local value_changed = data_backup ~= data if value_changed then @@ -51104,6 +57220,8 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min return data, value_changed end +-- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For an Input widget, step and step_fast are optional. +-- Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @param label string --- @param data_type ImGuiDataType --- @param data number @@ -51121,6 +57239,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag local g = GImGui local style = g.Style + -- IM_ASSERT((flags & ImGuiInputTextFlags.EnterReturnsTrue) == 0) -- Not supported by InputScalar(). Please open an issue if you this would be useful to you. Otherwise use IsItemDeactivatedAfterEdit()! if format == nil then format = ImGui.DataTypeGetInfo(data_type).PrintFmt @@ -51135,6 +57254,8 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag ImGui.DataTypeFormatString(buf, buf_size, data_type, data, format) end + -- Disable the MarkItemEdited() call in InputText but keep ImGuiItemStatusFlags.Edited. + -- We call MarkItemEdited() ourselves by comparing the actual data rather than the string. g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoMarkEdited) flags = bit32.bor(flags, ImGuiInputTextFlags.AutoSelectAll, ImGuiInputTextFlags.LocalizeDecimalPoint) @@ -51142,18 +57263,21 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag local button_size = has_step_buttons and ImGui.GetFrameHeight() or 0.0 local ret if has_step_buttons then - ImGui.BeginGroup() + -- With Step Buttons + ImGui.BeginGroup() -- The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() ImGui.PushID(label) ImGui.SetNextItemWidth(ImMax(1.0, ImGui.CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)) - ret = ImGui.InputText("", buf, buf_size, flags) + ret = ImGui.InputText("", buf, buf_size, flags) -- PushID(label) + "" gives us the expected ID from outside point of view -- IMGUI_TEST_ENGINE_ITEM_INFO() else + -- Without Step Buttons ret = ImGui.InputText(label, buf, buf_size, flags) end + -- Apply local value_changed = false if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0 then - local input_edited = bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal) ~= 0 + local input_edited = bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal) ~= 0 -- We would be using 'ret' if ImGuiInputTextFlags.EnterReturnsTrue was not involved. if input_edited then data, value_changed = ImGui.DataTypeApplyFromText(buf, data_type, data, format, bit32.band(flags, ImGuiInputTextFlags.ParseEmptyRefVal) ~= 0 and data_default or nil) end @@ -51166,6 +57290,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag end end + -- Step buttons if has_step_buttons then local backup_frame_padding = ImVec2() ImVec2_Copy(backup_frame_padding, style.FramePadding) @@ -51298,6 +57423,7 @@ function ImGui.InputInt(label, v, step, step_fast, flags) if step_fast == nil then step_fast = 100 end if flags == nil then flags = 0 end + -- Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. local format = (bit32.band(flags, ImGuiInputTextFlags.CharsHexadecimal) ~= 0) and "%08X" or "%d" return ImGui.InputScalar(label, ImGuiDataType.S32, v, (step > 0) and step or nil, (step_fast > 0) and step_fast or nil, format, flags) end @@ -51330,9 +57456,24 @@ function ImGui.InputDouble(label, v, step, step_fast, format, flags) return ImGui.InputScalar(label, ImGuiDataType.Double, v, (step > 0.0 and step or nil), (step_fast > 0.0 and step_fast or nil), format, flags) end ----------------------------------------------------------------- --- [SECTION] DRAGXXX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +------------------------------------------------------------------------------- +-- - DragBehaviorT<>() [Internal] +-- - DragBehavior() [Internal] +-- - DragScalar() +-- - DragScalarN() +-- - DragFloat() +-- - DragFloat2() +-- - DragFloat3() +-- - DragFloat4() +-- - DragFloatRange2() +-- - DragInt() +-- - DragInt2() +-- - DragInt3() +-- - DragInt4() +-- - DragIntRange2() +------------------------------------------------------------------------------- -- This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) --- @generic T : number @@ -51396,7 +57537,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m end adjust_delta = adjust_delta * v_speed - -- For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter + -- For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter. if axis == ImGuiAxis.Y then adjust_delta = -adjust_delta end @@ -51451,7 +57592,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m v_cur = ImGui.RoundScalarWithFormatT(format, data_type, v_cur) end - -- Preserve remainder after rounding has been applied. This also allow slow tweaking of values + -- Preserve remainder after rounding has been applied. This also allow slow tweaking of values. g.DragCurrentAccumDirty = false if is_logarithmic then -- Convert to parametric space, apply delta, convert back @@ -51461,7 +57602,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m g.DragCurrentAccum = g.DragCurrentAccum - ((SIGNEDTYPE)(v_cur) - (SIGNEDTYPE)(v)) end - -- This does nothing + -- Lose zero sign for float/double if v_cur == (TYPE)(-0) then v_cur = (TYPE)(0) end @@ -51476,7 +57617,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m v_cur = (TYPE)(v_cur - (TYPE)((TYPE)(v_max - v_min) - (is_floating_point and 0 or 1))) end else - -- Clamp values + handle overflow/wrap-around for integer types + -- Clamp values + handle overflow/wrap-around for integer types. if v_cur < v_min or (v_cur > v and adjust_delta < 0.0 and not is_floating_point) then v_cur = (TYPE)(v_min) end @@ -51504,8 +57645,10 @@ end --- @param flags ImGuiSliderFlags @native function ImGui.DragBehavior(id, data_type, v, v_speed, min, max, format, flags) + -- Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. IM_ASSERT((flags == 1 or bit32.band(flags, ImGuiSliderFlags.InvalidMask_) == 0), "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.") + -- Things we can do easily outside the DragBehaviorT<> template, saves code generation. local g = GImGui if g.ActiveId == id then if g.ActiveIdSource == ImGuiInputSource.Mouse and not g.IO.MouseDown[0] then @@ -51543,6 +57686,7 @@ function ImGui.DragBehavior(id, data_type, v, v_speed, min, max, format, flags) return v, false end +-- Only clamp Ctrl+Click input when ImGuiSliderFlags.ClampOnInput is set (generally via ImGuiSliderFlags.AlwaysClamp) --- @param flags ImGuiSliderFlags --- @param data_type ImGuiDataType --- @param min number @@ -51551,7 +57695,7 @@ local function TempInputIsClampEnabled(flags, data_type, min, max) if bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 and (min ~= nil or max ~= nil) then local clamp_range_dir = 0 if min ~= nil and max ~= nil then - clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) + clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) -- -1 when min < max, == 0 when min == max end if min == nil or max == nil or clamp_range_dir < 0 then return true @@ -51586,6 +57730,8 @@ function FormatCached(format, v) return r end +-- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a Drag widget, min and max are optional. +-- Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. @native function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, flags) if v_speed == nil then v_speed = 1.0 end @@ -51620,6 +57766,7 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla local hovered = ImGui.ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags) local temp_input_is_active = temp_input_allowed and ImGui.TempInputIsActive(id) if not temp_input_is_active then + -- Tabbing or Ctrl+Click on Drag turns it into an InputText local clicked = hovered and ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, id) local double_clicked = (hovered and g.IO.MouseClickedCount[0] == 2 and ImGui.TestKeyOwner(ImGuiKey.MouseLeft, id)) local make_active = (clicked or double_clicked or g.NavActivateId == id) @@ -51679,7 +57826,7 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla -- TODO: ImGui.DataTypeFormatString() should be used here instead of ImFormatString() - -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value + -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value. ImGui.RenderTextClipped(frame_bb.Min, frame_bb.Max, FormatCached(format, data), nil, nil, DRAG_TEXT_ALIGN) if label_size.x > 0.0 then @@ -51706,6 +57853,7 @@ function ImGui.DragFloat(label, v, v_speed, v_min, v_max, format, flags) return ImGui.DragScalar(label, ImGuiDataType.Float, v, v_speed, v_min, v_max, format, flags) end +-- NB: v_speed is float to allow adjusting the drag speed with more precision --- @param label string --- @param v int --- @param v_speed? float @@ -51782,7 +57930,7 @@ ImGui.DragInt2 = DragIntN(2) ImGui.DragInt3 = DragIntN(3) ImGui.DragInt4 = DragIntN(4) --- NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. +-- NB: You likely want to specify the ImGuiSliderFlags.AlwaysClamp when using this. --- @return float v_current_min --- @return float v_current_max --- @return bool value_changed @@ -51830,9 +57978,28 @@ function ImGui.DragIntRange2(label, v_current_min, v_current_max, v_speed, v_min return DragRange2(ImGuiDataType.S32, label, v_current_min, v_current_max, v_speed or 1.0, v_min or 0, v_max or 0, format or "%d", format_max, flags or 0) end ----------------------------------------------------------------- --- [SECTION] SLIDERXXX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +------------------------------------------------------------------------------- +-- - ScaleRatioFromValueT<> [Internal] +-- - ScaleValueFromRatioT<> [Internal] +-- - SliderBehaviorT<>() [Internal] +-- - SliderBehavior() [Internal] +-- - SliderScalar() +-- - SliderScalarN() +-- - SliderFloat() +-- - SliderFloat2() +-- - SliderFloat3() +-- - SliderFloat4() +-- - SliderAngle() +-- - SliderInt() +-- - SliderInt2() +-- - SliderInt3() +-- - SliderInt4() +-- - VSliderScalar() +-- - VSliderFloat() +-- - VSliderInt() +------------------------------------------------------------------------------- -- Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT) --- @param data_type ImGuiDataType @@ -51978,7 +58145,11 @@ function ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, t, v_min, v_max local is_floating_point = (data_type == ImGuiDataType.Float) or (data_type == ImGuiDataType.Double) if is_floating_point then result = ImLerp(v_min, v_max, t) - elseif t < 1.0 then + elseif t < 1.0 then -- t is already < 1.0 here + -- - For integer values we want the clicking position to match the grab box so we round above + -- This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. + -- - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64 + -- range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits. local v_new_off_f = (SIGNEDTYPE)((v_max - v_min)) * t result = (TYPE)((SIGNEDTYPE)(v_min) + (SIGNEDTYPE)(v_new_off_f + 0)) -- LUA: + 0 instead of + ((v_min > v_max) and -0.5 or 0.5) end @@ -51987,6 +58158,7 @@ function ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, t, v_min, v_max return result end +-- FIXME: Try to move more of the code into shared SliderBehavior() --- @generic T : number --- @param TYPE fun(val: number): T --- @param SIGNEDTYPE fun(val: number): T @@ -52008,27 +58180,30 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ local axis = (bit32.band(flags, ImGuiSliderFlags.Vertical) ~= 0) and ImGuiAxis.Y or ImGuiAxis.X local is_logarithmic = bit32.band(flags, ImGuiSliderFlags.Logarithmic) ~= 0 local is_floating_point = (data_type == ImGuiDataType.Float) or (data_type == ImGuiDataType.Double) - local v_range_f = (v_min < v_max) and (v_max - v_min) or (v_min - v_max) + local v_range_f = (v_min < v_max) and (v_max - v_min) or (v_min - v_max) -- We don't need high precision for what we do with it. - local grab_padding = 2.0 + -- Calculate bounds + local grab_padding = 2.0 -- FIXME: Should be part of style. local slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0 local grab_sz = style.GrabMinSize - if not is_floating_point and v_range_f >= 0.0 then - grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize) + if not is_floating_point and v_range_f >= 0.0 then -- v_range_f < 0 may happen on integer overflows + grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize) -- For integer sliders: if possible have the grab size represent 1 unit end grab_sz = ImMin(grab_sz, slider_sz) local slider_usable_sz = slider_sz - grab_sz local slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5 local slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5 - local logarithmic_zero_epsilon = 0.0 - local zero_deadzone_halfsize = 0.0 + local logarithmic_zero_epsilon = 0.0 -- Only valid when is_logarithmic is true + local zero_deadzone_halfsize = 0.0 -- Only valid when is_logarithmic is true if is_logarithmic then + -- When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. local decimal_precision = is_floating_point and ImParseFormatPrecision(format, 3) or 1 logarithmic_zero_epsilon = ImPow(0.1, decimal_precision) zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5) / ImMax(slider_usable_sz, 1.0) end + -- Process interacting with the slider local value_changed = false if g.ActiveId == id then local set_new_value = false @@ -52044,7 +58219,7 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ grab_t = 1.0 - grab_t end local grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t) - local clicked_around_grab = (mouse_abs_pos >= grab_pos - grab_sz * 0.5 - 1.0) and (mouse_abs_pos <= grab_pos + grab_sz * 0.5 + 1.0) + local clicked_around_grab = (mouse_abs_pos >= grab_pos - grab_sz * 0.5 - 1.0) and (mouse_abs_pos <= grab_pos + grab_sz * 0.5 + 1.0) -- No harm being extra generous here. g.SliderGrabClickOffset = (clicked_around_grab and is_floating_point) and (mouse_abs_pos - grab_pos) or 0.0 end if slider_usable_sz > 0.0 then @@ -52057,7 +58232,7 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ end elseif g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad then if g.ActiveIdIsJustActivated then - g.SliderCurrentAccum = 0.0 + g.SliderCurrentAccum = 0.0 -- Reset any stored nav delta upon activation g.SliderCurrentAccumDirty = false end @@ -52067,13 +58242,13 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ local tweak_fast = ImGui.IsKeyDown((g.NavInputSource == ImGuiInputSource.Gamepad) and ImGuiKey.NavGamepadTweakFast or ImGuiKey.NavKeyboardTweakFast) local decimal_precision = is_floating_point and ImParseFormatPrecision(format, 3) or 0 if decimal_precision > 0 then - input_delta = input_delta / 100.0 + input_delta = input_delta / 100.0 -- Keyboard/Gamepad tweak speeds in % of slider bounds if tweak_slow then input_delta = input_delta / 10.0 end else if (v_range_f >= -100.0 and v_range_f <= 100.0 and v_range_f ~= 0.0) or tweak_slow then - input_delta = ((input_delta < 0.0) and -1.0 or 1.0) / v_range_f + input_delta = ((input_delta < 0.0) and -1.0 or 1.0) / v_range_f -- Keyboard/Gamepad tweak speeds in integer steps else input_delta = input_delta / 100.0 end @@ -52092,14 +58267,15 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ elseif g.SliderCurrentAccumDirty then clicked_t = ImGui.ScaleRatioFromValueT(data_type, v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) - if (clicked_t >= 1.0 and delta > 0.0) or (clicked_t <= 0.0 and delta < 0.0) then + if (clicked_t >= 1.0 and delta > 0.0) or (clicked_t <= 0.0 and delta < 0.0) then -- This is to avoid applying the saturation when already past the limits set_new_value = false - g.SliderCurrentAccum = 0.0 + g.SliderCurrentAccum = 0.0 -- If pushing up against the limits, don't continue to accumulate else set_new_value = true local old_clicked_t = clicked_t clicked_t = ImSaturate(clicked_t + delta) + -- Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator local v_new = ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) if is_floating_point and bit32.band(flags, ImGuiSliderFlags.NoRoundToFormat) == 0 then v_new = ImGui.RoundScalarWithFormatT(format, data_type, v_new) @@ -52126,10 +58302,12 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ if set_new_value then local v_new = ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) + -- Round to user desired precision based on format string if is_floating_point and bit32.band(flags, ImGuiSliderFlags.NoRoundToFormat) == 0 then v_new = ImGui.RoundScalarWithFormatT(format, data_type, v_new) end + -- Apply result if v ~= v_new then v = v_new value_changed = true @@ -52140,6 +58318,7 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ if slider_sz < 1.0 then ImRect_Copy(out_grab_bb, ImRect(bb.Min, bb.Min)) else + -- Output grab position so it can be displayed by the caller local grab_t = ImGui.ScaleRatioFromValueT(data_type, v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) if axis == ImGuiAxis.Y then grab_t = 1.0 - grab_t @@ -52155,6 +58334,9 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ return v, value_changed end +-- For 32-bit and larger types, slider bounds are limited to half the natural type range. +-- So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. +-- It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. --- @generic T : number --- @param bb ImRect --- @param id ImGuiID @@ -52168,8 +58350,9 @@ end --- @return T v --- @return bool value_changed function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out_grab_bb) + -- Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. IM_ASSERT((flags == 1 or bit32.band(flags, ImGuiSliderFlags.InvalidMask_) == 0), "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.") - IM_ASSERT(bit32.band(flags, ImGuiSliderFlags.WrapAround) == 0) + IM_ASSERT(bit32.band(flags, ImGuiSliderFlags.WrapAround) == 0) -- Not supported by SliderXXX(), only by DragXXX() if data_type == ImGuiDataType.S8 then local v32 = (ImS32)((ImS8)(v)); local r @@ -52209,6 +58392,8 @@ function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out return v, false end +-- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a slider, min and max are required. +-- Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @generic T : number --- @param label string --- @param data_type ImGuiDataType @@ -52244,6 +58429,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) return data, false end + -- Default format string when passing NULL if format == nil then format = ImGui.DataTypeGetInfo(data_type).PrintFmt end @@ -52251,6 +58437,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) local hovered = ImGui.ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags) local temp_input_is_active = temp_input_allowed and ImGui.TempInputIsActive(id) if not temp_input_is_active then + -- Tabbing or Ctrl+Click on Slider turns it into an input box local clicked = hovered and ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, id) local make_active = clicked or g.NavActivateId == id if make_active and clicked then @@ -52262,6 +58449,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) end end + -- Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert) if make_active then g.ActiveIdValueOnActivation = data end @@ -52275,10 +58463,12 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) end if temp_input_is_active then - local clamp_enabled = bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 + -- Only clamp Ctrl+Click input when ImGuiSliderFlags.ClampOnInput is set (generally via ImGuiSliderFlags.AlwaysClamp) + local clamp_enabled = bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 -- Don't use TempInputIsClampEnabled() return ImGui.TempInputScalar(frame_bb, id, label, data_type, data, format, clamp_enabled and min or nil, clamp_enabled and max or nil) end + -- Draw frame local frame_col = ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.FrameBgActive or (hovered and ImGuiCol.FrameBgHovered or ImGuiCol.FrameBg)) ImGui.RenderNavCursor(frame_bb, id) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding) @@ -52287,6 +58477,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) end ImGui.RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding) + -- Slider behavior local grab_bb = ImRect() local value_changed data, value_changed = ImGui.SliderBehavior(frame_bb, id, data_type, data, min, max, format, flags, grab_bb) @@ -52294,12 +58485,14 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) ImGui.MarkItemEdited(id) end + -- Render grab if grab_bb.Max.x > grab_bb.Min.x then window.DrawList:AddRectFilled(grab_bb.Min, grab_bb.Max, ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.SliderGrabActive or ImGuiCol.SliderGrab), style.GrabRounding) end -- TODO: ImGui.DataTypeFormatString() should be used here instead of ImFormatString() + -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value. -- if g.LogEnabled then -- ImGui.LogSetNextTextDecoration("{", "}") -- end @@ -52313,6 +58506,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) return data, value_changed end +-- Add multiple sliders on 1 line for compact edition of multiple components --- @param label string --- @param data_type ImGuiDataType --- @param v table @@ -52481,6 +58675,7 @@ function ImGui.VSliderScalar(label, size, data_type, data, min, max, format, fla return data, false end + -- Default format string when passing NULL if format == nil then format = ImGui.DataTypeGetInfo(data_type).PrintFmt end @@ -52497,10 +58692,12 @@ function ImGui.VSliderScalar(label, size, data_type, data, min, max, format, fla g.ActiveIdUsingNavDirMask = bit32.bor(g.ActiveIdUsingNavDirMask, bit32.lshift(1, ImGuiDir.Up), bit32.lshift(1, ImGuiDir.Down)) end + -- Draw frame local frame_col = ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.FrameBgActive or (hovered and ImGuiCol.FrameBgHovered or ImGuiCol.FrameBg)) ImGui.RenderNavCursor(frame_bb, id) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding) + -- Slider behavior local grab_bb = ImRect() local value_changed data, value_changed = ImGui.SliderBehavior(frame_bb, id, data_type, data, min, max, format, bit32.bor(flags or 0, ImGuiSliderFlags.Vertical), grab_bb) @@ -52508,10 +58705,13 @@ function ImGui.VSliderScalar(label, size, data_type, data, min, max, format, fla ImGui.MarkItemEdited(id) end + -- Render grab if grab_bb.Max.y > grab_bb.Min.y then window.DrawList:AddRectFilled(grab_bb.Min, grab_bb.Max, ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.SliderGrabActive or ImGuiCol.SliderGrab), style.GrabRounding) end + -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + -- For the vertical slider we allow centered text to overlap the frame padding -- local value_buf, value_buf_size = {}, 64 -- TODO: ImGui.DataTypeFormatString() ImGui.RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, ImFormatString(format, data), nil, nil, ImVec2(0.5, 0.0)) @@ -52549,9 +58749,16 @@ function ImGui.VSliderInt(label, size, v, v_min, v_max, format, flags) return ImGui.VSliderScalar(label, size, ImGuiDataType.S32, v, v_min, v_max, format, flags) end ----------------------------------------------------------------- --- [SECTION] INPUT TEXT ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint +------------------------------------------------------------------------------- +-- - imstb_textedit.h include +-- - InputText() +-- - InputTextWithHint() +-- - InputTextMultiline() +-- - InputTextEx() [Internal] +-- - DebugNodeInputTextState() [Internal] +------------------------------------------------------------------------------- --- @param label string --- @param buf char[] @@ -52562,7 +58769,7 @@ end function ImGui.InputText(label, buf, buf_size, flags, callback, user_data) if flags == nil then flags = 0 end - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) -- call InputTextMultiline() return ImGui.InputTextEx(label, nil, buf, buf_size, ImVec2(0, 0), flags, callback, user_data) end @@ -52610,6 +58817,11 @@ local function InputTextCalcTextSize(ctx, text, text_begin, text_end_display, te return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, obj.WrapWidth, text, text_begin, text_end_display, text_end, out_offset, flags) end +-- 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) +-- With our UTF-8 use of stb_textedit: +-- - STB_TEXTEDIT_GETCHAR is nothing more than a a "GETBYTE". It's only used to compare to ascii or to copy blocks of text so we are fine. +-- - One exception is the STB_TEXTEDIT_IS_SPACE feature which would expect a full char in order to handle full-width space such as 0x3000 (see ImCharIsBlankW). +-- - ...but we don't use that feature. --- @param obj ImGuiInputTextState --- @return int function ImStb.TEXTEDIT_STRINGLEN(obj) return obj.TextLen end @@ -52680,7 +58892,7 @@ end --- @param obj ImGuiInputTextState --- @param idx int function ImStb.is_word_boundary_from_right(obj, idx) - -- When ImGuiInputTextFlags.Password is set, we don't want actions such as Ctrl+Arrow to leak the fact that underlying data are blanks or separators + -- When ImGuiInputTextFlags.Password is set, we don't want actions such as Ctrl+Arrow to leak the fact that underlying data are blanks or separators. if bit32.band(obj.Flags, ImGuiInputTextFlags.Password) ~= 0 or idx <= 1 then return false end @@ -52757,7 +58969,7 @@ function ImStb.TEXTEDIT_MOVEWORDRIGHT(obj, idx) end end --- Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping +-- Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping. --- @param obj ImGuiInputTextState --- @param state STB_TexteditState --- @param cursor int @@ -52834,6 +59046,7 @@ end --- @param pos int --- @param n int function ImStb.TEXTEDIT_DELETECHARS(obj, pos, n) + -- Offset remaining text (+ copy zero terminator) IM_ASSERT(obj.TextSrc == obj.TextA.Data) ImStd.memmove(obj.TextA.Data, pos, obj.TextA.Data, pos + n, obj.TextLen - n - pos + 2) obj.EditedBefore = true @@ -52851,10 +59064,10 @@ function ImStb.TEXTEDIT_INSERTCHARS(obj, pos, new_text, new_text_pos, new_text_l local text_len = obj.TextLen IM_ASSERT(pos <= text_len + 1) - -- We support partial insertion (with a mod in stb_textedit) + -- We support partial insertion (with a mod in stb_textedit.h) local avail = obj.BufCapacity - 1 - obj.TextLen if not is_resizable and new_text_len > avail then - new_text_len = math.floor(ImStd.ImTextFindValidUtf8CodepointEnd(new_text, new_text_pos, new_text_len + 1, avail) - new_text_pos) -- Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion + new_text_len = math.floor(ImStd.ImTextFindValidUtf8CodepointEnd(new_text, new_text_pos, new_text_len + 1, avail) - new_text_pos) -- Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion. end if new_text_len == 0 then return 0 @@ -52883,6 +59096,8 @@ end stbte = IM_INCLUDE"imstb_textedit.lua" +-- stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling +-- the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?) --- @param str ImGuiInputTextState --- @param state STB_TexteditState --- @param text IMSTB_TEXTEDIT_CHARTYPE[] @@ -52941,8 +59156,8 @@ function MT.ImGuiInputTextState:OnCharPressed(c) self:CursorAnimReset() end --- After a user-input the cursor stays on for a while without blinking -function MT.ImGuiInputTextState:CursorAnimReset() self.CursorAnim = -0.30 end +-- Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header. +function MT.ImGuiInputTextState:CursorAnimReset() self.CursorAnim = -0.30 end -- After a user-input the cursor stays on for a while without blinking function MT.ImGuiInputTextState:CursorClamp() self.Stb.cursor = ImMin(self.Stb.cursor, self.TextLen + 1) @@ -52987,6 +59202,7 @@ function ImGui.PopPasswordFont() IM_ASSERT(backup.IndexAdvanceX.Size == 0 and backup.IndexLookup.Size == 0) end +-- Return false to discard a character. Returns (char, ok). --- @param ctx ImGuiContext --- @param state ImGuiInputTextState --- @param char unsigned_int @@ -53127,7 +59343,7 @@ 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 +-- 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. --- @param state ImGuiInputTextState --- @param old_buf ImStringBuffer --- @param old_length int @@ -53170,6 +59386,10 @@ local function InputTextReconcileUndoState(state, old_buf, old_length, new_buf, end end +-- As InputText() retain textual data and we currently provide a path for user to not retain it (via local variables) +-- we need some form of hook to reapply data back to user buffer on deactivation frame. (#4714) +-- It would be more desirable that we discourage users from taking advantage of the "user not retaining data" trick, +-- but that more likely be attractive when we do have _NoLiveEdit flag available. --- @param id ImGuiID function ImGui.InputTextDeactivateHook(id) local g = GImGui @@ -53185,7 +59405,7 @@ function ImGui.InputTextDeactivateHook(id) g.InputTextDeactivatedState.ID = state.ID g.InputTextDeactivatedState.ElapseFrame = g.FrameCount + 1 if bit32.band(state.Flags, ImGuiInputTextFlags.ReadOnly) ~= 0 then - g.InputTextDeactivatedState.TextA:resize(0) -- In theory this data won't be used, but clear to be neat + g.InputTextDeactivatedState.TextA:resize(0) -- In theory this data won't be used, but clear to be neat. else IM_ASSERT(state.TextA.Data ~= nil) -- IM_ASSERT(state.TextA[state.TextLen + 1] == 0) @@ -53194,6 +59414,8 @@ function ImGui.InputTextDeactivateHook(id) end end +-- 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) --- @param flags ImGuiInputTextFlags --- @param line_index ImGuiTextIndex --- @param buf char[] @@ -53322,6 +59544,8 @@ local function InputTextLineIndexGetPosOffset(g, state, line_index, buf, buf_end end -- Edit a string of text +-- - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!". +-- - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect. --- @param label string --- @param hint? char[] --- @param buf char[] @@ -53352,9 +59576,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback IM_ASSERT(buf ~= nil and buf_size >= 0) IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.CallbackHistory) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Can't use both together (they both use up/down keys) IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.CallbackCompletion) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0)) -- Can't use both together (they both use tab key) - IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Multiline does not not work with left-trimming - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Password) == 0) -- WordWrap does not work with Password mode - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0) -- WordWrap does not work in single-line mode + IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Multiline does not work with left-trimming + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Password) == 0) -- WordWrap does not work with Password mode. + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0) -- WordWrap does not work in single-line mode. local g = GImGui --[[@as ImGuiContext]] local io = g.IO @@ -53391,18 +59615,18 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback ImGuiLastItemData_Copy(item_data_backup, g.LastItemData) ImVec2_Copy(window.DC.CursorPos, backup_pos) - -- Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping + -- Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping. if g.NavActivateId == id and (bit32.band(g.NavActivateFlags, ImGuiActivateFlags.FromTabbing) ~= 0) and (bit32.band(g.NavActivateFlags, ImGuiActivateFlags.FromFocusApi) == 0) and (bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0) then g.NavActivateId = 0 end - -- Prevent NavActivate reactivating in BeginChild() when we are already active + -- Prevent NavActivate reactivating in BeginChild() when we are already active. local backup_activate_id = g.NavActivateId if g.ActiveId == id then -- Prevent reactivation g.NavActivateId = 0 end - -- We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug + -- We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug. ImGui.PushStyleColor(ImGuiCol.ChildBg, style.Colors[ImGuiCol.FrameBg]) ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.FrameRounding) ImGui.PushStyleVar(ImGuiStyleVar.ChildBorderSize, style.FrameBorderSize) @@ -53417,7 +59641,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback return false end draw_window = g.CurrentWindow -- Child window - draw_window.DC.NavLayersActiveMaskNext = bit32.bor(draw_window.DC.NavLayersActiveMaskNext, bit32.lshift(1, draw_window.DC.NavLayerCurrent)) -- This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it + draw_window.DC.NavLayersActiveMaskNext = bit32.bor(draw_window.DC.NavLayersActiveMaskNext, bit32.lshift(1, draw_window.DC.NavLayerCurrent)) -- This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it. ImVec2_Copy(draw_window.DC.CursorPos, draw_window.DC.CursorPos + style.FramePadding) inner_size.x = inner_size.x - draw_window.ScrollbarSizes.x @@ -53426,6 +59650,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback g.LastItemData.ItemFlags = item_data_backup.ItemFlags g.LastItemData.StatusFlags = item_data_backup.StatusFlags else + -- Support for internal ImGuiInputTextFlags.MergedItem flag, which could be redesigned as an ItemFlags if needed (with test performed in ItemAdd) ImGui.ItemSize(total_bb, style.FramePadding.y) if bit32.band(flags, ImGuiInputTextFlags.TempInput) == 0 then @@ -53444,7 +59669,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback hovered = false end - -- We are only allowed to access the state if we are already the active widget + -- We are only allowed to access the state if we are already the active widget. local state = ImGui.GetInputTextState(id) if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.ReadOnly) ~= 0 then @@ -53479,8 +59704,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local scroll_y = is_multiline and draw_window.Scroll.y or FLT_MAX local init_reload_from_user_buf = (state ~= nil and state.WantReloadUserBuf) - local init_changed_specs_multiline = (state ~= nil and (state.Stb.single_line ~= (not is_multiline))) - local init_changed_specs_readonly = (state ~= nil and (bit32.band(bit32.bxor(state.Flags, flags), ImGuiInputTextFlags.ReadOnly) ~= 0)) -- state ~= nil means it's our state + local init_changed_specs_multiline = (state ~= nil and (state.Stb.single_line ~= (not is_multiline))) -- state ~= nil means its our state. + local init_changed_specs_readonly = (state ~= nil and (bit32.band(bit32.bxor(state.Flags, flags), ImGuiInputTextFlags.ReadOnly) ~= 0)) -- state ~= nil means its our state. local init_make_active = (input_requested_by_user or input_requested_by_nav or input_requested_by_reactivate or user_scroll_finish) if init_reload_from_user_buf then local new_len = ImStd.ImStrlen(buf) @@ -53488,14 +59713,14 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.WantReloadUserBuf = false --- @cast state ImGuiInputTextState InputTextReconcileUndoState(state, state.TextA.Data, state.TextLen, buf, new_len) - state.TextA:resize(buf_size + 1) + 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 ImStd.memmove(state.TextA.Data, 1, buf, 1, state.TextLen + 1) state.Stb.select_start = state.ReloadSelectionStart state.Stb.cursor = state.ReloadSelectionEnd state.Stb.select_end = state.ReloadSelectionEnd -- will be clamped to bounds below elseif (init_make_active and g.ActiveId ~= id) or init_changed_specs_multiline or init_changed_specs_readonly then - -- Access state even if we don't own it yet + -- Access state even if we don't own it yet. state = g.InputTextState state:CursorAnimReset() @@ -53509,7 +59734,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local buf_len = ImStd.ImStrlen(buf) IM_ASSERT(((buf_len + 1 <= buf_size) or (buf_len == 0 and buf_size == 0)), "Is your input buffer properly zero-terminated?") if not user_scroll_finish then - state.TextToRevertTo:resize(buf_len + 1) + 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. ImStd.memmove(state.TextToRevertTo.Data, 1, buf, 1, buf_len + 1) end @@ -53525,7 +59750,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.TextLen = buf_len state.EditedBefore = false if not is_readonly then - state.TextA:resize(buf_size + 1) + state.TextA:resize(buf_size + 1) -- we use +1 to make sure that .Data is always pointing to at least an empty string. ImStd.memmove(state.TextA.Data, 1, buf, 1, state.TextLen + 1) end @@ -53536,7 +59761,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end -- 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 + -- Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. if not recycle_state then stbte.initialize_state(state.Stb, not is_multiline) end @@ -53570,8 +59795,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end if g.ActiveId == id then - -- 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 combination into individual shortcuts + -- 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 combination into individual shortcuts. local always_owned_keys = { ImGuiKey.LeftArrow, ImGuiKey.RightArrow, ImGuiKey.Delete, ImGuiKey.Backspace, ImGuiKey.Home, ImGuiKey.End } for _, key in ipairs(always_owned_keys) do ImGui.SetKeyOwner(key, id) @@ -53630,7 +59855,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local value_changed = false local validated = false - -- Select the buffer to render + -- Select the buffer to render. local buf_display_from_state = (render_cursor or render_selection or g.ActiveId == id) and not is_readonly and state ~= nil local is_displaying_hint = (hint ~= nil and (buf_display_from_state and state.TextA.Data or buf)[1] == 0) @@ -53659,7 +59884,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback 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 + -- Down the line we should have a cleaner library-wide concept of Selected vs Active. g.ActiveIdAllowOverlap = not io.MouseDown[0] -- Edit in progress @@ -53690,7 +59915,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback else -- Triple-click: Select line local is_eol = ImStb.TEXTEDIT_GETCHAR(state, state.Stb.cursor) == 10 - state.WrapWidth = 0.0 -- Temporarily disable wrapping so we use real line start + state.WrapWidth = 0.0 -- Temporarily disable wrapping so we use real line start. state:OnKeyPressed(STB_TEXTEDIT_K_LINESTART) state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_LINEEND, STB_TEXTEDIT_K_SHIFT)) state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_RIGHT, STB_TEXTEDIT_K_SHIFT)) @@ -53720,6 +59945,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.SelectedAllMouseLock = false end + -- We expect backends to emit a Tab key but some also emit a Tab character which we ignore (#2467, #1336) + -- (For Tab and Enter: Win32/SFML/Allegro are sending both keys and chars, GLFW and SDL are only sending keys. For Space they all send all threes) if bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0 and not is_readonly then if ImGui.Shortcut(ImGuiKey.Tab, ImGuiInputFlags.Repeat, id) then local c = 9 -- Insert TAB @@ -53731,9 +59958,12 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end -- FIXME: Implement Shift+Tab + -- if ImGui.Shortcut(bit32.bor(ImGuiKey.Tab, ImGuiMod_Shift), ImGuiInputFlags.Repeat, id) then + -- end end - -- Process regular text input + -- Process regular text input (before we check for Return because using some IME will effectively send a Return?) + -- We ignore Ctrl inputs, but need to allow Alt+Ctrl as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. local ignore_char_inputs = io.KeyCtrl and not io.KeyAlt if io.InputQueueCharacters.Size > 0 then if not ignore_char_inputs and not is_readonly and not input_requested_by_nav then @@ -53741,7 +59971,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback repeat -- Insert character if they pass filtering local c = io.InputQueueCharacters[n] - if c == 9 then -- Skip Tab, see above + if c == 9 then -- Skip Tab, see above. break end @@ -53770,9 +60000,11 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.Stb.row_count_per_page = row_count_per_page local k_mask = (io.KeyShift and STB_TEXTEDIT_K_SHIFT or 0) - local is_wordmove_key_down = is_osx and io.KeyAlt or io.KeyCtrl - local is_startend_key_down = is_osx and io.KeyCtrl and not io.KeySuper and not io.KeyAlt + local is_wordmove_key_down = is_osx and io.KeyAlt or io.KeyCtrl -- OS X style: Text editing cursor movement using Alt instead of Ctrl + local is_startend_key_down = is_osx and io.KeyCtrl and not io.KeySuper and not 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: former would be handled by InputText) + -- Otherwise we could simply assume that we own the keys as we are active. local f_repeat = ImGuiInputFlags.Repeat local is_cut = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.X), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Shift, ImGuiKey.Delete), f_repeat, id)) and not is_readonly and not is_password and (not is_multiline or state:HasSelection()) local is_copy = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.C), 0, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Insert), 0, id)) and not is_password and (not is_multiline or state:HasSelection()) @@ -53781,6 +60013,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local is_redo = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Y), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Z), f_repeat, id)) and not is_readonly and is_undoable local is_select_all = ImGui.Shortcut(bit32.bor(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. local nav_gamepad_active = (bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0) and (bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0) local is_enter = ImGui.Shortcut(ImGuiKey.Enter, f_repeat, id) or ImGui.Shortcut(ImGuiKey.KeypadEnter, f_repeat, id) local is_ctrl_enter = ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Enter), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.KeypadEnter), f_repeat, id) @@ -53788,6 +60021,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local is_gamepad_validate = nav_gamepad_active and ImGui.IsKeyPressed(ImGuiKey.NavGamepadActivate, false) local is_cancel = ImGui.Shortcut(ImGuiKey.Escape, f_repeat, id) or (nav_gamepad_active and ImGui.Shortcut(ImGuiKey.NavGamepadCancel, f_repeat, id)) + -- FIXME: Should use more Shortcut() and reduce IsKeyPressed()+SetKeyOwner(), but requires modifiers combination to be taken account of. + -- FIXME-OSX: Missing support for Alt(option)+Right/Left = go to end of line, or next line if already in end of line. if ImGui.IsKeyPressed(ImGuiKey.LeftArrow) then state:OnKeyPressed(bit32.bor(is_startend_key_down and STB_TEXTEDIT_K_LINESTART or (is_wordmove_key_down and STB_TEXTEDIT_K_WORDLEFT or STB_TEXTEDIT_K_LEFT), k_mask)) elseif ImGui.IsKeyPressed(ImGuiKey.RightArrow) then @@ -53816,6 +60051,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state:OnKeyPressed(io.KeyCtrl and bit32.bor(STB_TEXTEDIT_K_TEXTEND, k_mask) or bit32.bor(STB_TEXTEDIT_K_LINEEND, k_mask)) elseif ImGui.IsKeyPressed(ImGuiKey.Delete) and not is_readonly and not is_cut then if not state:HasSelection() then + -- OSX doesn't seem to have Super+Delete to delete until end-of-line, so we don't emulate that (as opposed to Super+Backspace) if is_wordmove_key_down then state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_WORDRIGHT, STB_TEXTEDIT_K_SHIFT)) end @@ -53831,17 +60067,20 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_BACKSPACE, k_mask)) elseif is_enter or is_ctrl_enter or is_shift_enter or is_gamepad_validate then + -- Determine if we turn Enter into a \n character local ctrl_enter_for_new_line = bit32.band(flags, ImGuiInputTextFlags.CtrlEnterForNewLine) ~= 0 local is_new_line = is_multiline and not is_gamepad_validate and (is_shift_enter or (is_enter and not ctrl_enter_for_new_line) or (is_ctrl_enter and ctrl_enter_for_new_line)) if not is_new_line then validated = true clear_active_id = true if io.ConfigInputTextEnterKeepActive and not is_multiline and not is_ctrl_enter and not is_shift_enter then - state:SelectAll() - g.InputTextReactivateId = id + -- Queue reactivation, so that e.g. IsItemDeactivatedAfterEdit() will work. (#9001) + state:SelectAll() -- No need to scroll + g.InputTextReactivateId = id -- Mark for reactivation on next frame end elseif not is_readonly then - local c = 10 -- Insert new line + -- Insert new line + local c = 10 local ret2 c, ret2 = InputTextFilterCharacter(g, state, c, callback, callback_user_data) if ret2 then @@ -53870,7 +60109,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state:SelectAll() state.CursorFollow = true elseif is_cut or is_copy then + -- Cut, Copy if g.PlatformIO.Platform_SetClipboardTextFn ~= nil then + -- SetClipboardText() only takes null terminated strings + state.TextSrc may point to read-only user buffer, so we need to make a copy. local ib = state:HasSelection() and ImMin(state.Stb.select_start, state.Stb.select_end) or 1 local ie = state:HasSelection() and ImMax(state.Stb.select_start, state.Stb.select_end) or state.TextLen + 1 g.TempBuffer:reserve(ie - ib + 1) @@ -53888,6 +60129,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback elseif is_paste then local clipboard = ImGui.GetClipboardText() if clipboard then + -- Filter pasted buffer local clipboard_len = #clipboard local clipboard_end = clipboard_len + 1 local clipboard_filtered = ImVector() @@ -53914,7 +60156,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback until true end - if clipboard_filtered.Size > 0 then + if clipboard_filtered.Size > 0 then -- If everything was filtered, ignore the pasting operation clipboard_filtered:push_back(0) stbte.paste(state, state.Stb, clipboard_filtered.Data, clipboard_filtered.Size - 1) state.CursorFollow = true @@ -53922,6 +60164,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end + -- Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame. render_selection = render_selection or (state:HasSelection() and (RENDER_SELECTION_WHEN_INACTIVE or render_cursor)) end @@ -53934,6 +60177,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback if revert_edit and not is_readonly then if bit32.band(flags, ImGuiInputTextFlags.EscapeClearsAll) ~= 0 then + -- Clear input IM_ASSERT(state.TextA.Data[1] ~= 0) apply_new_text = {0} apply_new_text_length = 0 @@ -53944,14 +60188,19 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback 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 ImStb.stb_textedit_replace(state, state.Stb, state.TextToRevertTo.Data, state.TextToRevertTo.Size - 1) end end + -- User callback if bit32.band(flags, bit32.bor(ImGuiInputTextFlags.CallbackCompletion, ImGuiInputTextFlags.CallbackHistory, ImGuiInputTextFlags.CallbackEdit, ImGuiInputTextFlags.CallbackAlways)) ~= 0 then IM_ASSERT(callback ~= nil) + -- The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. + local event_flag = 0 local event_key = ImGuiKey.None if bit32.band(flags, ImGuiInputTextFlags.CallbackCompletion) ~= 0 and ImGui.Shortcut(ImGuiKey.Tab, 0, id) then @@ -53978,6 +60227,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback callback_data.EventActivated = (g.ActiveId == state.ID and g.ActiveIdIsJustActivated) callback_data.UserData = callback_user_data + -- FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925 local callback_buf = is_readonly and buf or state.TextA.Data IM_ASSERT(callback_buf == state.TextSrc) state.CallbackTextBackup:resize(state.TextLen + 1) @@ -53992,10 +60242,12 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback callback_data.SelectionStart = state.Stb.select_start callback_data.SelectionEnd = state.Stb.select_end + -- Call user code callback(callback_data) - callback_buf = is_readonly and buf or state.TextA.Data - IM_ASSERT(callback_data.Buf == callback_buf) + -- Read back what user may have modified + callback_buf = is_readonly and buf or 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.BufCapacity) IM_ASSERT(callback_data.Flags == flags) if callback_data.BufDirty or callback_data.CursorPos ~= state.Stb.cursor then @@ -54005,15 +60257,18 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.Stb.select_start = ImClamp(callback_data.SelectionStart, 0, callback_data.BufTextLen) state.Stb.select_end = ImClamp(callback_data.SelectionEnd, 0, callback_data.BufTextLen) if callback_data.BufDirty then - IM_ASSERT(callback_data.BufTextLen == ImStd.ImStrlen(callback_data.Buf)) + -- Callback may update buffer and thus set buf_dirty even in read-only mode. + IM_ASSERT(callback_data.BufTextLen == ImStd.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 + state.TextLen = callback_data.BufTextLen -- Assume correct length and valid UTF-8 from user, saves us an extra strlen() state.EditedBefore = true; state.EditedThisFrame = true state:CursorAnimReset() end end end + -- Write back result string if modified. + -- FIXME-OPT: Could mark dirty state from the stb_textedit callbacks if not is_readonly then if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0 then -- Apply when modified @@ -54031,6 +60286,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end + -- Handle reapplying final data on deactivation (see InputTextDeactivateHook() for details) + -- This is used when e.g. losing focus or tabbing out into another InputText() which may already be using the temp buffer. if g.InputTextDeactivatedState.ID == id then -- The state only exists after an Edit. IsItemDeactivatedAfterEdit() is not valid in every code path (see "widgets_inputtext_status_noliveedit" test). if ((g.ActiveId ~= id and ImGui.IsItemDeactivated()) or (g.ActiveId == id and bit32.band(flags, ImGuiInputTextFlags.TempInput) ~= 0)) then @@ -54044,6 +60301,12 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback g.InputTextDeactivatedState.ID = 0 end + -- Write back result to user buffer. This can currently only happen when (g.ActiveId == id) or when just deactivated. + -- - As soon as the InputText() is active, our stored in-widget value gets priority over any underlying modification of the user buffer. + -- - Make sure we always reapply the live buffer back to the input/user buffer before clearing ActiveId, even thought strictly speaking + -- it was not modified on this frame. This allows the user to use InputText() without maintaining any user-side storage. + -- (PS: if you use this property together with ImGuiInputTextFlags.CallbackResize, you are at the risk of recreating a temporary + -- allocated/string object every frame. Which in the grand scheme of scheme is nothing, but isn't dear imgui vibe). if apply_new_text ~= nil then IM_ASSERT(apply_new_text_length >= 0) if is_resizable then @@ -54065,7 +60328,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1) IM_ASSERT(apply_new_text_length <= buf_size) end + -- IMGUI_DEBUG_PRINT("InputText(\"%s\"): apply_new_text length %d\n", label, apply_new_text_length); + -- If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size. ImStd.ImStrncpy(buf, 1, apply_new_text, 1, ImMin(apply_new_text_length + 1, buf_size)) end @@ -54117,7 +60382,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback if render_cursor or render_selection or g.ActiveId == id then buf_display_end = state.TextLen + 1 elseif is_multiline and not is_wordwrap then - buf_display_end = nil -- Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path + buf_display_end = nil -- Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path. else buf_display_end = ImStd.ImStrlen(buf_display) + 1 end @@ -54129,10 +60394,13 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize) end + -- Build line index for easy data access (makes code below simpler and faster) local line_index = g.InputTextLineIndex line_index.Offsets:resize(0) local line_count = 1 if is_multiline then + -- If scrolling is expected to change build full index. + -- FIXME-OPT: Could append to index when new value of line_visible_n1 becomes bigger, see second call to CalcClipRectVisibleItemsY() below. local will_scroll_y = state and ((state.CursorFollow and render_cursor) or (state.CursorCenterY and (render_cursor or render_selection))) --- @cast buf_display_end int local out_buf_end @@ -54144,19 +60412,32 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback line_index.EndOffset = buf_display_end - 1 line_visible_n1 = ImMin(line_visible_n1, line_count + 1) + -- Store text height (we don't need width) local text_size_y = line_count * g.FontSize + -- ImGui.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 --- @cast buf_display_end int local cursor_offset = (render_cursor and state) and InputTextLineIndexGetPosOffset(g, state, line_index, buf_display, buf_display_end, state.Stb.cursor) or ImVec2(0.0, 0.0) local draw_scroll = ImVec2() + -- Render text. We currently only render selection when the widget is active or while scrolling. local text_col = ImGui.GetColorU32(is_displaying_hint and ImGuiCol.TextDisabled or ImGuiCol.Text) if render_cursor or render_selection then + -- 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) + -- - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) + -- - 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. IM_ASSERT(state ~= nil) state.LineCount = line_count + -- Scroll local new_scroll_y = scroll_y if render_cursor and state.CursorFollow then + -- Horizontal scroll in chunks of quarter width if bit32.band(flags, ImGuiInputTextFlags.NoHorizontalScroll) == 0 then local scroll_increment_x = inner_size.x * 0.25 local visible_width = inner_size.x - style.FramePadding.x @@ -54169,7 +60450,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.Scroll.x = 0.0 end + -- Vertical scroll if is_multiline then + -- Test if cursor is vertically visible if cursor_offset.y - g.FontSize < scroll_y then new_scroll_y = ImMax(0.0, cursor_offset.y - g.FontSize) elseif cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0) >= scroll_y then @@ -54188,18 +60471,19 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback if new_scroll_y ~= scroll_y then local scroll_max_y = ImMax((text_size_y + style.FramePadding.y * 2.0) - inner_size.y, 0.0) scroll_y = ImClamp(new_scroll_y, 0.0, scroll_max_y) - draw_pos.y = draw_pos.y + (draw_window.Scroll.y - scroll_y) + draw_pos.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 line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize) line_visible_n1 = ImMin(line_visible_n1, line_count) end + -- Draw selection draw_scroll.x = state.Scroll.x if render_selection then - local bg_color = ImGui.GetColorU32(ImGuiCol.TextSelectedBg, render_cursor and 1.0 or 0.6) - local bg_offy_up = is_multiline and 0.0 or -1.0 + local bg_color = ImGui.GetColorU32(ImGuiCol.TextSelectedBg, render_cursor and 1.0 or 0.6) -- FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. + local bg_offy_up = is_multiline and 0.0 or -1.0 -- FIXME-DPI: those offsets should be part of the style? they don't play so well with multi-line selection. local bg_offy_dn = is_multiline and 0.0 or 2.0 - local bg_eol_width = IM_TRUNC(g.FontBaked:GetCharAdvance(32) * 0.50) + local bg_eol_width = IM_TRUNC(g.FontBaked:GetCharAdvance(32) * 0.50) -- So we can see selected empty lines local text_selected_begin = ImMin(state.Stb.select_start, state.Stb.select_end) local text_selected_end = ImMax(state.Stb.select_start, state.Stb.select_end) @@ -54219,7 +60503,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback rect_width = rect_width + ImGui.CalcTextSizeEx(buf_display, line_selected_begin, line_selected_end).x end if text_selected_begin <= p_eol and text_selected_end > p_eol and not p_eol_is_wrap then - rect_width = rect_width + bg_eol_width + rect_width = rect_width + bg_eol_width -- So we can see selected empty lines end if rect_width == 0.0 then break @@ -54239,10 +60523,13 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end + -- Find render position for right alignment (single-line only) if g.ActiveId ~= id and bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and not render_cursor and not render_selection then draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - ImGui.CalcTextSize(buf_display, nil).x - style.FramePadding.x) end + -- draw_scroll.x = state.Scroll.x -- Preserve scroll when inactive? + -- Render text if (is_multiline or (buf_display_end - 1) < buf_display_max_length) and bit32.band(text_col, IM_COL32_A_MASK) ~= 0 and line_visible_n0 < line_visible_n1 then g.Font:RenderText(draw_window.DrawList, g.FontSize, draw_pos - draw_scroll + ImVec2(0.0, (line_visible_n0 - 1) * g.FontSize), @@ -54253,6 +60540,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback wrap_width, bit32.bor(ImDrawTextFlags.WrapKeepBlanks, ImDrawTextFlags.CpuFineClip)) end + -- Render blinking cursor if render_cursor then state.CursorAnim = state.CursorAnim + io.DeltaTime local cursor_is_visible = (not g.IO.ConfigInputTextCursorBlink) or (state.CursorAnim <= 0.0) or (ImFmod(state.CursorAnim, 1.20) <= 0.80) @@ -54264,8 +60552,11 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback draw_window.DrawList:AddLineV(cursor_screen_rect.Min.x, cursor_screen_rect.Min.y, cursor_screen_rect.Max.y, ImGui.GetColorU32(ImGuiCol.InputTextCursor), style.InputTextCursorSize) end + -- 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 not is_readonly and g.ActiveId == id then - local ime_data = g.PlatformImeData + local ime_data = g.PlatformImeData -- (this is a public struct, passed to io.Platform_SetImeDataFn() handler) ime_data.WantVisible = true ime_data.WantTextInput = true ImVec2_Copy(ime_data.InputPos, ImVec2(cursor_screen_pos.x - 1.0, cursor_screen_pos.y - g.FontSize)) @@ -54324,13 +60615,23 @@ end function ImGui.InputTextWithHint(label, hint, buf, buf_size, flags, callback, user_data) if flags == nil then flags = 0 end - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) -- call InputTextMultiline() or InputTextEx() manually if you need multi-line + hint. return ImGui.InputTextEx(label, hint, buf, buf_size, ImVec2(0, 0), flags, callback, user_data) end ----------------------------------------------------------------- --- [SECTION] COLOR EDIT / PICKER ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +------------------------------------------------------------------------------- +-- - ColorEdit3() +-- - ColorEdit4() +-- - ColorPicker3() +-- - RenderColorRectWithAlphaCheckerboard() [Internal] +-- - ColorPicker4() +-- - ColorButton() +-- - ColorTooltip() [Internal] +-- - ColorEditOptionsPopup() [Internal] +-- - ColorPickerOptionsPopup() [Internal] +------------------------------------------------------------------------------- --- @param col float[] --- @param H float @@ -54345,6 +60646,8 @@ local function ColorEditRestoreH(col, H) return H end +-- ColorEdit supports RGB and HSV inputs. In case of RGB input resulting color may have undefined hue and/or saturation. +-- Since widget displays both RGB and HSV values we must preserve hue and saturation to prevent these values resetting. --- @param col float[] --- @param H float --- @param S float @@ -54386,6 +60689,9 @@ local fmt_table_float = { { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } -- Long display for HSVA } +-- 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. --- @param label string --- @param col float[] --- @param flags ImGuiColorEditFlags @@ -54487,6 +60793,7 @@ function ImGui.ColorEdit4(label, col, flags) window.DC.CursorPos.x = pos.x + inputs_offset_x if bit32.band(flags, bit32.bor(ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.DisplayHSV)) ~= 0 and bit32.band(flags, ImGuiColorEditFlags.NoInputs) == 0 then + -- RGB/HSV 0..255 Sliders local w_items = w_inputs - style.ItemInnerSpacing.x * (components - 1) local w_per_component = IM_TRUNC(w_items / components) local draw_color_marker = bit32.band(flags, bit32.bor(ImGuiColorEditFlags.DisplayHSV, ImGuiColorEditFlags.NoColorMarkers)) == 0 @@ -54514,7 +60821,7 @@ function ImGui.ColorEdit4(label, col, flags) ImGui.SetNextItemColorMarker(GDefaultRgbaColorMarkers[n]) end - -- FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0 + -- FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0. if bit32.band(flags, ImGuiColorEditFlags.Float) ~= 0 then local changed f[n], changed = ImGui.DragFloat(ids[n], f[n], 1.0 / 255.0, 0.0, hdr and 0.0 or 1.0, fmt_table_float[fmt_idx][n], drag_flags) @@ -54552,15 +60859,15 @@ function ImGui.ColorEdit4(label, col, flags) p = p + 1 end i[1], i[2], i[3] = 0, 0, 0 - i[4] = 0xFF + i[4] = 0xFF -- alpha default to 255 is not parsed by scanf (e.g. inputting #FFFFFF omitting alpha) local r if alpha then - r = ImStd.sscanf(buf, p, "%02X%02X%02X%02X", i) + r = ImStd.sscanf(buf, p, "%02X%02X%02X%02X", i) -- Treat at unsigned (%X is unsigned) else r = ImStd.sscanf(buf, p, "%02X%02X%02X", i) end - -- IM_UNUSED(r) + -- IM_UNUSED(r) -- Fixes C6031: Return value ignored: 'sscanf'. end if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then @@ -54604,7 +60911,7 @@ function ImGui.ColorEdit4(label, col, flags) if label ~= "" and label_display_end > 1 and bit32.band(flags, ImGuiColorEditFlags.NoLabel) == 0 then -- Position not necessarily next to last submitted button (e.g. if style.ColorButtonPosition == ImGuiDir_Left), - -- but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this + -- but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this. ImGui.SameLine(0.0, style.ItemInnerSpacing.x) window.DC.CursorPos.x = pos.x + ((bit32.band(flags, ImGuiColorEditFlags.NoInputs) ~= 0) and w_button or (w_full + style.ItemInnerSpacing.x)) ImGui.TextEx(label, label_display_end) @@ -54645,7 +60952,7 @@ function ImGui.ColorEdit4(label, col, flags) -- Drag and Drop Target -- TODO: - -- When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4() + -- When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4(). if picker_active_window and g.ActiveId ~= 0 and g.ActiveIdWindow == picker_active_window then g.LastItemData.ID = g.ActiveId end @@ -54680,6 +60987,7 @@ function ImGui.ColorPicker3(label, col, flags) return true end +-- This allowed passing 0 to set default, whereas NewFrame() will assert if one of missing. Abide to old logic. function ImGui.SetColorEditOptions(flags) local g = GImGui local def = ImGuiColorEditFlags.DefaultOptions_ @@ -54709,6 +61017,9 @@ do --[[ColorPicker4]] local backup_initial_col = {0, 0, 0, 0} +-- Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags.NoAlpha flag is set. +-- FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) +-- FIXME: this is trying to be aware of style.Alpha but not fully correct. Also, the color wheel will have overlapping glitches with (style.Alpha < 1.0) --- @param label string --- @param col float[] --- @param flags ImGuiColorEditFlags @@ -54774,8 +61085,8 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) local picker_pos = ImVec2() ImVec2_Copy(picker_pos, window.DC.CursorPos) local square_sz = ImGui.GetFrameHeight() - local bars_width = square_sz -- Arbitrary smallish width of Hue/Alpha picking bars - local sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar and 2 or 1) * (bars_width + style.ItemInnerSpacing.x)) -- Saturation/Value picking box + local bars_width = square_sz -- Arbitrary smallish width of Hue/Alpha picking bars + local sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar and 2 or 1) * (bars_width + style.ItemInnerSpacing.x)) -- Saturation/Value picking box local bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x local bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x local bars_triangles_half_sz = IM_TRUNC(bars_width * 0.20) @@ -54791,9 +61102,9 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) local triangle_rotate = bit32.band(flags, ImGuiColorEditFlags.PickerNoRotate) == 0 local triangle_r = wheel_r_inner - math.floor(sv_picker_size * 0.027) local triangle_pa, triangle_pb, triangle_pc - if triangle_rotate then triangle_pa = ImVec2( triangle_r, 0.0) else triangle_pa = ImVec2( triangle_r * 0.866, triangle_r * 0.5) end -- Hue point - if triangle_rotate then triangle_pb = ImVec2(triangle_r * -0.5, triangle_r * -0.866) else triangle_pb = ImVec2( 0.0, -triangle_r) end -- Black point - if triangle_rotate then triangle_pc = ImVec2(triangle_r * -0.5, triangle_r * 0.866) else triangle_pc = ImVec2(triangle_r * -0.866, triangle_r * 0.5) end -- White point + if triangle_rotate then triangle_pa = ImVec2( triangle_r, 0.0) else triangle_pa = ImVec2( triangle_r * 0.866, triangle_r * 0.5) end -- Hue point. + if triangle_rotate then triangle_pb = ImVec2(triangle_r * -0.5, triangle_r * -0.866) else triangle_pb = ImVec2( 0.0, -triangle_r) end -- Black point. + if triangle_rotate then triangle_pc = ImVec2(triangle_r * -0.5, triangle_r * 0.866) else triangle_pc = ImVec2(triangle_r * -0.866, triangle_r * 0.5) end -- White point. local H = col[1]; local S = col[2]; local V = col[3] local R = col[1]; local G = col[2]; local B = col[3] @@ -54853,7 +61164,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) if ImGui.IsItemActive() and not is_readonly then S = ImSaturate((io.MousePos.x - picker_pos.x) / ImMax(sv_picker_size - 1, 0.0001)) V = 1.0 - ImSaturate((io.MousePos.y - picker_pos.y) / ImMax(sv_picker_size - 1, 0.0001)) - H = ColorEditRestoreH(col, H) -- Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square. + H = ColorEditRestoreH(col, H) -- Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square. value_changed = true value_changed_sv = true end @@ -54881,7 +61192,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) value_changed = true end end - ImGui.PopItemFlag() + ImGui.PopItemFlag() -- ImGuiItemFlags.NoNav if bit32.band(flags, ImGuiColorEditFlags.NoSidePreview) == 0 then ImGui.SameLine(0, style.ItemInnerSpacing.x) @@ -55071,8 +61382,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) draw_list:AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black) ImGui.RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0) - -- Sneakily prevent the circle to stick out too much - sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2) + sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2) -- Sneakily prevent the circle to stick out too much sv_cursor_pos.y = ImClamp(IM_ROUND(picker_pos.y + ImSaturate(1 - V) * sv_picker_size), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2) -- Render Hue Bar @@ -55087,7 +61397,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) -- Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range) local sv_cursor_rad = value_changed_sv and (wheel_thickness * 0.55) or (wheel_thickness * 0.40) - local sv_cursor_segments = draw_list:_CalcCircleAutoSegmentCount(sv_cursor_rad) -- Lock segment count so the +1 one matches others. + local sv_cursor_segments = draw_list:_CalcCircleAutoSegmentCount(sv_cursor_rad) -- Lock segment count so the +1 one matches others. draw_list:AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, sv_cursor_segments) draw_list:AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, sv_cursor_segments) draw_list:AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, sv_cursor_segments) @@ -55132,6 +61442,10 @@ end end +-- A little color square. Return true when clicked. +-- FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. +-- 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. +-- Note that 'col' may be encoded in HSV if ImGuiColorEditFlags.InputHSV is set. --- @param desc_id string --- @param col ImVec4 --- @param flags? ImGuiColorEditFlags @@ -55186,6 +61500,7 @@ function ImGui.ColorButton(desc_id, col, flags, size_arg) end window.DrawList:AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), ImGui.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 local col_source = (bit32.band(flags, ImGuiColorEditFlags.AlphaOpaque) ~= 0) and col_rgb_without_alpha or col_rgb if col_source.w < 1.0 and bit32.band(flags, ImGuiColorEditFlags.AlphaNoBg) == 0 then ImGui.RenderColorRectWithAlphaCheckerboard(window.DrawList, bb_inner.Min, bb_inner.Max, ImGui.GetColorU32(col_source), grid_step, ImVec2(off, off), rounding) @@ -55198,7 +61513,7 @@ function ImGui.ColorButton(desc_id, col, flags, size_arg) if g.Style.FrameBorderSize > 0.0 then ImGui.RenderFrameBorder(bb.Min, bb.Max, rounding) else - window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), rounding) + window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), rounding) -- Color buttons are often in need of some sort of border end end @@ -55224,6 +61539,7 @@ function ImGui.ColorButton(desc_id, col, flags, size_arg) return pressed end +-- Note: only access 3 floats if ImGuiColorEditFlags.NoAlpha flag is set. --- @param text? string --- @param col ImVec4 --- @param flags ImGuiColorEditFlags @@ -55361,6 +61677,7 @@ function ImGui.ColorPickerOptionsPopup(ref_col, flags) local picker_size = ImVec2(g.FontSize * 8, ImMax(g.FontSize * 8 - (ImGui.GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0)) -- FIXME: Picker size copied from main picker function ImGui.PushItemWidth(picker_size.x) for picker_type = 0, 1 do + -- Draw small/thumbnail version of each picker type (over an invisible button for selection) if picker_type > 0 then ImGui.Separator() end @@ -55373,8 +61690,7 @@ function ImGui.ColorPickerOptionsPopup(ref_col, flags) picker_flags = bit32.bor(picker_flags, ImGuiColorEditFlags.PickerHueWheel) end local backup_pos = ImGui.GetCursorScreenPos() - -- By default, Selectable() is closing popup - if ImGui.Selectable("##selectable", false, 0, picker_size) then + if ImGui.Selectable("##selectable", false, 0, picker_size) then -- By default, Selectable() is closing popup g.IO.ConfigColorEditFlags = bit32.bor(bit32.band(g.IO.ConfigColorEditFlags, bit32.bnot(ImGuiColorEditFlags.PickerMask_)), bit32.band(picker_flags, ImGuiColorEditFlags.PickerMask_)) end ImGui.SetCursorScreenPos(backup_pos) @@ -55397,9 +61713,21 @@ function ImGui.ColorPickerOptionsPopup(ref_col, flags) ImGui.EndPopup() end ----------------------------------------------------------------- --- [SECTION] TREES ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +------------------------------------------------------------------------------- +-- - TreeNode() +-- - TreeNodeV() +-- - TreeNodeEx() +-- - TreeNodeExV() +-- - TreeNodeStoreStackData() [Internal] +-- - TreeNodeBehavior() [Internal] +-- - TreePush() +-- - TreePop() +-- - GetTreeNodeToLabelSpacing() +-- - SetNextItemOpen() +-- - CollapsingHeader() +------------------------------------------------------------------------------- -- va_list variants: identical in Lua (varargs) ImGui.TextColoredV = function(...) return ImGui.TextColored(...) end @@ -55463,6 +61791,8 @@ function ImGui.TreeNodeExV(str_id, flags, fmt, ...) return ImGui.TreeNodeBehavior(id, flags, label, #label + 1) end +-- The reason those two functions are not yet in public API is because I would like to design a more feature-full and generic API for this. +-- They are otherwise function (cc: #3823, #9251, #7553, #6754, #5423, #2958, #2079, #1947, #1131, #722) --- @param storage_id ImGuiID function ImGui.TreeNodeGetOpen(storage_id) local g = GImGui @@ -55481,10 +61811,12 @@ end --- @param storage_id ImGuiID --- @param flags ImGuiTreeNodeFlags function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) + -- Leaf node always open a new tree/id scope. If you never use it, add ImGuiTreeNodeFlags.NoTreePushOnOpen. if bit32.band(flags, ImGuiTreeNodeFlags.Leaf) ~= 0 then return true end + -- We only write to the tree storage if the user clicks, or explicitly use the SetNextItemOpen function local g = GImGui local window = g.CurrentWindow local storage = window.DC.StateStorage @@ -55495,6 +61827,7 @@ function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) is_open = g.NextItemData.OpenVal ImGui.TreeNodeSetOpen(storage_id, is_open) else + -- We treat ImGuiCond.Once and ImGuiCond.FirstUseEver the same because tree node state are not saved persistently. local stored_value = storage[storage_id] if stored_value == nil then is_open = g.NextItemData.OpenVal @@ -55507,6 +61840,8 @@ function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) is_open = (storage[storage_id] == nil) and (bit32.band(flags, ImGuiTreeNodeFlags.DefaultOpen) ~= 0) or storage[storage_id] end + -- When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). + -- NB- If we are above max depth we still allow manually opened nodes to be logged. if g.LogEnabled and bit32.band(flags, ImGuiTreeNodeFlags.NoAutoOpenOnLog) == 0 and (window.DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand then is_open = true end @@ -55514,6 +61849,8 @@ function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) return is_open end +-- Store ImGuiTreeNodeStackData for just submitted node. +-- Currently only supports 32 level deep. Easy to increase to e.g. 64. --- @param flags ImGuiTreeNodeFlags --- @param x1 float local function TreeNodeStoreStackData(flags, x1) @@ -55527,6 +61864,7 @@ local function TreeNodeStoreStackData(flags, x1) tree_node_data.ItemFlags = g.LastItemData.ItemFlags ImRect_Copy(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. local draw_lines = bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DrawLinesToNodes)) ~= 0 tree_node_data.DrawLinesX1 = draw_lines and (x1 + g.FontSize * 0.5 + g.Style.FramePadding.x) or FLT_MAX tree_node_data.DrawLinesTableColumn = (draw_lines and g.CurrentTable) and g.CurrentTable.CurrentColumn or -1 @@ -55551,6 +61889,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local g = GImGui local style = g.Style + -- When not framed, we vertically increase height up to typical framed widget height local display_frame = bit32.band(flags, ImGuiTreeNodeFlags.Framed) ~= 0 local use_frame_padding = display_frame or (bit32.band(flags, ImGuiTreeNodeFlags.FramePadding) ~= 0) local padding @@ -55565,9 +61904,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end local label_size = ImGui.CalcTextSize(label, label_end, false) - local text_offset_x = g.FontSize + (display_frame and (padding.x * 3) or (padding.x * 2)) - local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset - local text_width = g.FontSize + label_size.x + padding.x * 2 + local text_offset_x = g.FontSize + (display_frame and (padding.x * 3) or (padding.x * 2)) -- Collapsing arrow width + Spacing + local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset -- Latch before ItemSize changes it + local text_width = g.FontSize + label_size.x + padding.x * 2 -- Include collapsing arrow local frame_height = label_size.y + padding.y * 2 local span_all_columns = bit32.band(flags, ImGuiTreeNodeFlags.SpanAllColumns) ~= 0 and (g.CurrentTable ~= nil) @@ -55578,7 +61917,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) frame_bb.Max.x = span_all_columns and window.ParentWorkRect.Max.x or (bit32.band(flags, ImGuiTreeNodeFlags.SpanLabelWidth) ~= 0 and window.DC.CursorPos.x + text_width + padding.x or window.WorkRect.Max.x) frame_bb.Max.y = window.DC.CursorPos.y + (text_offset_y - padding.y) + frame_height if display_frame then - local outer_extend = IM_TRUNC(window.WindowPadding.x * 0.5) + local outer_extend = IM_TRUNC(window.WindowPadding.x * 0.5) -- Framed header expand a little outside of current limits frame_bb.Min.x = frame_bb.Min.x - outer_extend frame_bb.Max.x = frame_bb.Max.x + outer_extend end @@ -55586,17 +61925,20 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local text_pos = ImVec2(window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y) ImGui.ItemSize(ImVec2(text_width, frame_height), padding.y) + -- For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing local interact_bb = ImRect() ImRect_Copy(interact_bb, frame_bb) if bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.Framed, ImGuiTreeNodeFlags.SpanAvailWidth, ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.SpanLabelWidth, ImGuiTreeNodeFlags.SpanAllColumns)) == 0 then interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0 and (style.ItemSpacing.x * 2.0) or 0.0) end + -- Compute open and multi-select states before ItemAdd() as it clear NextItem data. local storage_id = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasStorageID) ~= 0) and g.NextItemData.StorageId or id local is_open = ImGui.TreeNodeUpdateNextOpen(storage_id, flags) local is_visible if span_all_columns or span_all_columns_label then + -- Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. local backup_clip_rect_min_x = window.ClipRect.Min.x local backup_clip_rect_max_x = window.ClipRect.Max.x window.ClipRect.Min.x = window.ParentWorkRect.Min.x @@ -55610,6 +61952,10 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasDisplayRect) ImRect_Copy(g.LastItemData.DisplayRect, frame_bb) + -- 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.NavLeftJumpsToParent by default or move it to ImGuiStyle. local store_tree_node_stack_data = false if bit32.band(flags, ImGuiTreeNodeFlags.DrawLinesMask_) == 0 then flags = bit32.bor(flags, g.Style.TreeLinesFlags) @@ -55628,13 +61974,13 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) if not is_visible then if bit32.band(flags, ImGuiTreeNodeFlags.DrawLinesToNodes) ~= 0 and bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.lshift(1, (window.DC.TreeDepth - 1))) ~= 0 then local parent_data = g.TreeNodeStack.Data[g.TreeNodeStack.Size] - parent_data.DrawLinesToNodesY2 = ImMax(parent_data.DrawLinesToNodesY2, window.DC.CursorPos.y) + 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 then - window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(bit32.lshift(1, (window.DC.TreeDepth - 1)))) + window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(bit32.lshift(1, (window.DC.TreeDepth - 1)))) -- Done end end if is_open and store_tree_node_stack_data then - TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) -- Call before TreePushOverrideID() end if is_open and bit32.band(flags, ImGuiTreeNodeFlags.NoTreePushOnOpen) == 0 then ImGui.TreePushOverrideID(id) @@ -55657,15 +62003,27 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnDragDropHold) end + -- We allow clicking on the arrow section with keyboard modifiers held, in order to easily + -- allow browsing a tree while preserving selection with code implementing multi-selection patterns. + -- When clicking on the rest of the tree node we always disallow keyboard modifiers. local arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x local arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0) + style.TouchExtraPadding.x local is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 and g.IO.MousePos.x < arrow_hit_x2) local is_multi_select = bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0 - if is_multi_select then + if is_multi_select then -- We absolutely need to distinguish open vs select so _OpenOnArrow comes by default flags = bit32.bor(flags, (bit32.band(flags, ImGuiTreeNodeFlags.OpenOnMask_) == 0) and bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick) or ImGuiTreeNodeFlags.OpenOnArrow) end + -- Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags. + -- Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support. + -- - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0) + -- - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0) + -- - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1) + -- - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1) + -- - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0) + -- It is rather standard that arrow click react on Down rather than Up. + -- We set ImGuiButtonFlags.PressedOnClickRelease on OpenOnDoubleClick because we want the item to be active on the initial MouseDown in order for drag and drop to work. if is_mouse_x_over_arrow then button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClick) elseif bit32.band(flags, ImGuiTreeNodeFlags.OpenOnDoubleClick) ~= 0 then @@ -55680,7 +62038,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local selected = bit32.band(flags, ImGuiTreeNodeFlags.Selected) ~= 0 local was_selected = selected + -- Multi-selection support (header) if is_multi_select then + -- Handle multi-select + alter button flags for it selected, button_flags = ImGui.MultiSelectItemHeader(id, selected, button_flags) if is_mouse_x_over_arrow then button_flags = bit32.band(bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClick), bit32.bnot(ImGuiButtonFlags.PressedOnClickRelease)) @@ -55696,20 +62056,20 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) if not is_leaf then if pressed and g.DragDropHoldJustPressedId ~= id then if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnMask_) == 0 or (g.NavActivateId == id and not is_multi_select) then - toggled = true + toggled = true -- Single click end if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnArrow) ~= 0 then - toggled = toggled or (is_mouse_x_over_arrow and not g.NavHighlightItemUnderNav) + toggled = toggled or (is_mouse_x_over_arrow and not g.NavHighlightItemUnderNav) -- Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job end if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnDoubleClick) ~= 0 and g.IO.MouseClickedCount[0] == 2 then - toggled = true + toggled = true -- Double click end elseif pressed and g.DragDropHoldJustPressedId == id then IM_ASSERT(bit32.band(button_flags, ImGuiButtonFlags.PressedOnDragDropHold) ~= 0) - if not is_open then + if not is_open then -- When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again. toggled = true else - pressed = false + pressed = false -- Cancel press so it doesn't trigger selection. end end @@ -55718,7 +62078,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavMoveRequestCancel() end - if g.NavId == id and g.NavMoveDir == ImGuiDir.Right and not is_open then + if g.NavId == id and g.NavMoveDir == ImGuiDir.Right and not is_open then -- If there's something upcoming on the line we may want to give it the priority? toggled = true ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavMoveRequestCancel() @@ -55731,6 +62091,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end end + -- Multi-selection support (footer) if is_multi_select then local pressed_copy = pressed and not toggled selected, pressed_copy = ImGui.MultiSelectItemFooter(id, selected, pressed_copy) @@ -55748,9 +62109,10 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local text_col = ImGui.GetColorU32(ImGuiCol.Text) local nav_render_cursor_flags = ImGuiNavRenderCursorFlags.Compact if is_multi_select then - nav_render_cursor_flags = bit32.bor(nav_render_cursor_flags, ImGuiNavRenderCursorFlags.AlwaysDraw) + nav_render_cursor_flags = bit32.bor(nav_render_cursor_flags, ImGuiNavRenderCursorFlags.AlwaysDraw) -- Always show the nav rectangle end if display_frame then + -- Framed type local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header)) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding) ImGui.RenderNavCursor(frame_bb, id, nav_render_cursor_flags) @@ -55761,7 +62123,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col) elseif not is_leaf then ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 1.0) - else + else -- Leaf without bullet, left-adjusted text text_pos.x = text_pos.x - (text_offset_x - padding.x) end if bit32.band(flags, ImGuiTreeNodeFlags.ClipLabelForTrailingButton) ~= 0 then @@ -55771,6 +62133,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) -- ImGui.LogSetNextTextDecoration("###", "###") -- end else + -- Unframed typed for tree nodes if hovered or selected then local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header)) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false, 0.0) @@ -55793,6 +62156,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5)) end + -- Label if display_frame then ImGui.RenderTextClipped(text_pos, frame_bb.Max, label, label_end, label_size) else @@ -55805,16 +62169,18 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end if is_open and store_tree_node_stack_data then - TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) -- Call before TreePushOverrideID() end if is_open and bit32.band(flags, ImGuiTreeNodeFlags.NoTreePushOnOpen) == 0 then - ImGui.TreePushOverrideID(id) + ImGui.TreePushOverrideID(id) -- Could use TreePush(label) but this avoid computing twice end -- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); return is_open end +-- Draw horizontal line from our parent node +-- This is only called for visible child nodes so we are not too fussy anymore about performances --- @param target_pos ImVec2 function ImGui.TreeNodeDrawLineToChildNode(target_pos) local g = GImGui @@ -55823,6 +62189,7 @@ function ImGui.TreeNodeDrawLineToChildNode(target_pos) return end + -- FIXME: Could this be simplified using new stroke flags? local parent_data = g.TreeNodeStack.Data[g.TreeNodeStack.Size] local x1 = ImTrunc(parent_data.DrawLinesX1) local x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x) @@ -55844,6 +62211,7 @@ function ImGui.TreeNodeDrawLineToChildNode(target_pos) end end +-- Draw vertical line of the hierarchy --- @param data ImGuiTreeNodeStackData function ImGui.TreeNodeDrawLineToTreePop(data) local g = GImGui @@ -55856,7 +62224,7 @@ function ImGui.TreeNodeDrawLineToTreePop(data) y2_full = ImMax(g.CurrentTable.RowPosY2, y2_full) end y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5) - if y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full then + if y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full then -- FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y y2 = y2_full end end @@ -55864,10 +62232,12 @@ function ImGui.TreeNodeDrawLineToTreePop(data) if y2 <= y1 then return end - local x = ImTrunc(data.DrawLinesX1 - g.Style.TreeLinesSize * 0.5) + g.Style.TreeLinesSize * 0.5 + local x = ImTrunc(data.DrawLinesX1 - g.Style.TreeLinesSize * 0.5) + g.Style.TreeLinesSize * 0.5 -- Draw line centered at X1, but snap to pixels boundary. if data.DrawLinesTableColumn ~= -1 then ImGui.TablePushColumnChannel(data.DrawLinesTableColumn) end + + -- We use AddLine() instead of AddLineV() as we provide coordinates for line center (FIXME-OPT) window.DrawList:AddLine(ImVec2(x, y1), ImVec2(x, y2), ImGui.GetColorU32(ImGuiCol.TreeLines), g.Style.TreeLinesSize) if data.DrawLinesTableColumn ~= -1 then ImGui.TablePopColumnChannel() @@ -55903,12 +62273,14 @@ function ImGui.TreePop() local data = g.TreeNodeStack.Data[g.TreeNodeStack.Size] IM_ASSERT(data.ID == window.IDStack:back()) + -- Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags.NavLeftJumpsToParent is enabled) if bit32.band(data.TreeFlags, ImGuiTreeNodeFlags.NavLeftJumpsToParent) ~= 0 then if g.NavIdIsAlive and g.NavMoveDir == ImGuiDir.Left and g.NavWindow == window and ImGui.NavMoveRequestButNoResultYet() then ImGui.NavMoveRequestResolveWithPastTreeNode(g.NavMoveResultLocal, data) end end + -- Draw hierarchy lines if data.DrawLinesX1 ~= FLT_MAX and window.DC.CursorPos.y >= window.ClipRect.Min.y then ImGui.TreeNodeDrawLineToTreePop(data) end @@ -55918,10 +62290,11 @@ function ImGui.TreePop() window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(tree_depth_mask)) end - IM_ASSERT(window.IDStack.Size > 1) + 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. ImGui.PopID() end +-- Set next TreeNode/CollapsingHeader open state. --- @param is_open bool --- @param cond? ImGuiCond function ImGui.SetNextItemOpen(is_open, cond) @@ -55942,6 +62315,7 @@ function ImGui.GetTreeNodeToLabelSpacing() return g.FontSize + (g.Style.FramePadding.x * 2.0) end +-- Set next TreeNode/CollapsingHeader storage id. --- @param storage_id ImGuiID function ImGui.SetNextItemStorageID(storage_id) local g = GImGui @@ -55952,8 +62326,14 @@ function ImGui.SetNextItemStorageID(storage_id) g.NextItemData.StorageId = storage_id end +-- CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags.NoTreePushOnOpen flag). +-- This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags.CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). -- Overloads: CollapsingHeader(label, flags?) -> is_open -- CollapsingHeader(label, p_visible: bool, flags?) -> is_open, p_visible +-- p_visible == nil : regular collapsing header +-- p_visible == true : show a small close button on the corner of the header, clicking the button will set p_visible = false (returned as 2nd value) +-- p_visible == false : do not show the header at all +-- Do not mistake this with the Open state of the header itself, which you can adjust with SetNextItemOpen() or ImGuiTreeNodeFlags.DefaultOpen. --- @param label string @native function ImGui.CollapsingHeader(label, a, b) @@ -55978,6 +62358,8 @@ function ImGui.CollapsingHeader(label, a, b) local is_open = ImGui.TreeNodeBehavior(id, flags, label) if p_visible ~= nil then -- Create a small overlapping close button + -- FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + -- FIXME: CloseButton can overlap into text, need find a way to clip the text somehow. local g = GImGui local last_item_backup = ImGuiLastItemData() ImGuiLastItemData_Copy(last_item_backup, g.LastItemData) @@ -55994,15 +62376,15 @@ function ImGui.CollapsingHeader(label, a, b) return is_open, p_visible end ----------------------------------------------------------------- --- [SECTION] SELECTABLE ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Selectable +------------------------------------------------------------------------------- -- - Selectable() ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image. -- But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id. --- With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowOverlap are also frequently used flags. +-- With this scheme, ImGuiSelectableFlags.SpanAllColumns and ImGuiSelectableFlags.AllowOverlap are also frequently used flags. -- FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported. --- @param label string --- @param selected? bool @@ -56024,6 +62406,7 @@ function ImGui.Selectable(label, selected, flags, size_arg) local g = GImGui local style = g.Style + -- Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle. local id = window:GetID(label) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) @@ -56058,6 +62441,7 @@ function ImGui.Selectable(label, selected, flags, size_arg) bb.Max.x = bb.Max.x + (spacing_x - spacing_L) bb.Max.y = bb.Max.y + (spacing_y - spacing_U) end + -- if g.IO.KeyCtrl then ImGui.GetForegroundDrawList():AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)) end local disabled_item = bit32.band(flags, ImGuiSelectableFlags.Disabled) ~= 0 local extra_item_flags = disabled_item and ImGuiItemFlags.Disabled or ImGuiItemFlags.None @@ -56082,16 +62466,14 @@ function ImGui.Selectable(label, selected, flags, size_arg) local is_multi_select = bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0 if not is_visible then - if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(bb) then - -- Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd) + if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(bb) then -- Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd) return false, selected end end local disabled_global = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0 - if disabled_item and not disabled_global then - -- Only testing this as an optimization + if disabled_item and not disabled_global then -- Only testing this as an optimization ImGui.BeginDisabled() end @@ -56150,7 +62532,7 @@ function ImGui.Selectable(label, selected, flags, size_arg) -- Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad if pressed or (hovered and bit32.band(flags, ImGuiSelectableFlags.SetNavIdOnHover) ~= 0) then if not g.NavHighlightItemUnderNav and g.NavWindow == window and g.NavLayer == window.DC.NavLayerCurrent then - ImGui.SetNavID(id, window.DC.NavLayerCurrent, g.CurrentFocusScopeId, ImGui.WindowRectAbsToRel(window, bb)) -- (bb == NavRect) + ImGui.SetNavID(id, window.DC.NavLayerCurrent, g.CurrentFocusScopeId, ImGui.WindowRectAbsToRel(window, bb)) -- (bb == NavRect) if g.IO.ConfigNavCursorVisibleAuto then g.NavCursorVisible = false end @@ -56216,15 +62598,25 @@ function ImGui.Selectable(label, selected, flags, size_arg) ImGui.EndDisabled() end - -- Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui::IsItemToggledSelection() to retrieve + -- Selectable() always returns a pressed state! + -- Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui.IsItemToggledSelection() to retrieve -- selection toggle, only useful if you need that state updated (e.g. for rendering purpose) before reaching EndMultiSelect(). return pressed, selected end ----------------------------------------------------------------- --- [SECTION] LISTBOX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: ListBox +------------------------------------------------------------------------------- +-- - BeginListBox() +-- - EndListBox() +-- - ListBox() +------------------------------------------------------------------------------- +-- 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. +-- 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.5f * item_height). --- @param label string --- @param size_arg? ImVec2 function ImGui.BeginListBox(label, size_arg) @@ -56240,6 +62632,8 @@ function ImGui.BeginListBox(label, size_arg) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) + -- Size default to hold ~7.25 items. + -- Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. local size = ImTrunc(ImGui.CalcItemSize(size_arg, ImGui.CalcItemWidth(), ImGui.GetTextLineHeightWithSpacing() * 7.25 + style.FramePadding.y * 2.0)) local frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)) local frame_bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + frame_size) @@ -56249,10 +62643,11 @@ function ImGui.BeginListBox(label, size_arg) if not ImGui.IsRectVisible(bb.Min, bb.Max) then ImGui.ItemSize(bb:GetSize(), style.FramePadding.y) ImGui.ItemAdd(bb, 0, frame_bb) - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values return false end + -- FIXME-OPT: We could omit the BeginGroup() if label_size.x == 0.0f but would need to omit the EndGroup() as well. ImGui.BeginGroup() if label_size.x > 0.0 then local label_pos = ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y) @@ -56271,9 +62666,11 @@ function ImGui.EndListBox() IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0, "Mismatched BeginListBox/EndListBox calls. Did you test the return value of BeginListBox?") ImGui.EndChild() - ImGui.EndGroup() + ImGui.EndGroup() -- This is only required to be able to do IsItemXXX query on the whole ListBox including label end +-- This is merely a helper around BeginListBox(), EndListBox(). +-- Considering using those directly to submit custom data or store selection differently. -- Overloads: (label, current_item, items[], items_count?, height_in_items?) or (label, current_item, getter, user_data, items_count, height_in_items?) --- @param current_item int # 0-based --- @return int current_item @@ -56283,6 +62680,7 @@ function ImGui.ListBox(label, current_item, a, b, c, d) local getter, user_data, items_count, height_in_items = Items_ResolveArgs(a, b, c, d) if height_in_items == nil then height_in_items = -1 end + -- Calculate size from "height_in_items" if height_in_items < 0 then height_in_items = ImMin(items_count, 7) end @@ -56293,9 +62691,11 @@ function ImGui.ListBox(label, current_item, a, b, c, d) return current_item, false end + -- Assume all items have even height (= 1 line of text). If you need items of different height, + -- you can create a custom version of ListBox() in your code without using the clipper. local value_changed = false local clipper = ImGuiListClipper() - clipper:Begin(items_count, ImGui.GetTextLineHeightWithSpacing()) + clipper:Begin(items_count, ImGui.GetTextLineHeightWithSpacing()) -- We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. clipper:IncludeItemByIndex(current_item) while clipper:Step() do for i = clipper.DisplayStart, clipper.DisplayEnd - 1 do @@ -56325,9 +62725,16 @@ function ImGui.ListBox(label, current_item, a, b, c, d) return current_item, value_changed end ----------------------------------------------------------------- --- [SECTION] BASIC PLOTTING ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: PlotLines, PlotHistogram +------------------------------------------------------------------------------- +-- - PlotEx() [Internal] +-- - PlotLines() +-- - PlotHistogram() +------------------------------------------------------------------------------- +-- Plot/Graph widgets are not very good. +-- Consider using ImPlot (https://github.com/epezent/implot) which is much better! +------------------------------------------------------------------------------- --- @param plot_type ImGuiPlotType --- @param label string @@ -56364,6 +62771,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local _, hovered, _ = ImGui.ButtonBehavior(frame_bb, id) + -- Determine scale from values if not specified if scale_min == FLT_MAX or scale_max == FLT_MAX then local v_min = FLT_MAX local v_max = -FLT_MAX @@ -56390,6 +62798,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local res_w = ImMin(math.floor(frame_size.x), values_count) + ((plot_type == ImGuiPlotType.Lines) and -1 or 0) local item_count = values_count + ((plot_type == ImGuiPlotType.Lines) and -1 or 0) + -- Tooltip on hover if hovered and inner_bb:Contains(g.IO.MousePos) then local t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0, 0.999) local v_idx = math.floor(t * item_count) + 1 @@ -56410,8 +62819,8 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local v0 = values_getter(data, (0 + values_offset) % values_count + 1) local t0 = 0.0 - local tp0 = ImVec2(t0, 1.0 - ImSaturate((v0 - scale_min) * inv_scale)) - local histogram_zero_line_t = (scale_min * scale_max < 0.0) and (1 + scale_min * inv_scale) or (scale_min < 0.0 and 0.0 or 1.0) + local tp0 = ImVec2(t0, 1.0 - ImSaturate((v0 - scale_min) * inv_scale)) -- Point in the normalized space of our target rectangle + local histogram_zero_line_t = (scale_min * scale_max < 0.0) and (1 + scale_min * inv_scale) or (scale_min < 0.0 and 0.0 or 1.0) -- Where does the zero line stands local col_base = ImGui.GetColorU32((plot_type == ImGuiPlotType.Lines) and ImGuiCol.PlotLines or ImGuiCol.PlotHistogram) local col_hovered = ImGui.GetColorU32((plot_type == ImGuiPlotType.Lines) and ImGuiCol.PlotLinesHovered or ImGuiCol.PlotHistogramHovered) @@ -56423,6 +62832,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local v1 = values_getter(data, (v1_idx - 1 + values_offset + 1) % values_count + 1) local tp1 = ImVec2(t1, 1.0 - ImSaturate((v1 - scale_min) * inv_scale)) + -- NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. local pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0) local pos1 if plot_type == ImGuiPlotType.Lines then @@ -56445,6 +62855,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value end end + -- Text overlay if overlay_text then ImGui.RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, nil, nil, ImVec2(0.5, 0.0)) end @@ -56453,6 +62864,8 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label, 1, label_end, false) end + -- Return hovered index or -1 if none are hovered. + -- This is currently not exposed in the public API because we need a larger redesign of the whole thing, but in the short-term we are making it available in PlotEx(). return idx_hovered end @@ -56504,6 +62917,7 @@ function ImGui.PlotLines(label, values_or_getter, data, values_count, values_off end end +-- Plot Histogram (the data provided _is_ histogram data. it doesn't compute the histogram of your data) --- @param label string --- @param values_or_getter table|fun(data:table, i:int) # 1-based table or a function --- @param data? table # 1-based table @@ -56529,10 +62943,21 @@ function ImGui.PlotHistogram(label, values_or_getter, data, values_count, values end end ----------------------------------------------------------------- --- [SECTION] MENU RELATED ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] MenuItem, BeginMenu, EndMenu, etc. +------------------------------------------------------------------------------- +-- - ImGuiMenuColumns [Internal] +-- - BeginMenuBar() +-- - EndMenuBar() +-- - BeginMainMenuBar() +-- - EndMainMenuBar() +-- - BeginMenu() +-- - EndMenu() +-- - MenuItemEx() [Internal] +-- - MenuItem() +------------------------------------------------------------------------------- +-- Helpers for internal use --- @param spacing float --- @param window_reappearing bool function MT.ImGuiMenuColumns:Update(spacing, window_reappearing) @@ -56593,7 +63018,7 @@ function ImGui.BeginMenuBar() end IM_ASSERT(not window.DC.MenuBarAppending) - ImGui.BeginGroup() -- FIXME: Misleading to use a group for that backup/restore + ImGui.BeginGroup() -- Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore ImGui.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. @@ -56605,7 +63030,7 @@ function ImGui.BeginMenuBar() clip_rect:ClipWith(window.OuterRectClipped) ImGui.PushClipRect(clip_rect.Min, clip_rect.Max, false) - -- We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags) + -- We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags). ImVec2_Copy(window.DC.CursorPos, ImVec2(bar_rect.Min.x + window.DC.MenuBarOffset.x, bar_rect.Min.y + window.DC.MenuBarOffset.y)) ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorPos) window.DC.LayoutType = ImGuiLayoutType.Horizontal @@ -56627,24 +63052,28 @@ function ImGui.EndMenuBar() IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.MenuBar) ~= 0) 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 + -- Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings. if ImGui.NavMoveRequestButNoResultYet() and (g.NavMoveDir == ImGuiDir.Left or g.NavMoveDir == ImGuiDir.Right) and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then + -- Try to find out if the request is for one of our child menu local nav_earliest_child = g.NavWindow while nav_earliest_child.ParentWindow and bit32.band(nav_earliest_child.ParentWindow.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 do nav_earliest_child = nav_earliest_child.ParentWindow end if nav_earliest_child.ParentWindow == window and nav_earliest_child.DC.ParentLayoutType == ImGuiLayoutType.Horizontal and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) == 0 then + -- To do so we claim focus back, restore NavId and then process the movement request for yet another frame. + -- This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth bothering) local layer = ImGuiNavLayer.Menu - IM_ASSERT(bit32.band(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, layer)) ~= 0) + IM_ASSERT(bit32.band(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, layer)) ~= 0) -- Sanity check (FIXME: Seems unnecessary) ImGui.FocusWindow(window) ImGui.SetNavID(window.NavLastIds[layer], layer, 0, window.NavRectRel[layer]) + -- FIXME-NAV: How to deal with this when not using g.IO.ConfigNavCursorVisibleAuto? if g.NavCursorVisible then - g.NavCursorVisible = false + g.NavCursorVisible = false -- Hide nav cursor for the current frame so we don't see the intermediary selection. Will be set again g.NavCursorHideFrames = 2 end g.NavHighlightItemUnderNav = true g.NavMousePosDirty = true - ImGui.NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags) + ImGui.NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags) -- Repeat end else ImGui.NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags.WrapX) @@ -56652,14 +63081,14 @@ function ImGui.EndMenuBar() ImGui.PopClipRect() ImGui.PopID() - 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 + 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 + -- FIXME: Extremely confusing, cleanup by (a) working on WorkRect stack system (b) not using a Group confusingly here. local group_data = g.GroupStack:back() group_data.EmitItem = false local restore_cursor_max_pos = ImVec2() ImVec2_Copy(restore_cursor_max_pos, group_data.BackupCursorMaxPos) - window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, window.DC.CursorMaxPos.x - window.Scroll.x) -- Convert ideal extents for scrolling layer equivalent + window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, window.DC.CursorMaxPos.x - window.Scroll.x) -- Convert ideal extents for scrolling layer equivalent. ImGui.EndGroup() -- Restore position on layer 0 // FIXME: Misleading to use a group for that backup/restore window.DC.LayoutType = ImGuiLayoutType.Vertical window.DC.IsSameLine = false @@ -56669,6 +63098,8 @@ function ImGui.EndMenuBar() end -- Important: calling order matters! +-- FIXME: Somehow overlapping with docking tech. +-- FIXME: The "rect-cut" aspect of this could be formalized into a lower-level helper (rect-cut: https://halt.software/dead-simple-layouts) --- @param name string --- @param viewport_p? ImGuiViewport --- @param dir ImGuiDir @@ -56680,6 +63111,7 @@ function ImGui.BeginViewportSideBar(name, viewport_p, dir, axis_size, window_fla local bar_window = ImGui.FindWindowByName(name) local viewport = viewport_p or ImGui.GetMainViewport() if bar_window == nil or bar_window.BeginCount == 0 then + -- Calculate and set window size/position local avail_rect = viewport:GetBuildWorkRect() local axis = (dir == ImGuiDir.Up or dir == ImGuiDir.Down) and ImGuiAxis.Y or ImGuiAxis.X local pos = ImVec2(avail_rect.Min.x, avail_rect.Min.y) @@ -56691,6 +63123,7 @@ function ImGui.BeginViewportSideBar(name, viewport_p, dir, axis_size, window_fla ImGui.SetNextWindowPos(pos) ImGui.SetNextWindowSize(size) + -- Report our size into work area (for next frame) using actual window size if dir == ImGuiDir.Up or dir == ImGuiDir.Left then viewport.BuildWorkInsetMin[axis] = viewport.BuildWorkInsetMin[axis] + axis_size elseif dir == ImGuiDir.Down or dir == ImGuiDir.Right then @@ -56701,7 +63134,7 @@ function ImGui.BeginViewportSideBar(name, viewport_p, dir, axis_size, window_fla window_flags = bit32.bor(window_flags or 0, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoDocking) ImGui.SetNextWindowViewport(viewport.ID) ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 0.0) - ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, ImVec2(0, 0)) + ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, ImVec2(0, 0)) -- Lift normal size constraint local _, is_open = ImGui.Begin(name, nil, window_flags) ImGui.PopStyleVar(2) @@ -56712,8 +63145,12 @@ function ImGui.BeginMainMenuBar() local g = GImGui local viewport = ImGui.GetMainViewport() + -- Notify of viewport change so GetFrameHeight() can be accurate in case of DPI change ImGui.SetCurrentViewport(nil, viewport) + -- For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set. + -- FIXME: This could be generalized as an opt-in way to clamp window.DC.CursorStartPos to avoid SafeArea? + -- FIXME: Consider removing support for safe area down the line... it's messy. Nowadays consoles have support for TV calibration in OS settings. g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0)) local window_flags = bit32.bor(ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.MenuBar) local height = ImGui.GetFrameHeight() @@ -56724,6 +63161,7 @@ function ImGui.BeginMainMenuBar() return false end + -- 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 = bit32.band(g.CurrentWindow.Flags, bit32.bnot(ImGuiWindowFlags.NoSavedSettings)) ImGui.BeginMenuBar() return is_open @@ -56731,11 +63169,13 @@ end function ImGui.EndMainMenuBar() local g = GImGui - IM_ASSERT_USER_ERROR_RET(g.CurrentWindow.DC.MenuBarAppending, "Calling EndMainMenuBar() not from a menu-bar!") + IM_ASSERT_USER_ERROR_RET(g.CurrentWindow.DC.MenuBarAppending, "Calling EndMainMenuBar() not from a menu-bar!") -- Not technically testing that it is the main menu bar ImGui.EndMenuBar() - g.CurrentWindow.Flags = bit32.bor(g.CurrentWindow.Flags, ImGuiWindowFlags.NoSavedSettings) + g.CurrentWindow.Flags = bit32.bor(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 nil focus. if g.CurrentWindow == g.NavWindow and g.NavLayer == ImGuiNavLayer.Main and not g.NavAnyRequest and g.ActiveId == 0 then ImGui.FocusTopMostWindowUnderOne(g.NavWindow, nil, nil, bit32.bor(ImGuiFocusRequestFlags.UnlessBelowModal, ImGuiFocusRequestFlags.RestoreFocusedChild)) end @@ -56750,6 +63190,17 @@ local function IsRootOfOpenMenuSet() return false end + -- Initially we used 'upper_popup.OpenParentId == window.IDStack:back()' to differentiate multiple menu sets from each others + -- (e.g. inside menu bar vs loose menu items) based on parent ID. + -- This would however prevent the use of e.g. PushID() user code submitting menus. + -- Previously this worked between popup and a first child menu because the first child menu always had the _ChildWindow flag, + -- making hovering on parent popup possible while first child menu was focused - but this was generally a bug with other side effects. + -- Instead we don't treat Popup specifically (in order to consistently support menu features in them), maybe the first child menu of a Popup + -- doesn't have the _ChildWindow flag, and we rely on this IsRootOfOpenMenuSet() check to allow hovering between root window/popup and first child menu. + -- In the end, lack of ID check made it so we could no longer differentiate between separate menu sets. To compensate for that, we at least check parent window nav layer. + -- This fixes the most common case of menu opening on hover when moving between window content and menu bar. Multiple different menu sets in same nav layer would still + -- open on hover, but that should be a lesser problem, because if such menus are close in proximity in window content then it won't feel weird and if they are far apart + -- it likely won't be a problem anyone runs into. local upper_popup = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1] if window.DC.NavLayerCurrent ~= upper_popup.ParentNavLayer then return false @@ -56771,30 +63222,41 @@ function ImGui.BeginMenuEx(label, icon, enabled) local id = window:GetID(label) local menu_is_open = ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) + -- Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu) + -- The first menu in a hierarchy isn't so hovering doesn't get across (otherwise e.g. resizing borders with ImGuiButtonFlags.FlattenChildren would react), but top-most BeginMenu() will bypass that limitation. local window_flags = bit32.bor(ImGuiWindowFlags.ChildMenu, ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoNavFocus) if bit32.band(window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.ChildWindow) end + -- If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin(). + -- We are relying on a O(N) search - so O(N log N) over the frame - which seems like the most efficient for the expected small amount of BeginMenu() calls per frame. + -- If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used. if g.MenusIdSubmittedThisFrame:contains(id) then if menu_is_open then - menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags) + menu_is_open = ImGui.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() + g.NextWindowData:ClearFlags() -- we behave like Begin() and need to consume those values end return menu_is_open end + -- Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu g.MenusIdSubmittedThisFrame:push_back(id) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) + -- Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent without always being a Child window) + -- This is only done for items for the menu set and not the full parent window. local menuset_is_open = IsRootOfOpenMenuSet() if menuset_is_open then g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoWindowHoverableCheck) end + -- The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu, + -- However the final position is going to be different! It is chosen by FindBestWindowPosForPopup(). + -- e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering. local popup_pos local pos = ImVec2() ImVec2_Copy(pos, window.DC.CursorPos) @@ -56810,6 +63272,9 @@ function ImGui.BeginMenuEx(label, icon, enabled) local selectable_flags = bit32.bor(ImGuiSelectableFlags.SelectOnClick, ImGuiSelectableFlags.NoAutoClosePopups) local offsets = window.DC.MenuColumns if window.DC.LayoutType == ImGuiLayoutType.Horizontal then + -- 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() window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * 0.5) ImGui.PushStyleVarX(ImGuiStyleVar.ItemSpacing, style.ItemSpacing.x * 2.0) local text_pos = ImVec2(window.DC.CursorPos.x + offsets.OffsetLabel, pos.y + window.DC.CurrLineTextBaseOffset) @@ -56817,13 +63282,16 @@ function ImGui.BeginMenuEx(label, icon, enabled) -- TODO: ImGui.LogSetNextTextDecoration("[", "]") ImGui.RenderText(text_pos, label, 1, label_end, false) ImGui.PopStyleVar() - window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) + window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) -- -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). popup_pos = ImVec2(pos.x - 1.0 - IM_TRUNC(style.ItemSpacing.x * 0.5), text_pos.y - style.FramePadding.y + window.MenuBarHeight) else + -- 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.) local icon_w if (icon and icon ~= "") then icon_w = ImGui.CalcTextSize(icon, nil).x else icon_w = 0.0 end local checkmark_w = IM_TRUNC(g.FontSize * 1.20) - local min_w = offsets:DeclColumns(icon_w, label_size.x, 0.0, checkmark_w) + local min_w = offsets:DeclColumns(icon_w, label_size.x, 0.0, checkmark_w) -- Feedback to next frame local extra_w = ImMax(0.0, ImGui.GetContentRegionAvail().x - min_w) local text_pos = ImVec2(window.DC.CursorPos.x, pos.y + window.DC.CurrLineTextBaseOffset) pressed = ImGui.Selectable("", menu_is_open, bit32.bor(selectable_flags, ImGuiSelectableFlags.SpanAvailWidth), ImVec2(min_w, label_size.y)) @@ -56842,6 +63310,8 @@ function ImGui.BeginMenuEx(label, icon, enabled) ImGui.EndDisabled() end + -- Once dragged, release ActiveId + key ownership. This is to allow the idiom of mouse down a menu, dragging elsewhere, up on some other MenuItem(). (#8233, #9394) + -- Could move logic into lower-level ImGuiButtonFlags.AutoReleaseActiveId + ImGuiButtonFlags.AutoReleaseKeyOwner? Easier once we get rid of the Selectable() middle-man here. if g.ActiveId == id and g.HoveredId ~= id and g.ActiveIdSource == ImGuiInputSource.Mouse and ImGui.IsMouseDragging(0) then ImGui.ClearActiveID() ImGui.SetKeyOwner(ImGuiKey.MouseLeft, ImGuiKeyOwner_NoOwner) @@ -56852,12 +63322,14 @@ function ImGui.BeginMenuEx(label, icon, enabled) local want_open = false local want_open_nav_init = false local want_close = false - if window.DC.LayoutType == ImGuiLayoutType.Vertical then + if window.DC.LayoutType == ImGuiLayoutType.Vertical then -- (window.Flags & (ImGuiWindowFlags.Popup|ImGuiWindowFlags.ChildMenu)) + -- Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu + -- Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. local moving_toward_child_menu = false - local child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) and g.OpenPopupStack[g.BeginPopupStack.Size + 1] or nil + local child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) and g.OpenPopupStack[g.BeginPopupStack.Size + 1] or nil -- Popup candidate (testing below) local child_menu_window = (child_popup and child_popup.Window and child_popup.Window.ParentWindow == window) and child_popup.Window or nil if g.HoveredWindow == window and child_menu_window ~= nil then - local ref_unit = g.FontSize + local ref_unit = g.FontSize -- FIXME-DPI local child_dir = (window.Pos.x < child_menu_window.Pos.x) and 1.0 or -1.0 local next_window_rect = child_menu_window:Rect() local ta = (g.IO.MousePos - g.IO.MouseDelta) @@ -56870,46 +63342,53 @@ function ImGui.BeginMenuEx(label, icon, enabled) tb = next_window_rect:GetTR() tc = next_window_rect:GetBR() end - local pad_farmost_h = ImClamp(ImFabs(ta.x - tb.x) * 0.30, ref_unit * 0.5, ref_unit * 2.5) + local pad_farmost_h = ImClamp(ImFabs(ta.x - tb.x) * 0.30, ref_unit * 0.5, ref_unit * 2.5) -- Add a bit of extra slack. ta.x = ta.x + child_dir * -0.5 tb.x = tb.x + child_dir * ref_unit tc.x = tc.x + child_dir * ref_unit - tb.y = ta.y + ImMax((tb.y - pad_farmost_h) - ta.y, -ref_unit * 8.0) + tb.y = ta.y + ImMax((tb.y - pad_farmost_h) - ta.y, -ref_unit * 8.0) -- Triangle has maximum height to limit the slope and the bias toward large sub-menus tc.y = ta.y + ImMin((tc.y + pad_farmost_h) - ta.y, ref_unit * 8.0) moving_toward_child_menu = ImStd.ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos) + -- ImGui.GetForegroundDrawList():AddTriangleFilled(ta, tb, tc, moving_toward_child_menu and IM_COL32(0, 128, 0, 128) or IM_COL32(128, 0, 0, 128)) -- [DEBUG] end + -- The 'HovereWindow == window' check creates an inconsistency (e.g. moving away from menu slowly tends to hit same window, whereas moving away fast does not) + -- But we also need to not close the top-menu menu when moving over void. Perhaps we should extend the triangle check to a larger polygon. + -- (Remember to test this on BeginPopup("A")->BeginMenu("B") sequence which behaves slightly differently as B isn't a Child of A and hovering isn't shared.) if menu_is_open and not hovered and g.HoveredWindow == window and not moving_toward_child_menu and not g.NavHighlightItemUnderNav and g.ActiveId == 0 then want_close = true end - if not menu_is_open and pressed then + -- Open + -- (note: at this point 'hovered' actually includes the NavDisableMouseHover == false test) + if not menu_is_open and pressed then -- Click/activate to open want_open = true - elseif not menu_is_open and hovered and not moving_toward_child_menu then + elseif not menu_is_open and hovered and not moving_toward_child_menu then -- Hover to open want_open = true - elseif not menu_is_open and hovered and g.HoveredIdTimer >= 0.30 and g.MouseStationaryTimer >= 0.30 then + elseif not menu_is_open and hovered and g.HoveredIdTimer >= 0.30 and g.MouseStationaryTimer >= 0.30 then -- Hover to open (timer fallback) want_open = true end - if g.NavId == id and g.NavMoveDir == ImGuiDir.Right then + if g.NavId == id and g.NavMoveDir == ImGuiDir.Right then -- Nav-Right to open want_open = true want_open_nav_init = true ImGui.NavMoveRequestCancel() ImGui.SetNavCursorVisibleAfterMove() end else - if menu_is_open and pressed and menuset_is_open then + -- Menu bar + if menu_is_open and pressed and menuset_is_open then -- Click an open menu again to close it want_close = true want_open = false menu_is_open = false - elseif pressed or (hovered and menuset_is_open and not menu_is_open) then + elseif pressed or (hovered and menuset_is_open and not menu_is_open) then -- First click to open, then hover to open others want_open = true - elseif g.NavId == id and g.NavMoveDir == ImGuiDir.Down then + elseif g.NavId == id and g.NavMoveDir == ImGuiDir.Down then -- Nav-Down to open want_open = true ImGui.NavMoveRequestCancel() end end - if not enabled then + if not enabled then -- explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' want_close = true end if want_close and ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then @@ -56924,32 +63403,38 @@ function ImGui.BeginMenuEx(label, icon, enabled) end if want_open and not menu_is_open and g.OpenPopupStack.Size > g.BeginPopupStack.Size then + -- Don't reopen/recycle same menu level in the same frame if it is a different menu ID, first close the other menu and yield for a frame. ImGui.OpenPopup(label) elseif want_open then menu_is_open = true - ImGui.OpenPopup(label, ImGuiPopupFlags.NoReopen) + ImGui.OpenPopup(label, ImGuiPopupFlags.NoReopen) -- | (want_open_nav_init ? ImGuiPopupFlags.NoReopenAlwaysNavInit : 0)) end if menu_is_open then local last_item_in_parent = ImGuiLastItemData() ImGuiLastItemData_Copy(last_item_in_parent, g.LastItemData) - ImGui.SetNextWindowPos(popup_pos, ImGuiCond.Always) - ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.PopupRounding) - menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags) + ImGui.SetNextWindowPos(popup_pos, ImGuiCond.Always) -- Note: misleading: the value will serve as reference for FindBestWindowPosForPopup(), not actual pos. + ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.PopupRounding) -- First level will use _PopupRounding, subsequent will use _ChildRounding + menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags) -- menu_is_open may be 'false' when the popup is completely clipped (e.g. zero size display) ImGui.PopStyleVar() if menu_is_open then + -- Implement what ImGuiPopupFlags.NoReopenAlwaysNavInit would do: + -- Perform an init request in the case the popup was already open (via a previous mouse hover) if want_open and want_open_nav_init and not g.NavInitRequest then ImGui.FocusWindow(g.CurrentWindow, ImGuiFocusRequestFlags.UnlessBelowModal) ImGui.NavInitWindow(g.CurrentWindow, false) end + + -- Restore LastItemData so IsItemXXXX functions can work after BeginMenu()/EndMenu() + -- (This fixes using IsItemClicked() and IsItemHovered(), but IsItemHovered() also relies on its support for ImGuiItemFlags.NoWindowHoverableCheck) ImGuiLastItemData_Copy(g.LastItemData, last_item_in_parent) if g.HoveredWindow == window then g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end end else - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values end return menu_is_open @@ -56964,11 +63449,12 @@ function ImGui.BeginMenu(label, enabled) end function ImGui.EndMenu() + -- Nav: When a left move request our menu failed, close ourselves. local g = GImGui local window = g.CurrentWindow IM_ASSERT_USER_ERROR_RET(bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.ChildMenu)) == bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.ChildMenu), "Calling EndMenu() in wrong window!") - local parent_window = window.ParentWindow + local parent_window = window.ParentWindow -- Should always be ~= nil is we passed assert. if window.BeginCount == window.BeginCountPreviousFrame then if g.NavMoveDir == ImGuiDir.Left and ImGui.NavMoveRequestButNoResultYet() then if g.NavWindow and g.NavWindow.RootWindowForNav == window and parent_window.DC.LayoutType == ImGuiLayoutType.Vertical then @@ -57002,11 +63488,14 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) + -- See BeginMenuEx() for comments about this. local menuset_is_open = IsRootOfOpenMenuSet() if menuset_is_open then g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoWindowHoverableCheck) end + -- We've been using the equivalent of ImGuiSelectableFlags.SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73), + -- but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only. ImGui.PushID(label) if not enabled then ImGui.BeginDisabled() @@ -57014,11 +63503,14 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) local pressed + -- We use ImGuiSelectableFlags.NoSetKeyOwner to allow down on one menu item, move, up on another. local backup_rounding = style.SelectableRounding style.SelectableRounding = style.MenuItemRounding local selectable_flags = bit32.bor(ImGuiSelectableFlags.SelectOnRelease, ImGuiSelectableFlags.SetNavIdOnHover) local offsets = window.DC.MenuColumns if window.DC.LayoutType == ImGuiLayoutType.Horizontal then + -- Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful + -- Note that in this situation: we don't render the shortcut, we render a highlight instead of the selected tick mark. window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * 0.5) local text_pos = ImVec2(window.DC.CursorPos.x + offsets.OffsetLabel, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset) ImGui.PushStyleVarX(ImGuiStyleVar.ItemSpacing, style.ItemSpacing.x * 2.0) @@ -57027,8 +63519,11 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 then ImGui.RenderText(text_pos, label, 1, label_end, false) end - window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) + window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) -- -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). else + -- 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.) local icon_w = 0.0 if icon and icon ~= "" then icon_w = ImGui.CalcTextSize(icon, nil).x @@ -57037,8 +63532,8 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) if shortcut and shortcut ~= "" then shortcut_w = ImGui.CalcTextSize(shortcut, nil).x end - local checkmark_w = IM_TRUNC(g.FontSize * 1.20) - local min_w = offsets:DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w) + local checkmark_w = IM_TRUNC(g.FontSize * 1.20) -- FIXME: Always accounted for, even in a menu with none, because 'selected' has no neutral setting. + local min_w = offsets:DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w) -- Feedback for next frame local stretch_w = ImMax(0.0, ImGui.GetContentRegionAvail().x - min_w) local text_pos = ImVec2(pos.x, pos.y + window.DC.CurrLineTextBaseOffset) pressed = ImGui.Selectable("", false, bit32.bor(selectable_flags, ImGuiSelectableFlags.SpanAvailWidth), ImVec2(min_w, label_size.y)) @@ -57062,6 +63557,8 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) end style.SelectableRounding = backup_rounding + -- Once dragged, release ActiveId + key ownership. This is to allow the idiom of mouse down a menu, dragging elsewhere, up on some other MenuItem(). (#8233, #9394) + -- Could move logic into lower-level ImGuiButtonFlags_AutoReleaseActiveId + ImGuiButtonFlags_AutoReleaseKeyOwner? Easier once we get rid of the Selectable() middle-man here. local id = g.LastItemData.ID if g.ActiveId == id and g.HoveredId ~= id and g.ActiveIdSource == ImGuiInputSource.Mouse and ImGui.IsMouseDragging(0) then ImGui.ClearActiveID() @@ -57142,12 +63639,18 @@ local function SortTabsByBeginOrder(tab_bar) for i = 1, tab_bar.Tabs.Size do data[i] = arr[i] end end +-- Scrolling happens only in the central section (leading/trailing sections are not scrolling) local function TabBarCalcScrollableWidth(tab_bar, sections) return tab_bar.BarRect:GetWidth() - sections[1].Width - sections[3].Width - sections[2].Spacing end +-- TabCount: Number of tabs in this section. +-- Width: Sum of width of tabs in this section (after shrinking down) +-- Spacing: Horizontal spacing at the end of the section. local function ImGuiTabBarSection() return { TabCount = 0, Width = 0.0, WidthAfterShrinkMinWidth = 0.0, Spacing = 0.0 } end +-- 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. -- items: 1-based array of ImGuiShrinkWidthItem, `first` = 1-based index of first item, `count` items function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) if count <= 0 then return end @@ -57156,6 +63659,7 @@ function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) if it.Width >= 0.0 then it.Width = ImMax(it.Width - width_excess, width_min) end return end + -- Sort largest first, smallest last. local slice = {} for n = 1, count do slice[n] = items[first + n - 1] end table.sort(slice, function(a, b) @@ -57180,6 +63684,9 @@ function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) width_excess = width_excess - w end end + + -- Round width and redistribute remainder + -- Ensure that e.g. the right-most tab of a shrunk tab-bar always reaches exactly at the same distance from the right-most edge of the tab bar separator. width_excess = 0.0 for n = 1, count do local width_rounded = ImTrunc(it[n].Width) @@ -57201,15 +63708,39 @@ function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Widgets: BeginTabBar, EndTabBar, etc. ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - BeginTabBar() +-- - BeginTabBarEx() [Internal] +-- - EndTabBar() +-- - TabBarLayout() [Internal] +-- - TabBarCalcTabID() [Internal] +-- - TabBarCalcMaxTabWidth() [Internal] +-- - TabBarFindTabById() [Internal] +-- - TabBarFindTabByOrder() [Internal] +-- - TabBarFindMostRecentlySelectedTabForActiveWindow() [Internal] +-- - TabBarGetCurrentTab() [Internal] +-- - TabBarGetTabName() [Internal] +-- - TabBarAddTab() [Internal] +-- - TabBarRemoveTab() [Internal] +-- - TabBarCloseTab() [Internal] +-- - TabBarScrollClamp() [Internal] +-- - TabBarScrollToTab() [Internal] +-- - TabBarQueueFocus() [Internal] +-- - TabBarQueueReorder() [Internal] +-- - TabBarProcessReorderFromMousePos() [Internal] +-- - TabBarProcessReorder() [Internal] +-- - TabBarScrollingButtons() [Internal] +-- - TabBarTabListPopupButton() [Internal] +------------------------------------------------------------------------------- function ImGui.TabBarFindByID(id) SyncContext() return GImGui.TabBars:GetByKey(id) end +-- Remove TabBar data (currently only used by TestEngine) function ImGui.TabBarRemove(tab_bar) SyncContext() GImGui.TabBars:Remove(tab_bar.ID, tab_bar) @@ -57228,6 +63759,7 @@ function ImGui.BeginTabBar(str_id, flags) tab_bar.ID = id tab_bar.SeparatorMinX = tab_bar_bb.Min.x - IM_TRUNC(window.WindowPadding.x * 0.5) tab_bar.SeparatorMaxX = tab_bar_bb.Max.x + IM_TRUNC(window.WindowPadding.x * 0.5) + -- if (g.NavWindow and ImGui.IsWindowChildOf(g.NavWindow, window, false, false)) flags = bit32.bor(flags, ImGuiTabBarFlags.IsFocused) return ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) end @@ -57239,14 +63771,16 @@ function ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) if window.SkipItems then return false end IM_ASSERT(tab_bar.ID ~= 0) - if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then + if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then -- Already done ImGui.PushOverrideID(tab_bar.ID) end + -- Add to stack g.CurrentTabBarStack:push_back(tab_bar) g.CurrentTabBar = tab_bar tab_bar.Window = window + -- Append with multiple BeginTabBar()/EndTabBar() pairs. ImVec2_Copy(tab_bar.BackupCursorPos, window.DC.CursorPos) if tab_bar.CurrFrameVisible == g.FrameCount then ImVec2_CopyV(window.DC.CursorPos, tab_bar.BarRect.Min.x, tab_bar.BarRect.Max.y + tab_bar.ItemSpacingY) @@ -57254,21 +63788,23 @@ function ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) return true end + -- Ensure correct ordering when toggling ImGuiTabBarFlags.Reorderable flag, or when a new tab was added while being not reorderable if bit32.band(flags, ImGuiTabBarFlags.Reorderable) ~= bit32.band(tab_bar.Flags, ImGuiTabBarFlags.Reorderable) or (tab_bar.TabsAddedNew and bit32.band(flags, ImGuiTabBarFlags.Reorderable) == 0) then - if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then + if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then -- FIXME: TabBar with DockNode can now be hybrid SortTabsByBeginOrder(tab_bar) end end tab_bar.TabsAddedNew = false + -- Flags if bit32.band(flags, ImGuiTabBarFlags.FittingPolicyMask_) == 0 then flags = bit32.bor(flags, ImGuiTabBarFlags.FittingPolicyDefault_) end tab_bar.Flags = flags tab_bar.BarRect = ImRect(tab_bar_bb.Min, tab_bar_bb.Max) - tab_bar.WantLayout = true + tab_bar.WantLayout = true -- Layout will be done on the first call to ItemTab() tab_bar.PrevFrameVisible = tab_bar.CurrFrameVisible tab_bar.CurrFrameVisible = g.FrameCount tab_bar.PrevTabsContentsHeight = tab_bar.CurrTabsContentsHeight @@ -57279,8 +63815,11 @@ function ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) tab_bar.LastTabItemIdx = -1 tab_bar.BeginCount = 1 + -- Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap ImVec2_CopyV(window.DC.CursorPos, tab_bar.BarRect.Min.x, tab_bar.BarRect.Max.y + tab_bar.ItemSpacingY) + -- Draw separator + -- (it would be misleading to draw this in EndTabBar() suggesting that it may be drawn over tabs, as tab bar are appendable) local col = ImGui.GetColorU32(bit32.band(flags, ImGuiTabBarFlags.IsFocused) ~= 0 and ImGuiCol.TabSelected or ImGuiCol.TabDimmedSelected) if g.Style.TabBarBorderSize > 0.0 then local y = tab_bar.BarRect.Max.y @@ -57298,8 +63837,10 @@ function ImGui.EndTabBar() local tab_bar = g.CurrentTabBar IM_ASSERT(tab_bar ~= nil, "Mismatched BeginTabBar()/EndTabBar()!") + -- Fallback in case no TabItem have been submitted if tab_bar.WantLayout then ImGui.TabBarLayout(tab_bar) end + -- Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). local tab_bar_appearing = (tab_bar.PrevFrameVisible + 1 < g.FrameCount) if tab_bar.VisibleTabWasSubmitted or tab_bar.VisibleTabId == 0 or tab_bar_appearing then tab_bar.CurrTabsContentsHeight = ImMax(window.DC.CursorPos.y - tab_bar.BarRect.Max.y, tab_bar.CurrTabsContentsHeight) @@ -57312,7 +63853,7 @@ function ImGui.EndTabBar() end tab_bar.LastTabItemIdx = -1 - if bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0 then + if bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0 then -- Already done ImGui.PopID() end @@ -57320,22 +63861,27 @@ function ImGui.EndTabBar() if g.CurrentTabBarStack.Size == 0 then g.CurrentTabBar = nil else g.CurrentTabBar = g.CurrentTabBarStack.Data[g.CurrentTabBarStack.Size] end end +-- This is called only once a frame before by the first call to ItemTab() +-- The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions. function ImGui.TabBarLayout(tab_bar) SyncContext() local g = GImGui tab_bar.WantLayout = false + -- Track selected tab when resizing our parent down local 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) local tabs = tab_bar.Tabs local tab_dst_n = 0 local need_sort_by_section = false - local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- 1-based: [1]=Leading,[2]=Central,[3]=Trailing + local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- Layout sections: Leading, Central, Trailing (1-based: [1]=Leading,[2]=Central,[3]=Trailing) for tab_src_n = 0, tabs.Size - 1 do local tab = tabs.Data[tab_src_n + 1] if tab.LastFrameVisible < tab_bar.PrevFrameVisible or tab.WantClose then + -- Remove tab if tab_bar.VisibleTabId == tab.ID then tab_bar.VisibleTabId = 0 end if tab_bar.SelectedTabId == tab.ID then tab_bar.SelectedTabId = 0 end if tab_bar.NextSelectedTabId == tab.ID then tab_bar.NextSelectedTabId = 0 end @@ -57343,6 +63889,7 @@ function ImGui.TabBarLayout(tab_bar) if tab_dst_n ~= tab_src_n then tabs.Data[tab_dst_n + 1] = tab end tab.IndexDuringLayout = tab_dst_n + -- We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another) local curr_tab_section_n = TabItemGetSectionIdx(tab) if tab_dst_n > 0 then local prev_tab = tabs.Data[tab_dst_n] @@ -57361,10 +63908,12 @@ function ImGui.TabBarLayout(tab_bar) if need_sort_by_section then SortTabsBySection(tab_bar) end + -- Calculate spacing between sections local tab_spacing = g.Style.ItemInnerSpacing.x sections[1].Spacing = (sections[1].TabCount > 0 and (sections[2].TabCount + sections[3].TabCount) > 0) and tab_spacing or 0.0 sections[2].Spacing = (sections[2].TabCount > 0 and sections[3].TabCount > 0) and tab_spacing or 0.0 + -- Setup next selected tab local scroll_to_tab_id = 0 if tab_bar.NextScrollToTabId ~= 0 then scroll_to_tab_id = tab_bar.NextScrollToTabId @@ -57376,6 +63925,7 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.SelectedTabId end + -- Process order change request (we could probably process it when requested but it's just saner to do it in a single spot). if tab_bar.ReorderRequestTabId ~= 0 then if ImGui.TabBarProcessReorder(tab_bar) then if tab_bar.ReorderRequestTabId == tab_bar.SelectedTabId then @@ -57385,23 +63935,28 @@ function ImGui.TabBarLayout(tab_bar) tab_bar.ReorderRequestTabId = 0 end + -- Tab List Popup (will alter tab_bar.BarRect and therefore the available width!) local tab_list_popup_button = bit32.band(tab_bar.Flags, ImGuiTabBarFlags.TabListPopupButton) ~= 0 if tab_list_popup_button then - local tab_to_select = ImGui.TabBarTabListPopupButton(tab_bar) + local tab_to_select = ImGui.TabBarTabListPopupButton(tab_bar) -- NB: Will alter BarRect.Min.x! if tab_to_select then tab_bar.SelectedTabId = tab_to_select.ID scroll_to_tab_id = tab_to_select.ID end end - -- shrink buffer layout: leading, trailing, central (0-based offsets) + -- Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central + -- (whereas our tabs are stored as: leading, central, trailing) + -- (shrink_buffer_indexes holds 0-based offsets) local shrink_buffer_indexes = { 0, sections[1].TabCount + sections[3].TabCount, sections[1].TabCount } local swb = g.ShrinkWidthBuffer swb:resize(tabs.Size) for i = 1, tabs.Size do if swb.Data[i] == nil then swb.Data[i] = ImGuiShrinkWidthItem() end end + -- Minimum shrink width local shrink_min_width = (bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyMixed) ~= 0) and g.Style.TabMinWidthShrink or 1.0 + -- Compute ideal tabs widths + store them into shrink buffer local most_recently_selected_tab = nil local curr_section_n = -1 local found_selected_tab_id = false @@ -57415,6 +63970,9 @@ function ImGui.TabBarLayout(tab_bar) if tab.ID == tab_bar.SelectedTabId then found_selected_tab_id = true end if scroll_to_tab_id == 0 and g.NavJustMovedToId == tab.ID then scroll_to_tab_id = tab.ID end + -- Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar. + -- Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet, + -- and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window. local tab_name = ImGui.TabBarGetTabName(tab_bar, tab) local has_close_button_or_unsaved_marker = bit32.band(tab.Flags, ImGuiTabItemFlags.NoCloseButton) == 0 or bit32.band(tab.Flags, ImGuiTabItemFlags.UnsavedDocument) ~= 0 tab.ContentWidth = (tab.RequestedWidth >= 0.0) and tab.RequestedWidth or ImGui.TabItemCalcSize(tab_name, has_close_button_or_unsaved_marker).x @@ -57428,6 +63986,7 @@ function ImGui.TabBarLayout(tab_bar) section.WidthAfterShrinkMinWidth = section.WidthAfterShrinkMinWidth + ImMin(tab.ContentWidth, shrink_min_width) + ((section_n == curr_section_n) and tab_spacing or 0.0) curr_section_n = section_n + -- Store data so we can build an array sorted by width if we need to shrink tabs down local item = swb.Data[shrink_buffer_indexes[section_n + 1] + 1] shrink_buffer_indexes[section_n + 1] = shrink_buffer_indexes[section_n + 1] + 1 item.Index = tab_n @@ -57436,6 +63995,7 @@ function ImGui.TabBarLayout(tab_bar) tab.Width = ImMax(tab.ContentWidth, 1.0) end + -- Compute total ideal width (used for e.g. auto-resizing a window) local width_all_tabs_after_min_width_shrink = 0.0 tab_bar.WidthAllTabsIdeal = 0.0 for section_n = 1, 3 do @@ -57443,6 +64003,9 @@ function ImGui.TabBarLayout(tab_bar) width_all_tabs_after_min_width_shrink = width_all_tabs_after_min_width_shrink + sections[section_n].WidthAfterShrinkMinWidth + sections[section_n].Spacing end + -- Horizontal scrolling buttons + -- - Important: note that TabBarScrollButtons() will alter BarRect.Max.x. + -- - Selection skips buttons and might cross through sections if there are Tabs in Leading/Trailing sections. local can_scroll = bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyScroll) ~= 0 or bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyMixed) ~= 0 local width_all_tabs_to_use_for_scroll = (bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyScroll) ~= 0) and tab_bar.WidthAllTabs or width_all_tabs_after_min_width_shrink tab_bar.ScrollButtonEnabled = (width_all_tabs_to_use_for_scroll > tab_bar.BarRect:GetWidth() and tabs.Size > 1) @@ -57460,23 +64023,26 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.SelectedTabId end + -- Shrink widths if full tabs don't fit in their allocated space local section_0_w = sections[1].Width + sections[1].Spacing local section_1_w = sections[2].Width + sections[2].Spacing local section_2_w = sections[3].Width + sections[3].Spacing local central_section_is_visible = (section_0_w + section_2_w) < tab_bar.BarRect:GetWidth() local width_excess if central_section_is_visible then - width_excess = ImMax(section_1_w - (tab_bar.BarRect:GetWidth() - section_0_w - section_2_w), 0.0) + width_excess = ImMax(section_1_w - (tab_bar.BarRect:GetWidth() - section_0_w - section_2_w), 0.0) -- Excess used to shrink central section else - width_excess = (section_0_w + section_2_w) - tab_bar.BarRect:GetWidth() + width_excess = (section_0_w + section_2_w) - tab_bar.BarRect:GetWidth() -- Excess used to shrink leading/trailing section end + -- With ImGuiTabBarFlags.FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore local can_shrink = bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyShrink) ~= 0 or bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyMixed) ~= 0 if width_excess >= 1.0 and (can_shrink or not central_section_is_visible) then local shrink_data_count = central_section_is_visible and sections[2].TabCount or (sections[1].TabCount + sections[3].TabCount) local shrink_data_offset = central_section_is_visible and (sections[1].TabCount + sections[3].TabCount) or 0 ImGui.ShrinkWidths(swb.Data, shrink_data_offset + 1, shrink_data_count, width_excess, shrink_min_width) + -- Apply shrunk values into tabs and sections for tab_n = shrink_data_offset, shrink_data_offset + shrink_data_count - 1 do local item = swb.Data[tab_n + 1] local tab = tabs.Data[item.Index + 1] @@ -57510,6 +64076,7 @@ function ImGui.TabBarLayout(tab_bar) section_tab_index = section_tab_index + section.TabCount end + -- If we have lost the selected tab, select the next most recently active one local tab_bar_appearing = (tab_bar.PrevFrameVisible + 1 < g.FrameCount) if found_selected_tab_id == false and not tab_bar_appearing then tab_bar.SelectedTabId = 0 @@ -57519,6 +64086,7 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.SelectedTabId end + -- Lock in visible tab tab_bar.VisibleTabId = tab_bar.SelectedTabId tab_bar.VisibleTabWasSubmitted = false @@ -57528,6 +64096,7 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.VisibleTabId end + -- Apply request requests if scroll_to_tab_id ~= 0 then ImGui.TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections) elseif tab_bar.ScrollButtonEnabled and ImGui.IsMouseHoveringRect(tab_bar.BarRect.Min, tab_bar.BarRect.Max, true) and ImGui.IsWindowContentHoverable(g.CurrentWindow) then @@ -57541,9 +64110,12 @@ function ImGui.TabBarLayout(tab_bar) ImGui.SetKeyOwner(wheel_key, tab_bar.ID) end + -- Update scrolling tab_bar.ScrollingAnim = ImGui.TabBarScrollClamp(tab_bar, tab_bar.ScrollingAnim) tab_bar.ScrollingTarget = ImGui.TabBarScrollClamp(tab_bar, tab_bar.ScrollingTarget) if tab_bar.ScrollingAnim ~= tab_bar.ScrollingTarget then + -- Scrolling speed adjust itself so we can always reach our target in 1/3 seconds. + -- Teleport if we are aiming far off the visible line tab_bar.ScrollingSpeed = ImMax(tab_bar.ScrollingSpeed, 70.0 * g.FontSize) tab_bar.ScrollingSpeed = ImMax(tab_bar.ScrollingSpeed, math.abs(tab_bar.ScrollingTarget - tab_bar.ScrollingAnim) / 0.3) local teleport = (tab_bar.PrevFrameVisible + 1 < g.FrameCount) or (tab_bar.ScrollingTargetDistToVisibility > 10.0 * g.FontSize) @@ -57554,12 +64126,14 @@ function ImGui.TabBarLayout(tab_bar) tab_bar.ScrollingRectMinX = tab_bar.BarRect.Min.x + sections[1].Width + sections[1].Spacing tab_bar.ScrollingRectMaxX = tab_bar.BarRect.Max.x - sections[3].Width - sections[2].Spacing + -- Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame) local window = g.CurrentWindow ImVec2_Copy(window.DC.CursorPos, tab_bar.BarRect.Min) ImGui.ItemSize(ImVec2(tab_bar.WidthAllTabs, tab_bar.BarRect:GetHeight()), tab_bar.FramePadding.y) window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, tab_bar.BarRect.Min.x + tab_bar.WidthAllTabsIdeal) end +-- Dockable windows uses Name/ID in the global namespace. Non-dockable items use the ID stack. function ImGui.TabBarCalcTabID(tab_bar, label, docked_window) if docked_window ~= nil then IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) ~= 0) @@ -57584,6 +64158,7 @@ function ImGui.TabBarFindTabByID(tab_bar, tab_id) return nil end +-- Order = visible order, not submission order! (which is tab.BeginOrder) --- @param order int # 0-based visible order function ImGui.TabBarFindTabByOrder(tab_bar, order) if order < 0 or order >= tab_bar.Tabs.Size then return nil end @@ -57596,6 +64171,7 @@ function ImGui.TabBarGetTabOrder(tab_bar, tab) return i and (i - 1) or -1 end +-- FIXME: See references to #2304 in TODO.txt function ImGui.TabBarFindMostRecentlySelectedTabForActiveWindow(tab_bar) local most_recently_selected_tab = nil for n = 1, tab_bar.Tabs.Size do @@ -57625,22 +64201,25 @@ function ImGui.TabBarGetTabPos(tab_bar, tab) return tab_bar.BarRect.Min + ImVec2(tab.Offset, 0.0) end +-- The purpose of this call is to register tab in advance so we can control their order at the time they appear. +-- Otherwise calling this is unnecessary as tabs are appending as needed by the BeginTabItem() function. function ImGui.TabBarAddTab(tab_bar, tab_flags, window) local g = ImGui.GetCurrentContext() IM_ASSERT(ImGui.TabBarFindTabByID(tab_bar, window.TabId) == nil) - IM_ASSERT(g.CurrentTabBar ~= tab_bar) + IM_ASSERT(g.CurrentTabBar ~= tab_bar) -- Can't work while the tab bar is active as our tab doesn't have an X offset yet, in theory we could/should test something like (tab_bar.CurrFrameVisible < g.FrameCount) but we'd need to solve why triggers the commented early-out assert in BeginTabBarEx() (probably dock node going from implicit to explicit in same frame) if not window.HasCloseButton then - tab_flags = bit32.bor(tab_flags, ImGuiTabItemFlags.NoCloseButton) + tab_flags = bit32.bor(tab_flags, ImGuiTabItemFlags.NoCloseButton) -- Set _NoCloseButton immediately because it will be used for first-frame width calculation. end local new_tab = ImGuiTabItem() new_tab.ID = window.TabId new_tab.Flags = tab_flags - new_tab.LastFrameVisible = tab_bar.CurrFrameVisible + new_tab.LastFrameVisible = tab_bar.CurrFrameVisible -- Required so BeginTabBar() doesn't ditch the tab if new_tab.LastFrameVisible == -1 then new_tab.LastFrameVisible = g.FrameCount - 1 end - new_tab.Window = window + new_tab.Window = window -- Required so tab bar layout can compute the tab width before tab submission tab_bar.Tabs:push_back(new_tab) end +-- The *TabId fields are already set by the docking system _before_ the actual TabItem was created, so we clear them regardless. function ImGui.TabBarRemoveTab(tab_bar, tab_id) local tab = ImGui.TabBarFindTabByID(tab_bar, tab_id) if tab then tab_bar.Tabs:erase(tab_bar.Tabs:find_index(tab)) end @@ -57649,9 +64228,13 @@ function ImGui.TabBarRemoveTab(tab_bar, tab_id) if tab_bar.NextSelectedTabId == tab_id then tab_bar.NextSelectedTabId = 0 end end +-- Called on manual closure attempt function ImGui.TabBarCloseTab(tab_bar, tab) - if bit32.band(tab.Flags, ImGuiTabItemFlags.Button) ~= 0 then return end + if bit32.band(tab.Flags, ImGuiTabItemFlags.Button) ~= 0 then return end -- A button appended with TabItemButton(). + if bit32.band(tab.Flags, bit32.bor(ImGuiTabItemFlags.UnsavedDocument, ImGuiTabItemFlags.NoAssumedClosure)) == 0 then + -- This will remove a frame of lag for selecting another tab on closure. + -- However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure tab.WantClose = true if tab_bar.VisibleTabId == tab.ID then tab.LastFrameVisible = -1 @@ -57659,6 +64242,7 @@ function ImGui.TabBarCloseTab(tab_bar, tab) tab_bar.NextSelectedTabId = 0 end else + -- Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup) if tab_bar.VisibleTabId ~= tab.ID then ImGui.TabBarQueueFocus(tab_bar, tab) end end end @@ -57668,10 +64252,13 @@ function ImGui.TabBarScrollClamp(tab_bar, scrolling) return ImMax(scrolling, 0.0) end +-- Note: we may scroll to tab that are not selected! e.g. using keyboard arrow keys function ImGui.TabBarScrollToTab(tab_bar, tab_id, sections) local tab = ImGui.TabBarFindTabByID(tab_bar, tab_id) if tab == nil then return end + -- Clamp attempt to scroll to leading/trailing sections items. + -- This could be done at the TabBarScrollingButtons() call site as well, but here works. if bit32.band(tab.Flags, ImGuiTabItemFlags.Leading) ~= 0 then tab = tab_bar.Tabs.Data[sections[1].TabCount + 1] elseif bit32.band(tab.Flags, ImGuiTabItemFlags.Trailing) ~= 0 then @@ -57679,18 +64266,25 @@ function ImGui.TabBarScrollToTab(tab_bar, tab_id, sections) end if tab == nil or bit32.band(tab.Flags, ImGuiTabItemFlags.SectionMask_) ~= 0 then return end + -- When scrolling to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) + -- Disable the margin if the scrolling section is too small for the target tab: prefer displaying a maximum of the label. local g = ImGui.GetCurrentContext() local margin = ImClamp(tab_bar.ScrollingRectMaxX - tab_bar.ScrollingRectMinX - tab.Width, g.Style.ItemInnerSpacing.x, g.FontSize * 1.0) local order = ImGui.TabBarGetTabOrder(tab_bar, tab) + + -- Scrolling happens only in the central section (leading/trailing sections are not scrolling) local scrollable_width = TabBarCalcScrollableWidth(tab_bar, sections) + -- We make all tabs positions all relative Sections[0].Width to make code simpler local tab_x1 = tab.Offset - sections[1].Width + ((order > sections[1].TabCount - 1) and -margin or 0.0) local tab_x2 = tab.Offset - sections[1].Width + tab.Width + ((order + 1 < tab_bar.Tabs.Size - sections[3].TabCount) and margin or 1.0) tab_bar.ScrollingTargetDistToVisibility = 0.0 if tab_bar.ScrollingTarget > tab_x1 or (tab_x2 - tab_x1 >= scrollable_width) then + -- Scroll to the left tab_bar.ScrollingTargetDistToVisibility = ImMax(tab_bar.ScrollingAnim - tab_x2, 0.0) tab_bar.ScrollingTarget = tab_x1 elseif tab_bar.ScrollingTarget < tab_x2 - scrollable_width then + -- Scroll to the right tab_bar.ScrollingTargetDistToVisibility = ImMax((tab_x1 - scrollable_width) - tab_bar.ScrollingAnim, 0.0) tab_bar.ScrollingTarget = tab_x2 - scrollable_width end @@ -57699,7 +64293,7 @@ end --- TabBarQueueFocus(tab_bar, tab) or TabBarQueueFocus(tab_bar, tab_name) function ImGui.TabBarQueueFocus(tab_bar, tab) if type(tab) == "string" then - IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0) + IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0) -- Only supported for manual/explicit tab bars tab_bar.NextSelectedTabId = ImGui.TabBarCalcTabID(tab_bar, tab, nil) return end @@ -57722,17 +64316,22 @@ function ImGui.TabBarQueueReorderFromMousePos(tab_bar, src_tab, mouse_pos) local is_central_section = bit32.band(src_tab.Flags, ImGuiTabItemFlags.SectionMask_) == 0 local bar_offset = tab_bar.BarRect.Min.x - (is_central_section and tab_bar.ScrollingTarget or 0) + -- Count number of contiguous tabs we are crossing over local dir = ((bar_offset + src_tab.Offset) > mouse_pos.x) and -1 or 1 local src_idx = ImGui.TabBarGetTabOrder(tab_bar, src_tab) local dst_idx = src_idx local i = src_idx while i >= 0 and i < tab_bar.Tabs.Size do + -- Reordered tabs must share the same section local dst_tab = tab_bar.Tabs.Data[i + 1] if bit32.band(dst_tab.Flags, ImGuiTabItemFlags.NoReorder) ~= 0 then break end if bit32.band(dst_tab.Flags, ImGuiTabItemFlags.SectionMask_) ~= bit32.band(src_tab.Flags, ImGuiTabItemFlags.SectionMask_) then break end dst_idx = i + + -- Include spacing after tab, so when mouse cursor is between tabs we would not continue checking further tabs that are not hovered. local x1 = bar_offset + dst_tab.Offset - tab_spacing local x2 = bar_offset + dst_tab.Offset + dst_tab.Width + tab_spacing + -- ImGui.GetForegroundDrawList():AddRect(ImVec2(x1, tab_bar.BarRect.Min.y), ImVec2(x2, tab_bar.BarRect.Max.y), IM_COL32(255, 0, 0, 255)) if (dir < 0 and mouse_pos.x > x1) or (dir > 0 and mouse_pos.x < x2) then break end i = i + dir end @@ -57746,10 +64345,13 @@ function ImGui.TabBarProcessReorder(tab_bar) local tab1 = ImGui.TabBarFindTabByID(tab_bar, tab_bar.ReorderRequestTabId) if tab1 == nil or bit32.band(tab1.Flags, ImGuiTabItemFlags.NoReorder) ~= 0 then return false end + -- IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.Reorderable) ~= 0) -- <- this may happen when using debug tools local tab1_order = ImGui.TabBarGetTabOrder(tab_bar, tab1) local tab2_order = tab1_order + tab_bar.ReorderRequestOffset if tab2_order < 0 or tab2_order >= tab_bar.Tabs.Size then return false end + -- Reordered tabs must share the same section + -- (Note: TabBarQueueReorderFromMousePos() also has a similar test but since we allow direct calls to TabBarQueueReorder() we do it here too) local tab2 = tab_bar.Tabs.Data[tab2_order + 1] if bit32.band(tab2.Flags, ImGuiTabItemFlags.NoReorder) ~= 0 then return false end if bit32.band(tab1.Flags, ImGuiTabItemFlags.SectionMask_) ~= bit32.band(tab2.Flags, ImGuiTabItemFlags.SectionMask_) then return false end @@ -57770,6 +64372,7 @@ function ImGui.TabBarScrollingButtons(tab_bar) local scrolling_buttons_width = arrow_button_size.x * 2.0 local backup_cursor_pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y) + -- window.DrawList:AddRect(ImVec2(tab_bar.BarRect.Max.x - scrolling_buttons_width, tab_bar.BarRect.Min.y), ImVec2(tab_bar.BarRect.Max.x, tab_bar.BarRect.Max.y), IM_COL32(255,0,0,255)) local select_dir = 0 local tc = g.Style.Colors[ImGuiCol.Text] @@ -57798,9 +64401,15 @@ function ImGui.TabBarScrollingButtons(tab_bar) if tab_item then local selected_order = ImGui.TabBarGetTabOrder(tab_bar, tab_item) local target_order = selected_order + select_dir + + -- Skip tab item buttons until another tab item is found or end is reached while tab_to_scroll_to == nil do + -- If we are at the end of the list, still scroll to make our tab visible local idx = (target_order >= 0 and target_order < tab_bar.Tabs.Size) and target_order or selected_order tab_to_scroll_to = tab_bar.Tabs.Data[idx + 1] + + -- Cross through buttons + -- (even if first/last item is a button, return it so we can update the scroll) if bit32.band(tab_to_scroll_to.Flags, ImGuiTabItemFlags.Button) ~= 0 then target_order = target_order + select_dir selected_order = selected_order + select_dir @@ -57819,6 +64428,7 @@ function ImGui.TabBarTabListPopupButton(tab_bar) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow + -- We use g.Style.FramePadding.y to match the square ArrowButton size local tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y local backup_cursor_pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y) ImVec2_CopyV(window.DC.CursorPos, tab_bar.BarRect.Min.x - g.Style.FramePadding.y, tab_bar.BarRect.Min.y) @@ -57848,9 +64458,18 @@ function ImGui.TabBarTabListPopupButton(tab_bar) return tab_to_select end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Widgets: BeginTabItem, EndTabItem, etc. ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - BeginTabItem() +-- - EndTabItem() +-- - TabItemButton() +-- - TabItemEx() [Internal] +-- - SetTabItemClosed() +-- - TabItemCalcSize() [Internal] +-- - TabItemBackground() [Internal] +-- - TabItemLabelAndCloseButton() [Internal] +------------------------------------------------------------------------------- --- @return bool visible, bool? p_open function ImGui.BeginTabItem(label, p_open, flags) @@ -57861,13 +64480,13 @@ function ImGui.BeginTabItem(label, p_open, flags) local tab_bar = g.CurrentTabBar IM_ASSERT(tab_bar ~= nil, "Needs to be called between BeginTabBar() and EndTabBar()!") - IM_ASSERT(bit32.band(flags, ImGuiTabItemFlags.Button) == 0) + IM_ASSERT(bit32.band(flags, ImGuiTabItemFlags.Button) == 0) -- BeginTabItem() Can't be used with button flags, use TabItemButton() instead! local ret ret, p_open = ImGui.TabItemEx(tab_bar, label, p_open, flags, nil) if ret and bit32.band(flags, ImGuiTabItemFlags.NoPushId) == 0 then local tab = tab_bar.Tabs.Data[tab_bar.LastTabItemIdx + 1] - ImGui.PushOverrideID(tab.ID) + ImGui.PushOverrideID(tab.ID) -- We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label) end return ret, p_open end @@ -57908,6 +64527,7 @@ end --- @return bool ret, bool? p_open function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) + -- Layout whole tab bar if not already done local g = ImGui.GetCurrentContext() if tab_bar.WantLayout then local backup_next_item_data = {} @@ -57921,14 +64541,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) local style = g.Style local id = ImGui.TabBarCalcTabID(tab_bar, label, docked_window) + -- If the user called us with p_open == false, we early out and don't render. + -- We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. if p_open ~= nil and not p_open then ImGui.ItemAdd(ImRect(), id, nil, ImGuiItemFlags.NoNav) return false, p_open end IM_ASSERT(p_open == nil or bit32.band(flags, ImGuiTabItemFlags.Button) == 0) - IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) ~= bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) + IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) ~= bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) -- Can't use both Leading and Trailing + -- Store into ImGuiTabItemFlags.NoCloseButton, also honor ImGuiTabItemFlags.NoCloseButton passed by user (although not documented) local has_p_open = (p_open ~= nil) if bit32.band(flags, ImGuiTabItemFlags.NoCloseButton) ~= 0 then has_p_open = false @@ -57936,6 +64559,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) flags = bit32.bor(flags, ImGuiTabItemFlags.NoCloseButton) end + -- Acquire tab data local tab = ImGui.TabBarFindTabByID(tab_bar, id) local tab_is_new = false if tab == nil then @@ -57947,6 +64571,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end tab_bar.LastTabItemIdx = ImGui.TabBarGetTabOrder(tab_bar, tab) + -- Calculate tab contents size local size = ImGui.TabItemCalcSize(label, has_p_open or bit32.band(flags, ImGuiTabItemFlags.UnsavedDocument) ~= 0) tab.RequestedWidth = -1.0 if bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasWidth) ~= 0 then @@ -57967,6 +64592,8 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) tab.Flags = flags tab.Window = docked_window + -- Append name (port: stored on tab.Name) + -- (regular tabs are permitted in a DockNode tab bar, but window tabs not permitted in a non-DockNode tab bar) if docked_window ~= nil then IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) ~= 0) tab.NameOffset = -1 @@ -57976,26 +64603,32 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) tab.Name = label end + -- Update selected tab if not is_tab_button then if tab_appearing and bit32.band(tab_bar.Flags, ImGuiTabBarFlags.AutoSelectNewTabs) ~= 0 and tab_bar.NextSelectedTabId == 0 then if not tab_bar_appearing or tab_bar.SelectedTabId == 0 then - ImGui.TabBarQueueFocus(tab_bar, tab) + ImGui.TabBarQueueFocus(tab_bar, tab) -- New tabs gets activated end end - if bit32.band(flags, ImGuiTabItemFlags.SetSelected) ~= 0 and tab_bar.SelectedTabId ~= id then + if bit32.band(flags, ImGuiTabItemFlags.SetSelected) ~= 0 and tab_bar.SelectedTabId ~= id then -- _SetSelected can only be passed on explicit tab bar ImGui.TabBarQueueFocus(tab_bar, tab) end end + -- Lock visibility + -- (Note: tab_contents_visible ~= tab_selected... because Ctrl+Tab operations may preview some tabs without selecting them!) local tab_contents_visible = (tab_bar.VisibleTabId == id) if tab_contents_visible then tab_bar.VisibleTabWasSubmitted = true end + -- On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches if not tab_contents_visible and tab_bar.SelectedTabId == 0 and tab_bar_appearing and docked_window == nil then if tab_bar.Tabs.Size == 1 and bit32.band(tab_bar.Flags, ImGuiTabBarFlags.AutoSelectNewTabs) == 0 then tab_contents_visible = true end end + -- Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted + -- and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. if tab_appearing and (not tab_bar_appearing or tab_is_new) then ImGui.ItemAdd(ImRect(), id, nil, ImGuiItemFlags.NoNav) if is_tab_button then return false, p_open end @@ -58004,14 +64637,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) if tab_bar.SelectedTabId == id then tab.LastFrameSelected = g.FrameCount end + -- Backup current layout position local backup_main_cursor_pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y) + -- Layout local is_central_section = bit32.band(tab.Flags, ImGuiTabItemFlags.SectionMask_) == 0 size.x = tab.Width local pos = ImGui.TabBarGetTabPos(tab_bar, tab) ImVec2_Copy(window.DC.CursorPos, pos) local bb = ImRect(pos, pos + size) + -- We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) local want_clip_rect = is_central_section and (bb.Min.x < tab_bar.ScrollingRectMinX or bb.Max.x > tab_bar.ScrollingRectMaxX) if want_clip_rect then ImGui.PushClipRect(ImVec2(ImClamp(bb.Min.x, tab_bar.ScrollingRectMinX, tab_bar.ScrollingRectMaxX), bb.Min.y - 1), ImVec2(tab_bar.ScrollingRectMaxX, bb.Max.y), true) @@ -58027,8 +64663,9 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) return tab_contents_visible, p_open end + -- Click to Select a tab local button_flags = bit32.bor(is_tab_button and ImGuiButtonFlags.PressedOnClickRelease or ImGuiButtonFlags.PressedOnClick, ImGuiButtonFlags.AllowOverlap) - if g.DragDropActive and not ImGuiPayload_IsDataType(g.DragDropPayload, IMGUI_PAYLOAD_TYPE_WINDOW) then + if g.DragDropActive and not ImGuiPayload_IsDataType(g.DragDropPayload, IMGUI_PAYLOAD_TYPE_WINDOW) then -- FIXME: May be an opt-in property of the payload to disable this button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnDragDropHold) end local hovered, held, pressed @@ -58039,18 +64676,24 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end if pressed and not is_tab_button then ImGui.TabBarQueueFocus(tab_bar, tab) end + -- Transfer active id window so the active id is not owned by the dock host (as StartMouseMovingWindow() + -- will only do it on the drag). This allows FocusWindow() to be more conservative in how it clears active id. if held and docked_window and g.ActiveId == id and g.ActiveIdIsJustActivated then g.ActiveIdWindow = docked_window end + -- Drag and drop a single floating window node moves it local node = docked_window and docked_window.DockNode or nil local single_floating_window_node = node and node:IsFloatingNode() and (node.Windows.Size == 1) if held and single_floating_window_node and ImGui.IsMouseDragging(0, 0.0) then + -- Move ImGui.StartMouseMovingWindow(docked_window) elseif held and not tab_appearing and ImGui.IsMouseDragging(0) then + -- Drag and drop: re-order tabs local drag_dir = 0 local drag_distance_from_edge_x = 0.0 if not g.DragDropActive and (bit32.band(tab_bar.Flags, ImGuiTabBarFlags.Reorderable) ~= 0 or docked_window ~= nil) then + -- While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x if g.IO.MouseDelta.x < 0.0 and g.IO.MousePos.x < bb.Min.x then drag_dir = -1 drag_distance_from_edge_x = bb.Min.x - g.IO.MousePos.x @@ -58062,13 +64705,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end end + -- Extract a Dockable window out of it's tab bar local can_undock = docked_window ~= nil and bit32.band(docked_window.Flags, ImGuiWindowFlags.NoMove) == 0 and bit32.band(node.MergedFlags, ImGuiDockNodeFlags.NoUndocking) == 0 if can_undock then + -- We use a variable threshold to distinguish dragging tabs within a tab bar and extracting them out of the tab bar local undocking_tab = (g.DragDropActive and g.DragDropPayload.SourceId == id) - if not undocking_tab then + if not undocking_tab then -- and (not g.IO.ConfigDockingWithShift or g.IO.KeyShift) local threshold_base = g.FontSize local threshold_x = threshold_base * 2.2 local threshold_y = (threshold_base * 1.5) + ImClamp((math.abs(g.IO.MouseDragMaxDistanceAbs[0].x) - threshold_base * 2.0) * 0.20, 0.0, threshold_base * 4.0) + -- ImGui.GetForegroundDrawList():AddRect(ImVec2(bb.Min.x - threshold_x, bb.Min.y - threshold_y), ImVec2(bb.Max.x + threshold_x, bb.Max.y + threshold_y), IM_COL32_WHITE) -- [DEBUG] + local distance_from_edge_y = ImMax(bb.Min.y - g.IO.MousePos.y, g.IO.MousePos.y - bb.Max.y) if distance_from_edge_y >= threshold_y then undocking_tab = true end if drag_distance_from_edge_x > threshold_x then @@ -58079,6 +64726,8 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end if undocking_tab then + -- Undock + -- FIXME: refactor to share more code with e.g. StartMouseMovingWindow ImGui.DockContextQueueUndockWindow(g, docked_window) g.MovingWindow = docked_window ImGui.SetActiveID(g.MovingWindow.MoveId, g.MovingWindow) @@ -58089,6 +64738,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end end + -- Render tab shape local is_visible = bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 and bit32.band(flags, ImGuiTabItemFlags.Invisible) == 0 if is_visible then local display_draw_list = window.DrawList @@ -58098,6 +64748,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) else col_idx = tab_bar_focused and ImGuiCol.Tab or ImGuiCol.TabDimmed end ImGui.TabItemBackground(display_draw_list, bb, flags, ImGui.GetColorU32(col_idx)) if tab_contents_visible and bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DrawSelectedOverline) ~= 0 and style.TabBarOverlineSize > 0.0 then + -- Might be moved to TabItemBackground() ? local tl = ImVec2(bb.Min.x, bb.Min.y + style.TabBarOverlineSize * 0.5) local tr = ImVec2(bb.Max.x, bb.Min.y + style.TabBarOverlineSize * 0.5) local overline_col = ImGui.GetColorU32(tab_bar_focused and ImGuiCol.TabSelectedOverline or ImGuiCol.TabDimmedSelectedOverline) @@ -58112,6 +64763,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end ImGui.RenderNavCursor(bb, id) + -- Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. local hovered_unblocked = ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByPopup) if tab_bar.SelectedTabId ~= tab.ID and hovered_unblocked and (ImGui.IsMouseClicked(1) or ImGui.IsMouseReleased(1)) and not is_tab_button then ImGui.TabBarQueueFocus(tab_bar, tab) @@ -58121,6 +64773,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) flags = bit32.bor(flags, ImGuiTabItemFlags.NoCloseWithMiddleMouseButton) end + -- Render tab label, process close button local close_button_id = has_p_open and ImGui.GetIDWithSeed("#CLOSE", nil, docked_window and docked_window.ID or id) or 0 local label_flags = tab_just_unsaved and bit32.band(flags, bit32.bnot(ImGuiTabItemFlags.UnsavedDocument)) or flags local just_closed, text_clipped = ImGui.TabItemLabelAndCloseButton(display_draw_list, bb, label_flags, tab_bar.FramePadding, label, id, close_button_id, tab_contents_visible) @@ -58129,10 +64782,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) ImGui.TabBarCloseTab(tab_bar, tab) end + -- 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 and (hovered or g.HoveredId == close_button_id) then g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end + -- 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 and g.HoveredId == id and not held then if bit32.band(tab_bar.Flags, ImGuiTabBarFlags.NoTooltip) == 0 and bit32.band(tab.Flags, ImGuiTabItemFlags.NoTooltip) == 0 then local label_end = ImGui.FindRenderedTextEnd(label) @@ -58141,6 +64801,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end end + -- Restore main window position so user can draw there if want_clip_rect then ImGui.PopClipRect() end ImVec2_Copy(window.DC.CursorPos, backup_main_cursor_pos) @@ -58148,6 +64809,9 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) return tab_contents_visible, p_open end +-- [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. +-- To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar(). +-- Tabs closed by the close button will automatically be flagged to avoid this issue. function ImGui.SetTabItemClosed(label) local g = ImGui.GetCurrentContext() local is_within_manual_tab_bar = g.CurrentTabBar and bit32.band(g.CurrentTabBar.Flags, ImGuiTabBarFlags.DockNode) == 0 @@ -58155,7 +64819,7 @@ function ImGui.SetTabItemClosed(label) local tab_bar = g.CurrentTabBar local tab_id = ImGui.TabBarCalcTabID(tab_bar, label, nil) local tab = ImGui.TabBarFindTabByID(tab_bar, tab_id) - if tab then tab.WantClose = true end + if tab then tab.WantClose = true end -- Will be processed by next call to TabBarLayout() else local window = ImGui.FindWindowByName(label) if window and window.DockIsActive then @@ -58179,7 +64843,7 @@ function ImGui.TabItemCalcSize(label, has_close_button_or_unsaved_marker) local label_size = ImGui.CalcTextSize(label, nil, true) local size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0) if has_close_button_or_unsaved_marker then - size.x = size.x + g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize) + size.x = size.x + g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize) -- We use Y intentionally to fit the close button circle. else size.x = size.x + g.Style.FramePadding.x + 1.0 end @@ -58187,11 +64851,12 @@ function ImGui.TabItemCalcSize(label, has_close_button_or_unsaved_marker) end function ImGui.TabItemBackground(draw_list, bb, flags, col) + -- While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it. local g = ImGui.GetCurrentContext() local width = bb:GetWidth() IM_ASSERT(width > 0.0) local rounding = ImMax(0.0, ImMin(bit32.band(flags, ImGuiTabItemFlags.Button) ~= 0 and g.Style.FrameRounding or g.Style.TabRounding, width * 0.5 - 1.0)) - local y1 = bb.Min.y + 1.0 + local y1 = bb.Min.y + 1.0 -- Leave a bit of room in title bars. local y2 = bb.Max.y - g.Style.TabBarBorderSize draw_list:AddRectFilled(ImVec2(bb.Min.x, y1), ImVec2(bb.Max.x, y2), col, rounding, ImDrawFlags.RoundCornersTop) if g.Style.TabBorderSize > 0.0 then @@ -58203,6 +64868,8 @@ function ImGui.TabItemBackground(draw_list, bb, flags, col) end end +-- Render text label (with custom clipping) + Unsaved Document marker + Close Button logic +-- We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. --- @return bool just_closed, bool text_clipped function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, label, tab_id, close_button_id, is_contents_visible) local g = ImGui.GetCurrentContext() @@ -58211,15 +64878,24 @@ function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, l if bb:GetWidth() <= 1.0 then return false, false end + -- Render text label (with clipping + alpha gradient) + unsaved marker local text_ellipsis_clip_bb = ImRect(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 local 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.0, text_clipped and IM_COL32(255, 0, 0, 255) or IM_COL32(0, 255, 0, 255)) local button_sz = g.FontSize local button_pos = ImVec2(ImMax(bb.Min.x, bb.Max.x - frame_padding.x - button_sz), bb.Min.y + frame_padding.y) + -- Close Button & Unsaved Marker + -- We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap() + -- 'hovered' will be true when hovering the Tab but NOT when hovering the close button + -- 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button + -- 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false local close_button_pressed = false local close_button_visible = false - local is_hovered = g.HoveredId == tab_id or g.HoveredId == close_button_id or g.ActiveId == tab_id or g.ActiveId == close_button_id + local is_hovered = g.HoveredId == tab_id or g.HoveredId == close_button_id or g.ActiveId == tab_id or g.ActiveId == close_button_id -- Any interaction account for this too. if close_button_id ~= 0 then if is_contents_visible then @@ -58229,6 +64905,7 @@ function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, l end end + -- When tabs/document is unsaved, the unsaved marker takes priority over the close button. local unsaved_marker_visible = bit32.band(flags, ImGuiTabItemFlags.UnsavedDocument) ~= 0 and (button_pos.x + button_sz <= bb.Max.x) and (not close_button_visible or not is_hovered) if unsaved_marker_visible then local bullet_pos = button_pos + ImVec2(button_sz, button_sz) * 0.5 @@ -58239,11 +64916,15 @@ function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, l if ImGui.CloseButton(close_button_id, button_pos) then close_button_pressed = true end ImGuiLastItemData_Copy(g.LastItemData, last_item_backup) + -- Close with middle mouse button if is_hovered and bit32.band(flags, ImGuiTabItemFlags.NoCloseWithMiddleMouseButton) == 0 and ImGui.IsMouseClicked(2) then close_button_pressed = true end end + -- 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.. local ellipsis_max_x = text_ellipsis_clip_bb.Max.x if close_button_visible or unsaved_marker_visible then local visible_without_hover = unsaved_marker_visible or ((is_contents_visible and g.Style.TabCloseButtonMinWidthSelected or g.Style.TabCloseButtonMinWidthUnselected) < 0.0) @@ -58271,6 +64952,63 @@ __FILES['imstb_rectpack.lua'] = function() -- ALL TABLES IN THIS FILE ARE 1-BASED! -- Avoids table creation when possible +-- [DEAR IMGUI] +-- This is a slightly modified version of stb_rect_pack.h 1.01. +-- Grep for [DEAR IMGUI] to find the changes. +-- +-- stb_rect_pack.h - v1.01 - public domain - rectangle packing +-- Sean Barrett 2014 +-- +-- Useful for e.g. packing rectangular textures into an atlas. +-- Does not do rotation. +-- +-- Not necessarily the awesomest packing method, but better than +-- the totally naive one in stb_truetype (which is primarily what +-- this is meant to replace). +-- +-- Has only had a few tests run, may have issues. +-- +-- More docs to come. +-- +-- Uses table.sort and assert (STBRP_SORT and STBRP_ASSERT below). +-- +-- This library currently uses the Skyline Bottom-Left algorithm. +-- +-- Please note: better rectangle packers are welcome! Please +-- implement them to the same API, but with a different init +-- function. +-- +-- Credits +-- +-- Library +-- Sean Barrett +-- Minor features +-- Martins Mozeiko +-- github:IntellectualKitty +-- +-- Bugfixes / warning fixes +-- Jeremy Jaussaud +-- Fabian Giesen +-- +-- Version history: +-- +-- 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section +-- 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles +-- 0.99 (2019-02-07) warning fixes +-- 0.11 (2017-03-03) return packing success/fail result +-- 0.10 (2016-10-25) remove cast-away-const to avoid warnings +-- 0.09 (2016-08-27) fix compiler warnings +-- 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) +-- 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) +-- 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort +-- 0.05: added STBRP_ASSERT to allow replacing assert +-- 0.04: fixed minor bug in STBRP_LARGE_RECTS support +-- 0.01: initial release +-- +-- LICENSE +-- +-- See end of file for license information. + --- The `prev_link` can be stbrp_context or stbrp_node --- @diagnostic disable @@ -58280,7 +65018,13 @@ local STBRP_SORT = table.sort local STBRP_ASSERT = assert local STBRP__NOTUSED = function(_) end +------------------------------------------------------------------------------- +-- +-- INCLUDE SECTION +-- + local STBRP__MAXVAL = 0x7fffffff +-- Mostly for internal use, but this is the maximum supported coordinate value. --- @enum STBRP_HEURISTIC_Skyline local STBRP_HEURISTIC_Skyline = { @@ -58311,12 +65055,17 @@ local STBRP__PREV_LINK_TYPE = { --- @nodiscard local function stbrp_rect() return { + -- reserved for your use: id = 0, + + -- input: w = 0, h = 0, + + -- output: x = 0, y = 0, - was_packed = 0 + was_packed = 0 -- non-zero if valid packing } end @@ -58359,7 +65108,7 @@ local function stbrp_context() active_head = nil, free_head = nil, - extra = {stbrp_node(), stbrp_node()} + extra = {stbrp_node(), stbrp_node()} -- we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' } end @@ -58380,13 +65129,14 @@ local function stbrp__findresult() } end --------------------------- --------------------------- ---- ---- IMPLEMENTATION SECTION ---- ---- +------------------------------------------------------------------------------- +-- +-- IMPLEMENTATION SECTION +-- +-- Optionally select which packing heuristic the library should use. Different +-- heuristics will produce better/worse results for different data sets. +-- If you call init again, this will be reset to the default. --- @param context stbrp_context --- @param heuristic int local function stbrp_setup_heuristic(context, heuristic) @@ -58398,16 +65148,49 @@ local function stbrp_setup_heuristic(context, heuristic) end end +-- Optionally call this function after init but before doing any packing to +-- change the handling of the out-of-temp-memory scenario, described above. +-- If you call init again, this will be reset to the default (false). --- @param context stbrp_context --- @param allow_out_of_mem boolean local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem) if allow_out_of_mem then + -- if it's ok to run out of memory, then don't bother aligning them; + -- this gives better packing, but may fail due to OOM (even though + -- the rectangles easily fit). @TODO a smarter approach would be to only + -- quantize once we've hit OOM, then we could get rid of this parameter. context.align = 1 else + -- if it's not ok to run out of memory, then quantize the widths + -- so that num_nodes is always enough nodes. + -- + -- I.e. num_nodes * align >= width + -- align >= width / num_nodes + -- align = ceil(width/num_nodes) + context.align = (context.width + context.num_nodes - 1) / context.num_nodes end end +-- Initialize a rectangle packer to: +-- pack a rectangle that is 'width' by 'height' in dimensions +-- using temporary storage provided by the array 'nodes', which is 'num_nodes' long +-- +-- You must call this function every time you start packing into a new target. +-- +-- There is no "shutdown" function. The 'nodes' memory must stay valid for +-- the following stbrp_pack_rects() call (or calls), but can be freed after +-- the call (or calls) finish. +-- +-- Note: to guarantee best results, either: +-- 1. make sure 'num_nodes' >= 'width' +-- or 2. call stbrp_setup_allow_out_of_mem() defined above with 'allow_out_of_mem = true' +-- +-- If you don't do either of the above things, widths will be quantized to multiples +-- of small integers to guarantee the algorithm doesn't run out of temporary storage. +-- +-- If you do #2, then the non-quantized algorithm will be used, but the algorithm +-- may run out of temporary storage and be unable to pack some rectangles. --- @param context stbrp_context --- @param width int --- @param height int @@ -58427,6 +65210,7 @@ function stbrp_init_target(context, width, height, nodes, num_nodes) context.num_nodes = num_nodes stbrp_setup_allow_out_of_mem(context, false) + -- node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) context.extra[1].x = 0 context.extra[1].y = 0 context.extra[1].next = context.extra[2] @@ -58435,6 +65219,8 @@ function stbrp_init_target(context, width, height, nodes, num_nodes) context.extra[2].next = nil end +-- find minimum y position if it starts at x1 +-- Returns (min_y, waste_area) --- @param c stbrp_context --- @param first stbrp_node --- @param x0 int @@ -58448,7 +65234,7 @@ local function stbrp__skyline_find_min_y(c, first, x0, width) STBRP_ASSERT(first.x <= x0) - STBRP_ASSERT(node.next.x > x0) + STBRP_ASSERT(node.next.x > x0) -- we ended up handling this in the caller for efficiency STBRP_ASSERT(node.x <= x0) @@ -58457,14 +65243,19 @@ local function stbrp__skyline_find_min_y(c, first, x0, width) local visited_width = 0 while node.x < x1 do if node.y > min_y then + -- raise min_y higher. + -- we've accounted for all waste up to min_y, + -- but we'll now add more waste for everything we've visited waste_area = waste_area + visited_width * (node.y - min_y) min_y = node.y + -- the first time through, visited_width might be reduced if node.x < x0 then visited_width = visited_width + node.next.x - x0 else visited_width = visited_width + node.next.x - node.x end else + -- add waste area local under_width = node.next.x - node.x if under_width + visited_width > width then under_width = width - visited_width @@ -58490,10 +65281,12 @@ local function stbrp__skyline_find_best_pos(c, width, height) local best_prev_link = nil local best_prev_link_type = nil + -- align to multiple of c.align width = width + c.align - 1 width = width - width % c.align STBRP_ASSERT(width % c.align == 0) + -- if it can't possibly fit, bail immediately if width > c.width or height > c.height then fr.prev_link = nil fr.prev_link_type = nil @@ -58509,7 +65302,8 @@ local function stbrp__skyline_find_best_pos(c, width, height) while (node.x + width <= c.width) do local y, waste = stbrp__skyline_find_min_y(c, node, node.x, width) - if c.heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight then + if c.heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight then -- actually just want to test BL + -- bottom left if y < best_y then best_y = y best_prev_link = prev_link @@ -58517,7 +65311,9 @@ local function stbrp__skyline_find_best_pos(c, width, height) best_x = node.x end else + -- best-fit if y + height <= c.height then + -- can only use it if it first vertically if y < best_y or (y == best_y and waste < best_waste) then best_y = y best_waste = waste @@ -58533,12 +65329,30 @@ local function stbrp__skyline_find_best_pos(c, width, height) node = node.next end + -- if doing best-fit (BF), we also have to try aligning right edge to each node position + -- + -- e.g, if fitting + -- + -- ____________________ + -- |____________________| + -- + -- into + -- + -- | | + -- | ____________| + -- |____________| + -- + -- then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned + -- + -- This makes BF take about 2x the time + if c.heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight then local tail = c.active_head local node_scan = c.active_head local prev_link_scan = c local prev_link_scan_type = STBRP__PREV_LINK_TYPE.ACTIVE_HEAD + -- find first node that's admissible while tail and tail.x < width do tail = tail.next end @@ -58547,6 +65361,7 @@ local function stbrp__skyline_find_best_pos(c, width, height) local xpos = tail.x - width STBRP_ASSERT(xpos >= 0) + -- find the left position that matches this while node_scan.next and node_scan.next.x <= xpos do prev_link_scan = node_scan prev_link_scan_type = STBRP__PREV_LINK_TYPE.NEXT @@ -58562,6 +65377,7 @@ local function stbrp__skyline_find_best_pos(c, width, height) if y <= best_y then if y < best_y or waste < best_waste or (waste == best_waste and xpos < best_x) then best_x = xpos + -- STBRP_ASSERT(y <= best_y); [DEAR IMGUI] best_y = y best_waste = waste best_prev_link = prev_link_scan @@ -58587,19 +65403,29 @@ end --- @param height int --- @return stbrp__findresult local function stbrp__skyline_pack_rectangle(context, width, height) + -- find best position according to heuristic local res = stbrp__skyline_find_best_pos(context, width, height) + -- bail if: + -- 1. it failed + -- 2. the best node doesn't fit (we don't always check this) + -- 3. we're out of memory if res.prev_link == nil or res.y + height > context.height or context.free_head == nil then res.prev_link = nil res.prev_link_type = nil return res end + -- on success, create new node local node = context.free_head node.x = res.x node.y = res.y + height context.free_head = node.next + -- insert the new node into the right starting point, and + -- let 'cur' point to the remaining nodes needing to be + -- stitched back in + local cur if res.prev_link_type == STBRP__PREV_LINK_TYPE.ACTIVE_HEAD then cur = res.prev_link.active_head @@ -58608,6 +65434,7 @@ local function stbrp__skyline_pack_rectangle(context, width, height) end if cur.x < res.x then + -- preserve the existing one, so start testing with the next one local next = cur.next cur.next = node cur = next @@ -58619,13 +65446,17 @@ local function stbrp__skyline_pack_rectangle(context, width, height) end end + -- from here, traverse cur and free the nodes, until we get to one + -- that shouldn't be freed while cur.next and cur.next.x <= res.x + width do local next = cur.next + -- move the current node to the free list cur.next = context.free_head context.free_head = cur cur = next end + -- stitch the list back in node.next = cur if cur.x < res.x + width then @@ -58657,6 +65488,29 @@ local function rect_original_order(a, b) return a.was_packed < b.was_packed end +-- Assign packed locations to rectangles. The rectangles are of type +-- 'stbrp_rect' defined above, stored in the array 'rects', and there +-- are 'num_rects' many of them. +-- +-- Rectangles which are successfully packed have the 'was_packed' flag +-- set to a non-zero value and 'x' and 'y' store the minimum location +-- on each axis (i.e. bottom-left in cartesian coordinates, top-left +-- if you imagine y increasing downwards). Rectangles which do not fit +-- have the 'was_packed' flag set to 0. +-- +-- You should not try to access the 'rects' array from another thread +-- while this function is running, as the function temporarily reorders +-- the array while it executes. +-- +-- To pack into another rectangle, you need to call stbrp_init_target +-- again. To continue packing into the same rectangle, you can call +-- this function again. Calling this multiple times with multiple rect +-- arrays will probably produce worse packing results than calling it +-- a single time with the full rectangle array, but the option is +-- available. +-- +-- The function returns 1 if all of the rectangles were successfully +-- packed and 0 otherwise. --- @param context stbrp_context --- @param rects stbrp_rect[] --- @param num_rects int @@ -58664,15 +65518,17 @@ end local function stbrp_pack_rects(context, rects, num_rects) local all_rects_packed = 1 + -- we use the 'was_packed' field internally to allow sorting/unsorting for i = 1, num_rects do rects[i].was_packed = (i - 1) end + -- sort according to heuristic STBRP_SORT(rects, rect_height_compare) for i = 1, num_rects do if rects[i].w == 0 or rects[i].h == 0 then - rects[i].x = 0 + rects[i].x = 0 -- empty rect needs no space rects[i].y = 0 else local fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h) @@ -58686,8 +65542,10 @@ local function stbrp_pack_rects(context, rects, num_rects) end end + -- unsort STBRP_SORT(rects, rect_original_order) + -- set was_packed flags and all_rects_packed status for i = 1, num_rects do rects[i].was_packed = (rects[i].x == STBRP__MAXVAL and rects[i].y == STBRP__MAXVAL) and 0 or 1 if rects[i].was_packed == 0 then @@ -58695,6 +65553,7 @@ local function stbrp_pack_rects(context, rects, num_rects) end end + -- return the all_rects_packed status return all_rects_packed end @@ -58708,12 +65567,267 @@ return { setup_allow_out_of_mem = stbrp_setup_allow_out_of_mem, setup_heuristic = stbrp_setup_heuristic } + +-- ------------------------------------------------------------------------------ +-- This software is available under 2 licenses -- choose whichever you prefer. +-- ------------------------------------------------------------------------------ +-- ALTERNATIVE A - MIT License +-- Copyright (c) 2017 Sean Barrett +-- Permission is hereby granted, free of charge, to any person obtaining a copy of +-- this software and associated documentation files (the "Software"), to deal in +-- the Software without restriction, including without limitation the rights to +-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +-- of the Software, and to permit persons to whom the Software is furnished to do +-- so, subject to the following conditions: +-- The above copyright notice and this permission notice shall be included in all +-- copies or substantial portions of the Software. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +-- SOFTWARE. +-- ------------------------------------------------------------------------------ +-- ALTERNATIVE B - Public Domain (www.unlicense.org) +-- This is free and unencumbered software released into the public domain. +-- Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +-- software, either in source code form or as a compiled binary, for any purpose, +-- commercial or non-commercial, and by any means. +-- In jurisdictions that recognize copyright laws, the author or authors of this +-- software dedicate any and all copyright interest in the software to the public +-- domain. We make this dedication for the benefit of the public at large and to +-- the detriment of our heirs and successors. We intend this dedication to be an +-- overt act of relinquishment in perpetuity of all present and future rights to +-- this software under copyright law. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +-- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-- ------------------------------------------------------------------------------ end __FILES['imstb_textedit.lua'] = function() --- Dear ImGui -- This is a Lua port of original `imstb_textedit.h` +-- [DEAR IMGUI] +-- This is a slightly modified version of stb_textedit.h 1.14. +-- Those changes would need to be pushed into nothings/stb: +-- - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) +-- - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783) +-- - Added name to struct or it may be forward declared in our code. +-- - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925) +-- - Changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +-- Grep for [DEAR IMGUI] to find some changes. +-- - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_* + +-- stb_textedit.h - v1.14 - public domain - Sean Barrett +-- Development of this library was sponsored by RAD Game Tools +-- +-- This C header file implements the guts of a multi-line text-editing +-- widget; you implement display, word-wrapping, and low-level string +-- insertion/deletion, and stb_textedit will map user inputs into +-- insertions & deletions, plus updates to the cursor position, +-- selection state, and undo state. +-- +-- It is intended for use in games and other systems that need to build +-- their own custom widgets and which do not have heavy text-editing +-- requirements (this library is not recommended for use for editing large +-- texts, as its performance does not scale and it has limited undo). +-- +-- Non-trivial behaviors are modelled after Windows text controls. +-- +-- +-- LICENSE +-- +-- See end of file for license information. +-- +-- +-- DEPENDENCIES +-- +-- Uses the C runtime function 'memmove', which you can override +-- by defining IMSTB_TEXTEDIT_memmove before the implementation. +-- (In this port: ImStb.TEXTEDIT_memmove.) +-- +-- +-- VERSION HISTORY +-- +-- !!!! (2025-10-23) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +-- 1.14 (2021-07-11) page up/down, various fixes +-- 1.13 (2019-02-07) fix bug in undo size management +-- 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash +-- 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield +-- 1.10 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +-- 1.9 (2016-08-27) customizable move-by-word +-- 1.8 (2016-04-02) better keyboard handling when mouse button is down +-- 1.7 (2015-09-13) change y range handling in case baseline is non-0 +-- 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove +-- 1.5 (2014-09-10) add support for secondary keys for OS X +-- 1.4 (2014-08-17) fix signed/unsigned warnings +-- 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary +-- 1.2 (2014-05-27) fix some RAD types that had crept into the new code +-- 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) +-- 1.0 (2012-07-26) improve documentation, initial public release +-- 0.3 (2012-02-24) bugfixes, single-line mode; insert mode +-- 0.2 (2011-11-28) fixes to undo/redo +-- 0.1 (2010-07-08) initial version +-- +-- ADDITIONAL CONTRIBUTORS +-- +-- Ulf Winklemann: move-by-word in 1.1 +-- Fabian Giesen: secondary key inputs in 1.5 +-- Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6 +-- Louis Schnellbach: page up/down in 1.14 +-- +-- Bugfixes: +-- Scott Graham +-- Daniel Keller +-- Omar Cornut +-- Dan Thompson +-- +-- USAGE +-- +-- The basic concept is that you provide a "string" object which +-- behaves like an array of characters. stb_textedit uses indices to +-- refer to positions in the string, implicitly representing positions +-- in the displayed textedit. This is true for both plain text and +-- rich text; even with rich text stb_truetype interacts with your +-- code as if there was an array of all the displayed characters. +-- +-- Symbols you must define for implementation mode (in this port: fields of ImStb, see below): +-- +-- STB_TEXTEDIT_STRING the type of object representing a string being edited, +-- typically this is a wrapper object with other data you need +-- +-- STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) +-- STB_TEXTEDIT_LAYOUTROW(r,obj,n) returns the results of laying out a line of characters +-- starting from character #n (see discussion below) +-- STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character +-- to the xpos of the i+1'th char for a line of characters +-- starting at character #n (i.e. accounts for kerning +-- with previous char) +-- STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 1-based in this port +-- STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize +-- as manually wordwrapping for end-of-line positioning +-- +-- STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i +-- STB_TEXTEDIT_INSERTCHARS(obj,i,c,c_offset,n) try to insert n characters at i (taken from array c starting at c_offset) +-- returns number of characters actually inserted. [DEAR IMGUI] +-- +-- STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key +-- +-- STB_TEXTEDIT_K_LEFT keyboard input to move cursor left +-- STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right +-- STB_TEXTEDIT_K_UP keyboard input to move cursor up +-- STB_TEXTEDIT_K_DOWN keyboard input to move cursor down +-- STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page +-- STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page +-- STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line -- e.g. HOME +-- STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line -- e.g. END +-- STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text -- e.g. ctrl-HOME +-- STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text -- e.g. ctrl-END +-- STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor +-- STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor +-- STB_TEXTEDIT_K_UNDO keyboard input to perform undo +-- STB_TEXTEDIT_K_REDO keyboard input to perform redo +-- +-- STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to +-- STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to +-- STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word -- e.g. ctrl-LEFT +-- STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word -- e.g. ctrl-RIGHT +-- +-- 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, +-- i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. +-- +-- STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed +-- row of characters assuming they start on the i'th character--the width and +-- the height and the number of characters consumed. This allows this library +-- to traverse the entire layout incrementally. You need to compute word-wrapping +-- here. +-- +-- Each textfield keeps its own insert mode state, which is not how normal +-- applications work. To keep an app-wide insert mode, update/copy the +-- "insert_mode" field of STB_TexteditState before/after calling API functions. +-- +-- API (in this port: fields of the table returned by this file) +-- +-- initialize_state(state, is_single_line) +-- +-- click(str, state, x, y) +-- drag(str, state, x, y) +-- cut(str, state) -> bool +-- paste(str, state, text, len) -> bool +-- key(str, state, key) +-- text(str, state, text, text_len) +-- +-- Each of these functions potentially updates the string and updates the +-- state. +-- +-- initialize_state: +-- set the textedit state to a known good default state when initially +-- constructing the textedit. +-- +-- click: +-- call this with the mouse x,y on a mouse down; it will update the cursor +-- and reset the selection start/end to the cursor point. the x,y must +-- be relative to the text widget, with (0,0) being the top left. +-- +-- drag: +-- call this with the mouse x,y on a mouse drag/up; it will update the +-- cursor and the selection end point +-- +-- cut: +-- call this to delete the current selection; returns true if there was +-- one. you should FIRST copy the current selection to the system paste buffer. +-- (To copy, just copy the current selection out of the string yourself.) +-- +-- paste: +-- call this to paste text at the current cursor point or over the current +-- selection if there is one. +-- +-- key: +-- call this for keyboard inputs sent to the textfield. you can use it +-- for "key down" events or for "translated" key events. +-- +-- 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 +-- the STB_TexteditState. +-- +-- +-- Notes: +-- +-- This is designed to be usable in IMGUI, so it allows for the possibility of +-- running in an IMGUI that has NOT cached the multi-line layout. For this +-- reason, it provides an interface that is compatible with computing the +-- layout incrementally--we try to make sure we make as few passes through +-- as possible. (For example, to locate the mouse pointer in the text, we +-- could define functions that return the X and Y positions of characters +-- and binary search Y and then X, but if we're doing dynamic layout this +-- will run the layout algorithm many times, so instead we manually search +-- forward in one pass. Similar logic applies to e.g. up-arrow and +-- down-arrow movement.) +-- +-- If it's run in a widget that *has* cached the layout, then this is less +-- efficient, but it's not horrible on modern computers. But you wouldn't +-- want to edit million-line files with it. + -- ALL TABLES IN THIS FILE ARE 1-BASED! -- Character Indexing: -- idx=n, the n'th char (1-based) @@ -58726,6 +65840,10 @@ local STB_TEXTEDIT_STRINGLEN = ImStb.TEXTEDIT_STRINGLEN local STB_TEXTEDIT_GETCHAR = ImStb.TEXTEDIT_GETCHAR local STB_TEXTEDIT_GETWIDTH = ImStb.TEXTEDIT_GETWIDTH local STB_TEXTEDIT_LAYOUTROW = ImStb.TEXTEDIT_LAYOUTROW +-- [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. local IMSTB_TEXTEDIT_GETNEXTCHARINDEX = ImStb.TEXTEDIT_GETNEXTCHARINDEX local IMSTB_TEXTEDIT_GETPREVCHARINDEX = ImStb.TEXTEDIT_GETPREVCHARINDEX local STB_TEXTEDIT_MOVEWORDLEFT = ImStb.TEXTEDIT_MOVEWORDLEFT @@ -58735,34 +65853,35 @@ local STB_TEXTEDIT_MOVELINEEND = ImStb.TEXTEDIT_MOVELINEEND local STB_TEXTEDIT_DELETECHARS = ImStb.TEXTEDIT_DELETECHARS local STB_TEXTEDIT_INSERTCHARS = ImStb.TEXTEDIT_INSERTCHARS -STB_TEXTEDIT_NEWLINE = 10 +STB_TEXTEDIT_NEWLINE = 10 -- the character returned by _GETCHAR() we recognize as manually wordwrapping for end-of-line positioning STB_TEXTEDIT_K_LEFT = 0x200000 -- keyboard input to move cursor left STB_TEXTEDIT_K_RIGHT = 0x200001 -- keyboard input to move cursor right STB_TEXTEDIT_K_UP = 0x200002 -- keyboard input to move cursor up STB_TEXTEDIT_K_DOWN = 0x200003 -- keyboard input to move cursor down -STB_TEXTEDIT_K_LINESTART = 0x200004 -- keyboard input to move cursor to start of line -STB_TEXTEDIT_K_LINEEND = 0x200005 -- keyboard input to move cursor to end of line -STB_TEXTEDIT_K_TEXTSTART = 0x200006 -- keyboard input to move cursor to start of text -STB_TEXTEDIT_K_TEXTEND = 0x200007 -- keyboard input to move cursor to end of text +STB_TEXTEDIT_K_LINESTART = 0x200004 -- keyboard input to move cursor to start of line -- e.g. HOME +STB_TEXTEDIT_K_LINEEND = 0x200005 -- keyboard input to move cursor to end of line -- e.g. END +STB_TEXTEDIT_K_TEXTSTART = 0x200006 -- keyboard input to move cursor to start of text -- e.g. ctrl-HOME +STB_TEXTEDIT_K_TEXTEND = 0x200007 -- keyboard input to move cursor to end of text -- e.g. ctrl-END STB_TEXTEDIT_K_DELETE = 0x200008 -- keyboard input to delete selection or character under cursor STB_TEXTEDIT_K_BACKSPACE = 0x200009 -- keyboard input to delete selection or character left of cursor STB_TEXTEDIT_K_UNDO = 0x20000A -- keyboard input to perform undo STB_TEXTEDIT_K_REDO = 0x20000B -- keyboard input to perform redo -STB_TEXTEDIT_K_WORDLEFT = 0x20000C -- keyboard input to move cursor left one word -STB_TEXTEDIT_K_WORDRIGHT = 0x20000D -- keyboard input to move cursor right one word +STB_TEXTEDIT_K_WORDLEFT = 0x20000C -- keyboard input to move cursor left one word -- e.g. ctrl-LEFT +STB_TEXTEDIT_K_WORDRIGHT = 0x20000D -- keyboard input to move cursor right one word -- e.g. ctrl-RIGHT STB_TEXTEDIT_K_PGUP = 0x20000E -- keyboard input to move cursor up a page STB_TEXTEDIT_K_PGDOWN = 0x20000F -- keyboard input to move cursor down a page -STB_TEXTEDIT_K_SHIFT = 0x400000 +STB_TEXTEDIT_K_SHIFT = 0x400000 -- a power of two that is or'd in to a keyboard input to represent the shift key -IMSTB_TEXTEDIT_UNDOSTATECOUNT = 99 -local IMSTB_TEXTEDIT_UNDOCHARCOUNT = 999 +IMSTB_TEXTEDIT_UNDOSTATECOUNT = 99 -- the number of undo states to allow +local IMSTB_TEXTEDIT_UNDOCHARCOUNT = 999 -- the number of characters to store in the undo buffer local IMSTB_TEXTEDIT_memmove = ImStb.TEXTEDIT_memmove +-- forward declarations local stb_text_undo local stb_text_redo ----------------------------------------------------------------- ----------------------------------------------------------------- +------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- --- STB_TexteditState --- @@ -58785,6 +65904,7 @@ local stb_text_redo --- @nodiscard local function StbUndoRecord() return { + -- private data where = 1, insert_length = 0, delete_length = 0, @@ -58814,6 +65934,7 @@ local function StbUndoState() end return { + -- private data undo_rec = undo_rec, undo_char = undo_char, @@ -58844,16 +65965,34 @@ end --- @nodiscard function STB_TexteditState() return { - cursor = 0, + --------------------- + -- + -- public data + -- - select_start = 0, + cursor = 0, + -- position of the text cursor within the string + + select_start = 0, -- selection start point select_end = 0, + -- selection start and end point in characters; if equal, no selection. + -- note that start may be less than or greater than end (e.g. when + -- dragging the mouse, start is where the initial click was, and you + -- can drag in either direction) insert_mode = false, + -- each textfield keeps its own insert mode state. to keep an app-wide + -- insert mode, copy this value in/out of the app state row_count_per_page = 0, + -- page size in number of row. + -- this value MUST be set to >0 for pageup or pagedown in multilines documents. - cursor_at_end_of_line = false, + --------------------- + -- + -- private data + -- + cursor_at_end_of_line = false, -- not implemented yet initialized = false, has_preferred_x = false, single_line = false, @@ -58861,7 +66000,7 @@ function STB_TexteditState() padding2 = 0, padding3 = 0, - preferred_x = 0.0, + preferred_x = 0.0, -- this determines where the cursor up/down tries to seek to along x undostate = StbUndoState() } @@ -58872,12 +66011,20 @@ local function STB_TEXT_HAS_SELECTION(s) return s.select_start ~= s.select_end end +------------------------------------------------------------------------------- +--- +--- StbTexteditRow +--- +--- Result of layout query, used by stb_textedit to determine where +--- the text in each row is. + +-- result of layout query --- @class StbTexteditRow ---- @field x0 float # starting x location +--- @field x0 float # starting x location, end x location (allows for align=right, etc) --- @field x1 float # end x location --- @field baseline_y_delta float # position of baseline relative to previous row's baseline ---- @field ymin float # height of row above baseline ---- @field ymax float # height of row below baseline +--- @field ymin float # height of row above and below baseline +--- @field ymax float # height of row above and below baseline --- @field num_chars int --- @return StbTexteditRow @@ -58909,10 +66056,15 @@ end ---------------------------------------- ---------------------------------------- --- ---- Implementation +--- Implementation mode --- --- +------------------------------------------------------------------------------- +--- +--- Mouse input handling +--- + local stb_text_locate_coord do -- only create once, reuse later @@ -59064,6 +66216,7 @@ end --- --- +-- forward declarations local stb_text_makeundo_insert local stb_text_makeundo_delete local stb_text_makeundo_replace @@ -59112,8 +66265,8 @@ function stb_textedit_find_charpos(find, str, n, single_line) local z = STB_TEXTEDIT_STRINGLEN(str) local first - -- special case if it's at the end (may not be needed?) if n == z + 1 and single_line then + -- special case if it's at the end (may not be needed?) STB_TEXTEDIT_LAYOUTROW(r, str, 1) find.y = 0 find.first_char = 1 @@ -59133,18 +66286,18 @@ function stb_textedit_find_charpos(find, str, n, single_line) if n < i + r.num_chars - 1 then break end - if str.LastMoveDirectionLR == ImGuiDir.Right and str.Stb.cursor > 1 and str.Stb.cursor == i + r.num_chars and STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) ~= STB_TEXTEDIT_NEWLINE then -- [IMGUI] Wrapping point handling + if str.LastMoveDirectionLR == ImGuiDir.Right and str.Stb.cursor > 1 and str.Stb.cursor == i + r.num_chars and STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) ~= STB_TEXTEDIT_NEWLINE then -- [DEAR IMGUI] Wrapping point handling break end - if (i - 1) + r.num_chars == z and z > 0 and STB_TEXTEDIT_GETCHAR(str, z) ~= STB_TEXTEDIT_NEWLINE then -- [IMGUI] special handling for last line - break + if (i - 1) + r.num_chars == z and z > 0 and STB_TEXTEDIT_GETCHAR(str, z) ~= STB_TEXTEDIT_NEWLINE then -- [DEAR IMGUI] special handling for last line + break -- [DEAR IMGUI] end prev_start = i i = i + r.num_chars find.y = find.y + r.baseline_y_delta - if i == z + 1 then -- [IMGUI] - r.num_chars = 0 - break + if i == z + 1 then -- [DEAR IMGUI] + r.num_chars = 0 -- [DEAR IMGUI] + break -- [DEAR IMGUI] end end @@ -59192,7 +66345,7 @@ local function stb_textedit_delete(str, state, where, len) state.has_preferred_x = false end --- delete the selection +-- delete the section --- @param str IMSTB_TEXTEDIT_STRING --- @param state STB_TexteditState local function stb_textedit_delete_selection(str, state) @@ -59211,7 +66364,7 @@ local function stb_textedit_delete_selection(str, state) end end --- canonicalize the selection so start <= end +-- canoncialize the selection so start <= end --- @param state STB_TexteditState local function stb_textedit_sortselection(state) if state.select_end < state.select_start then @@ -59292,7 +66445,7 @@ local function stb_textedit_paste_internal(str, state, text, len) end -- API key: process text input --- [IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. +-- [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. --- @param str IMSTB_TEXTEDIT_STRING --- @param state STB_TexteditState --- @param text IMSTB_TEXTEDIT_CHARTYPE[] @@ -59445,7 +66598,7 @@ function stb_textedit_key(str, state, key) break end - -- [IMGUI] + -- [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 then -- break @@ -59642,8 +66795,8 @@ end ----------------------------------------------------- --- --- Undo processing ---- OPTIMIZE: the undo/redo buffer should be circular --- +--- @OPTIMIZE: the undo/redo buffer should be circular --- @param state StbUndoState local function stb_textedit_flush_redo(state) @@ -59663,7 +66816,7 @@ local function stb_textedit_discard_undo(state) IMSTB_TEXTEDIT_memmove(state.undo_char, 1, state.undo_char, n + 1, state.undo_char_point - 1) for i = 1, state.undo_point do if state.undo_rec[i].char_storage >= 0 then - state.undo_rec[i].char_storage = state.undo_rec[i].char_storage - n -- OPTIMIZE: get rid of char_storage and infer it + state.undo_rec[i].char_storage = state.undo_rec[i].char_storage - n -- @OPTIMIZE: get rid of char_storage and infer it end end end @@ -59696,7 +66849,7 @@ local function stb_textedit_discard_redo(state) end -- now move all the redo records towards the end of the buffer; the first one is at 'redo_point' - -- [IMGUI] + -- [DEAR IMGUI] local move_size = IMSTB_TEXTEDIT_UNDOSTATECOUNT - state.redo_point - 1 IMSTB_TEXTEDIT_memmove(state.undo_rec, state.redo_point + 1, state.undo_rec, state.redo_point, move_size) @@ -59842,6 +66995,9 @@ function stb_text_redo(str, state) local u = s.undo_rec[s.undo_point] local r = s.undo_rec[s.redo_point] + -- we KNOW there must be room for the undo record, because the redo record + -- was derived from an undo record + u.delete_length = r.insert_length u.insert_length = r.delete_length u.where = r.where @@ -59850,6 +67006,7 @@ function stb_text_redo(str, state) if r.delete_length > 0 then -- the redo record requires us to delete characters, so the undo record -- needs to store the characters + if s.undo_char_point + u.insert_length > s.redo_char_point then u.insert_length = 0 u.delete_length = 0 @@ -59857,6 +67014,7 @@ function stb_text_redo(str, state) u.char_storage = s.undo_char_point s.undo_char_point = s.undo_char_point + u.insert_length + -- now save the characters for i = 0, u.insert_length - 1 do s.undo_char[u.char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i) end @@ -59866,6 +67024,7 @@ function stb_text_redo(str, state) end if r.insert_length ~= 0 then + -- easy case: need to insert n characters r.insert_length = STB_TEXTEDIT_INSERTCHARS(str, r.where, s.undo_char, r.char_storage, r.insert_length) s.redo_char_point = s.redo_char_point + r.insert_length end @@ -59912,6 +67071,7 @@ function stb_text_makeundo_replace(str, state, where, old_length, new_length) end end +-- reset the state to default --- @param state STB_TexteditState --- @param is_single_line bool local function stb_textedit_clear_state(state, is_single_line) @@ -59935,7 +67095,7 @@ return { click = stb_textedit_click, drag = stb_textedit_drag, createundo = stb_text_createundo, - initialize_state = stb_textedit_clear_state, + initialize_state = stb_textedit_clear_state, -- API initialize text = stb_textedit_text, key = stb_textedit_key, @@ -59949,12 +67109,210 @@ return { HAS_SELECTION = STB_TEXT_HAS_SELECTION } + +------------------------------------------------------------------------------- +-- This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------- +-- ALTERNATIVE A - MIT License +-- Copyright (c) 2017 Sean Barrett +-- Permission is hereby granted, free of charge, to any person obtaining a copy of +-- this software and associated documentation files (the "Software"), to deal in +-- the Software without restriction, including without limitation the rights to +-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +-- of the Software, and to permit persons to whom the Software is furnished to do +-- so, subject to the following conditions: +-- The above copyright notice and this permission notice shall be included in all +-- copies or substantial portions of the Software. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +-- SOFTWARE. +------------------------------------------------------------------------------- +-- ALTERNATIVE B - Public Domain (www.unlicense.org) +-- This is free and unencumbered software released into the public domain. +-- Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +-- software, either in source code form or as a compiled binary, for any purpose, +-- commercial or non-commercial, and by any means. +-- In jurisdictions that recognize copyright laws, the author or authors of this +-- software dedicate any and all copyright interest in the software to the public +-- domain. We make this dedication for the benefit of the public at large and to +-- the detriment of our heirs and successors. We intend this dedication to be an +-- overt act of relinquishment in perpetuity of all present and future rights to +-- this software under copyright law. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +-- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------- end __FILES['imstb_truetype.lua'] = function() --- Dear ImGui -- This is a Lua port of original `imstb_truetype.h` +-- [DEAR IMGUI] +-- This is a slightly modified version of stb_truetype.h 1.26. +-- Mostly fixing for compiler and static analyzer warnings. +-- Grep for [DEAR IMGUI] to find the changes. + +-- stb_truetype.h - v1.26 - public domain +-- authored from 2009-2021 by Sean Barrett / RAD Game Tools +-- +-- ======================================================================= +-- +-- NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES +-- +-- This library does no range checking of the offsets found in the file, +-- meaning an attacker can use it to read arbitrary memory. +-- +-- ======================================================================= +-- +-- This library processes TrueType files: +-- parse files +-- extract glyph metrics +-- extract glyph shapes +-- render glyphs to one-channel bitmaps with antialiasing (box filter) +-- +-- Todo: +-- non-MS cmaps +-- crashproof on bad data +-- hinting? (no longer patented) +-- cleartype-style AA? +-- optimize: build edge-list directly from curves +-- optimize: rasterize directly from curves? +-- +-- ADDITIONAL CONTRIBUTORS +-- +-- Mikko Mononen: compound shape support, more cmap formats +-- Tor Andersson: kerning, subpixel rendering +-- Dougall Johnson: OpenType / Type 2 font handling +-- Daniel Ribeiro Maciel: basic GPOS-based kerning +-- +-- Misc other: +-- Ryan Gordon +-- Simon Glass +-- github:IntellectualKitty +-- Imanol Celaya +-- Daniel Ribeiro Maciel +-- +-- Bug/warning reports/fixes: +-- "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe +-- Cass Everitt Martins Mozeiko github:aloucks +-- stoiko (Haemimont Games) Cap Petschulat github:oyvindjam +-- Brian Hook Omar Cornut github:vassvik +-- Walter van Niftrik Ryan Griege +-- David Gow Peter LaValle +-- David Given Sergey Popov +-- Ivan-Assen Ivanov Giumo X. Clanjor +-- Anthony Pesch Higor Euripedes +-- Johan Duparc Thomas Fields +-- Hou Qiming Derek Vinyard +-- Rob Loach Cort Stratton +-- Kenney Phillis Jr. Brian Costabile +-- Ken Voskuil (kaesve) +-- +-- USAGE +-- +-- "Load" a font file from a memory buffer (you have to keep the buffer loaded) +-- stbtt_InitFont() +-- stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +-- +-- Character advance/positioning +-- stbtt_GetFontVMetrics() +-- +-- Starting with version 1.06, the rasterizer was replaced with a new, +-- faster and generally-more-precise rasterizer. The new rasterizer more +-- accurately measures pixel coverage for anti-aliasing, except in the case +-- where multiple shapes overlap, in which case it overestimates the AA pixel +-- coverage. Thus, anti-aliasing of intersecting shapes may look wrong. +-- (This port only implements the new rasterizer.) +-- +-- ADDITIONAL DOCUMENTATION +-- +-- Some important concepts to understand to use this library: +-- +-- Codepoint +-- Characters are defined by unicode codepoints, e.g. 65 is +-- uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is +-- the hiragana for "ma". +-- +-- Glyph +-- A visual character shape (every codepoint is rendered as +-- some glyph) +-- +-- Glyph index +-- A font-specific integer ID representing a glyph +-- +-- Baseline +-- Glyph shapes are defined relative to a baseline, which is the +-- bottom of uppercase characters. Characters extend both above +-- and below the baseline. +-- +-- Current Point +-- As you draw text to the screen, you keep track of a "current point" +-- which is the origin of each character. The current point's vertical +-- position is the baseline. Even "baked fonts" use this model. +-- +-- Vertical Font Metrics +-- The vertical qualities of the font, used to vertically position +-- and space the characters. See docs for stbtt_GetFontVMetrics. +-- +-- Font Size in Pixels or Points +-- The preferred interface for specifying font sizes in stb_truetype +-- is to specify how tall the font's vertical extent should be in pixels. +-- +-- DETAILED USAGE: +-- +-- Scale: +-- Select how high you want the font to be, in pixels. +-- Call ScaleForPixelHeight to compute a scale factor SF that will be +-- used by all other functions. +-- +-- Current point: +-- Set the current point where the first character will appear. The +-- first character could extend left of the current point; this is font +-- dependent. You can either choose a current point that is the leftmost +-- point and hope, or add some padding, or check the bounding box or +-- left-side-bearing of the first character to be displayed and set +-- the current point based on that. +-- +-- Displaying a character: +-- Compute the bounding box of the character. It will contain signed values +-- relative to . I.e. if it returns x0,y0,x1,y1, +-- then the character should be displayed in the rectangle from +-- to = n then @@ -60552,23 +67919,25 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.fontstart = fontstart info.cff = stbtt__new_buf(nil, 0) - cmap = stbtt__find_table(data, fontstart, "cmap") - info.loca = stbtt__find_table(data, fontstart, "loca") - info.head = stbtt__find_table(data, fontstart, "head") - info.glyf = stbtt__find_table(data, fontstart, "glyf") - info.hhea = stbtt__find_table(data, fontstart, "hhea") - info.hmtx = stbtt__find_table(data, fontstart, "hmtx") - info.kern = stbtt__find_table(data, fontstart, "kern") - info.gpos = stbtt__find_table(data, fontstart, "GPOS") + cmap = stbtt__find_table(data, fontstart, "cmap") -- required + info.loca = stbtt__find_table(data, fontstart, "loca") -- required + info.head = stbtt__find_table(data, fontstart, "head") -- required + info.glyf = stbtt__find_table(data, fontstart, "glyf") -- required + info.hhea = stbtt__find_table(data, fontstart, "hhea") -- required + info.hmtx = stbtt__find_table(data, fontstart, "hmtx") -- required + info.kern = stbtt__find_table(data, fontstart, "kern") -- not required + info.gpos = stbtt__find_table(data, fontstart, "GPOS") -- not required if (cmap == 0 or info.head == 0 or info.hhea == 0 or info.hmtx == 0) then return false end if info.glyf ~= 0 then + -- required for truetype if info.loca == 0 then return false end else + -- initialization for CFF / Type2 fonts (OTF) local cff = stbtt__find_table(data, fontstart, "CFF ") if cff == 0 then return false @@ -60577,14 +67946,16 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.fontdicts = stbtt__new_buf(nil, 0) info.fdselect = stbtt__new_buf(nil, 0) - info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- TODO: this should use size from table + -- @TODO this should use size from table (not 512MB) + info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- PORT: 64MB here instead of 512MB local b = info.cff -- read the header stbtt__buf_skip(b, 2) - stbtt__buf_seek(b, stbtt__buf_get8(b)) + stbtt__buf_seek(b, stbtt__buf_get8(b)) -- hdrsize - -- TODO: the name INDEX could list multiple fonts, but we just use the first one. + -- @TODO the name INDEX could list multiple fonts, + -- but we just use the first one. stbtt__cff_get_index(b) -- name INDEX local topdictidx = stbtt__cff_get_index(b) local topdict = stbtt__cff_index_get(topdictidx, 0) @@ -60597,6 +67968,7 @@ local function stbtt_InitFont_internal(info, data, fontstart) local fdselectoff = stbtt__dict_get_ints(topdict, bit32.bor(0x100, 37), 1) info.subrs = stbtt__get_subrs(b, topdict) + -- we only support Type 2 charstrings if cstype[1] ~= 2 then return false end @@ -60605,6 +67977,7 @@ local function stbtt_InitFont_internal(info, data, fontstart) end if fdarrayoff[1] ~= 0 then + -- looks like a CID font if fdselectoff[1] == 0 then return false end @@ -60627,19 +68000,26 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.svg = -1 + -- find a cmap encoding table we understand *now* to avoid searching + -- later. (todo: could make this installable) + -- the same regardless of glyph. numTables = ttUSHORT(data, cmap + 2) info.index_map = 0 for i = 0, numTables - 1 do local encoding_record = cmap + 4 + 8 * i + -- find an encoding we understand: local platform_id = ttUSHORT(data, encoding_record) if platform_id == STBTT_PLATFORM_ID.MICROSOFT then local ms_eid = ttUSHORT(data, encoding_record + 2) if ms_eid == STBTT_MS_EID.UNICODE_BMP or ms_eid == STBTT_MS_EID.UNICODE_FULL then + -- MS/Unicode info.index_map = cmap + ttULONG(data, encoding_record + 4) end elseif platform_id == STBTT_PLATFORM_ID.UNICODE then + -- Mac/iOS has these + -- all the encodingIDs are unicode, so we don't bother to check it info.index_map = cmap + ttULONG(data, encoding_record + 4) end end @@ -60651,6 +68031,11 @@ local function stbtt_InitFont_internal(info, data, fontstart) return true end +-- If you're going to perform multiple operations on the same character +-- and you want a speed-up, call this function with the character you're +-- going to process, then use glyph-based functions instead of the +-- codepoint-based functions. +-- Returns 0 if the character codepoint is not defined in the font. --- @param info stbtt_fontinfo --- @param unicode_codepoint int function stbtt_FindGlyphIndex(info, unicode_codepoint) @@ -60658,7 +68043,7 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) local index_map = info.index_map local format = ttUSHORT(data, index_map + 0) - if format == 0 then + if format == 0 then -- apple byte encoding local bytes = ttUSHORT(data, index_map + 2) if unicode_codepoint < bytes - 6 then return ttBYTE(data, index_map + 6 + unicode_codepoint) @@ -60672,14 +68057,15 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) end return 0 elseif format == 2 then - STBTT_assert(false) -- TODO: high-byte mapping for japanese/chinese/korean + STBTT_assert(false) -- @TODO: high-byte mapping for japanese/chinese/korean return 0 - elseif format == 4 then + elseif format == 4 then -- standard mapping for windows fonts: binary search collection of ranges local segcount = bit32.rshift(ttUSHORT(data, index_map + 6), 1) local searchRange = bit32.rshift(ttUSHORT(data, index_map + 8), 1) local entrySelector = ttUSHORT(data, index_map + 10) local rangeShift = bit32.rshift(ttUSHORT(data, index_map + 12), 1) + -- do a binary search of the segments local endCount = index_map + 14 local search = endCount @@ -60687,10 +68073,13 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) return 0 end + -- they lie from endCount .. endCount + segCount + -- but searchRange is the nearest power of two, so... if unicode_codepoint >= ttUSHORT(data, search + rangeShift * 2) then search = search + rangeShift * 2 end + -- now decrement to bias correctly to find smallest search = search - 2 while entrySelector ~= 0 do searchRange = bit32.rshift(searchRange, 1) @@ -60722,8 +68111,9 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) local ngroups = ttULONG(data, index_map + 12) local low = 0 local high = ngroups + -- Binary search the right group. while low < high do - local mid = low + bit32.rshift(high - low, 1) + local mid = low + bit32.rshift(high - low, 1) -- rounds down, so low <= mid < high local start_char = ttULONG(data, index_map + 16 + mid * 12) local end_char = ttULONG(data, index_map + 16 + mid * 12 + 4) if unicode_codepoint < start_char then @@ -60739,10 +68129,10 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) end end end - return 0 + return 0 -- not found end - -- TODO: + -- @TODO STBTT_assert(false) return 0 end @@ -60764,8 +68154,8 @@ end local function stbtt__GetGlyfOffset(info, glyph_index) STBTT_assert(info.cff.size == 0) - if glyph_index >= info.numGlyphs then return -1 end - if info.indexToLocFormat >= 2 then return -1 end + if glyph_index >= info.numGlyphs then return -1 end -- glyph index out of range + if info.indexToLocFormat >= 2 then return -1 end -- unknown index->glyph map format local g1, g2 if info.indexToLocFormat == 0 then @@ -60776,9 +68166,10 @@ local function stbtt__GetGlyfOffset(info, glyph_index) g2 = info.glyf + ttULONG(info.data, info.loca + glyph_index * 4 + 4) end - if g1 == g2 then return -1 else return g1 end + if g1 == g2 then return -1 else return g1 end -- if length is 0, return -1 end +-- Gets the bounding box of the visible part of the glyph, in unscaled coordinates --- @return integer, integer?, integer?, integer?, integer? local function stbtt_GetGlyphBox(info, glyph_index) local n, x0, y0, x1, y1 @@ -60850,7 +68241,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- 1-based idx local n = 1 + ttUSHORT(data, endPtsOfContours + numberOfContours * 2 - 2) - local m = n + 2 * numberOfContours + local m = n + 2 * numberOfContours -- a loose bound on how many vertices we might need vertices = {} for i = 1, m do vertices[i] = stbtt_vertex() end @@ -60861,7 +68252,11 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) local next_move = 0 local flagcount = 0 - local off = m - n + -- in first pass, we load uninterpreted data into the allocated array + -- above, shifted to the end of the array so we won't overwrite it when + -- we create our final data starting from the front + + local off = m - n -- starting offset for uninterpreted data, regardless of how m ends up being calculated -- first load flags local flags = 0 @@ -60888,7 +68283,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) if bit32.band(flags, 2) ~= 0 then local dx = data[points] points = points + 1 - if bit32.band(flags, 16) ~= 0 then + if bit32.band(flags, 16) ~= 0 then -- ??? x = x + dx else x = x - dx @@ -60910,7 +68305,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) if bit32.band(flags, 4) ~= 0 then local dy = data[points] points = points + 1 - if bit32.band(flags, 32) ~= 0 then + if bit32.band(flags, 32) ~= 0 then -- ??? y = y + dy else y = y - dy @@ -60941,15 +68336,19 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) -- now start the new one start_off = (bit32.band(flags, 1) == 0) if start_off then + -- if we start off with an off-curve point, then when we need to find a point on the curve + -- where we can start, and we need to save some state for when we wraparound. scx = x scy = y if bit32.band(vertices[off + i + 1].type, 1) == 0 then + -- next point is also a curve point, so interpolate an on-point curve sx = bit32.rshift(x + stbtt_int32(vertices[off + i + 1].x), 1) sy = bit32.rshift(y + stbtt_int32(vertices[off + i + 1].y), 1) else + -- otherwise just use the next point as our start point sx = stbtt_int32(vertices[off + i + 1].x) sy = stbtt_int32(vertices[off + i + 1].y) - i = i + 1 + i = i + 1 -- we're using point i+1 as the starting point, so skip it end else sx = x @@ -60961,8 +68360,8 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) next_move = 1 + ttUSHORT(data, endPtsOfContours + j * 2) j = j + 1 else - if bit32.band(flags, 1) == 0 then - if was_off then + if bit32.band(flags, 1) == 0 then -- if it's a curve + if was_off then -- two off-curve control points in a row means interpolate an on-curve midpoint stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.CURVE, bit32.rshift(cx + x, 1), bit32.rshift(cy + y, 1), cx, cy) num_vertices = num_vertices + 1 end @@ -60986,6 +68385,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy) elseif numberOfContours < 0 then + -- Compound shapes. local more = 1 local comp = g + 10 num_vertices = 0 @@ -61001,8 +68401,8 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) flags = ttSHORT(data, comp) comp = comp + 2 gidx = ttSHORT(data, comp) comp = comp + 2 - if bit32.band(flags, 2) ~= 0 then - if bit32.band(flags, 1) ~= 0 then + if bit32.band(flags, 2) ~= 0 then -- XY values + if bit32.band(flags, 1) ~= 0 then -- shorts mtx[5] = ttSHORT(data, comp) comp = comp + 2 mtx[6] = ttSHORT(data, comp) comp = comp + 2 else @@ -61010,7 +68410,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) mtx[6] = ttCHAR(data, comp) comp = comp + 1 end else - -- TODO: handle matching point + -- @TODO handle matching point STBTT_assert(false) end @@ -61037,11 +68437,14 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) mtx[4] = ttSHORT(data, comp) / 16384.0 comp = comp + 2 end + -- Find transformation scales. m = STBTT_sqrt(mtx[1] * mtx[1] + mtx[2] * mtx[2]) n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4]) + -- Get indexed glyph. comp_num_vertices, comp_verts = stbtt_GetGlyphShape(info, gidx) if comp_num_vertices > 0 then + -- Transform vertices. for i = 1, comp_num_vertices do local v = comp_verts[i] local x = v.x @@ -61054,6 +68457,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) v.cy = stbtt_int16(n * (mtx[2] * x + mtx[4] * y + mtx[6])) end + -- Append vertices. if num_vertices == 0 then -- LUA: No malloc vertices = comp_verts else @@ -61065,6 +68469,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) num_vertices = num_vertices + comp_num_vertices end + -- More components ? more = bit32.band(flags, bit32.lshift(1, 5)) end end @@ -61220,7 +68625,7 @@ local function stbtt__run_charstring(info, glyph_index, c) clear_stack = 1 b0 = stbtt__buf_get8(b) - -- TODO: implement hinting + -- @TODO implement hinting if b0 == 0x13 or b0 == 0x14 then -- hintmask or cntrmask if in_header then maskbits = maskbits + trunc(sp / 2) -- implicit "vstem" @@ -61369,6 +68774,8 @@ local function stbtt__run_charstring(info, glyph_index, c) elseif b0 == 0x0C then -- two-byte escape local b1 = stbtt__buf_get8(b) + -- @TODO These "flex" implementations ignore the flex-depth and resolution, + -- and always draw beziers. if b1 == 0x22 then -- hflex if sp < 7 then return STBTT__CSERR("hflex stack") end local dx1 = s[0] @@ -61501,6 +68908,15 @@ function stbtt__GetGlyphInfoT2(info, glyph_index) return ((r ~= 0) and c.num_vertices or 0), x0, y0, x1, y1 end +-- returns # of vertices and fills *vertices with the pointer to them +-- these are expressed in "unscaled" coordinates +-- +-- The shape is a series of contours. Each one starts with +-- a STBTT_moveto, then consists of a series of mixed +-- STBTT_lineto and STBTT_curveto segments. A lineto +-- draws a line from previous endpoint to its x,y; a curveto +-- draws a quadratic bezier from previous endpoint to +-- its x,y, using cx,cy as the bezier control point. --- @param info stbtt_fontinfo --- @param glyph_index int function stbtt_GetGlyphShape(info, glyph_index) @@ -61511,6 +68927,9 @@ function stbtt_GetGlyphShape(info, glyph_index) end end +-- leftSideBearing is the offset from the current horizontal position to the left edge of the character +-- advanceWidth is the offset from the current horizontal position to the next horizontal position +-- these are expressed in unscaled coordinates --- @param info stbtt_fontinfo --- @param glyph_index int function stbtt_GetGlyphHMetrics(info, glyph_index) @@ -61528,6 +68947,12 @@ function stbtt_GetGlyphHMetrics(info, glyph_index) return advanceWidth, leftSideBearing end +-- ascent is the coordinate above the baseline the font extends; descent +-- is the coordinate below the baseline the font extends (i.e. it is typically negative) +-- lineGap is the spacing between one row's descent and the next row's ascent... +-- so you should advance the vertical position by "ascent - descent + lineGap" +-- these are expressed in unscaled coordinates, so you must multiply by +-- the scale factor for a given size --- @param info stbtt_fontinfo function stbtt_GetFontVMetrics(info) local ascent = ttSHORT(info.data, info.hhea + 4) @@ -61537,6 +68962,12 @@ function stbtt_GetFontVMetrics(info) return ascent, descent, lineGap end +-- computes a scale factor to produce a font whose "height" is 'pixels' tall. +-- Height is measured as the distance from the highest ascender to the lowest +-- descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics +-- and computing: +-- scale = pixels / (ascent - descent) +-- so if you prefer to measure height by the ascent only, use a similar calculation. --- @param info stbtt_fontinfo --- @param height float function stbtt_ScaleForPixelHeight(info, height) @@ -61547,10 +68978,12 @@ end ------------------------------------ ------------------------------------ --- ---- Antialiasing software rasterizer +--- antialiasing software rasterizer --- --- +-- same as stbtt_GetGlyphBitmapBox, but you can specify a subpixel +-- shift for the character --- @param font stbtt_fontinfo --- @param glyph int --- @param scale_x float @@ -61578,6 +69011,11 @@ function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, return ix0, iy0, ix1, iy1 end +-- get the bbox of the bitmap centered around the glyph origin; so the +-- bitmap width is ix1-ix0, height is iy1-iy0, and location to place +-- the bitmap top left is (leftSideBearing*scale,iy0). +-- (Note that the bitmap uses y-increases-down, but the shape uses +-- y-increases-up, so GlyphBitmapBox and GlyphBox are inverted.) --- @param font stbtt_fontinfo --- @param glyph int --- @param scale_x float @@ -61600,6 +69038,8 @@ end --- stbtt_MakeGlyphBitmap --- stbtt_GetGlyphBitmapSubpixel +-- the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +-- (i.e. it has already been clipped to those) --- @param scanline float[] --- @param x int --- @param e stbtt__active_edge @@ -61641,7 +69081,7 @@ local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1) -- do nothing else STBTT_assert(x0 >= x and x0 <= x + 1 and x1 >= x and x1 <= x + 1) - scanline[x] = scanline[x] + e.direction * (y1 - y0) * (1 - ((x0 - x) + (x1 - x)) / 2) + scanline[x] = scanline[x] + e.direction * (y1 - y0) * (1 - ((x0 - x) + (x1 - x)) / 2) -- coverage = 1 - average x position end end @@ -61679,6 +69119,7 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t while e do -- brute force every pixel + -- compute intersection points with top & bottom STBTT_assert(e.ey >= y_top) @@ -61722,8 +69163,8 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t if x_top >= 0 and x_bottom >= 0 and x_top < len and x_bottom < len then -- from here on, we don't have to range check x values if trunc(x_top) == trunc(x_bottom) then - -- simple case, only spans one pixel local height + -- simple case, only spans one pixel local x = trunc(x_top) height = (sy1 - sy0) * e.direction STBTT_assert(x >= 0 and x < len) @@ -61755,8 +69196,25 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t -- compute intersection with y axis at x2 y_final = y_top + dy * (x2 - x0) + -- x1 x_top x2 x_bottom + -- y_top +------|-----+------------+------------+--------|---+------------+ + -- | | | | | | + -- | | | | | | + -- sy0 | Txxxxx|............|............|............|............| + -- y_crossing | *xxxxx.......|............|............|............| + -- | | xxxxx..|............|............|............| + -- | | /- xx*xxxx........|............|............| + -- | | dy < | xxxxxx..|............|............| + -- y_final | | \- | xx*xxx.........|............| + -- sy1 | | | | xxxxxB...|............| + -- | | | | | | + -- | | | | | | + -- y_bottom +------------+------------+------------+------------+------------+ + -- + -- goal is to measure the area covered by '.' in each pixel + -- if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 - -- TODO: maybe test against sy1 rather than y_bottom? + -- @TODO: maybe test against sy1 rather than y_bottom? if y_crossing > y_bottom then y_crossing = y_bottom end @@ -61778,6 +69236,16 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t end end + -- in second pixel, area covered by line segment found in first pixel + -- is always a rectangle 1 wide * the height of that line segment; this + -- is exactly what the variable 'area' stores. it also gets a contribution + -- from the line segment within it. the THIRD pixel will get the first + -- pixel's rectangle contribution, the second pixel's rectangle contribution, + -- and its own contribution. the 'own contribution' is the same in every pixel except + -- the leftmost and rightmost, a trapezoid that slides down in each pixel. + -- the second pixel's contribution to the third pixel will be the + -- rectangle 1 wide times the height change in the second pixel, which is dy. + step = sign * dy * 1 -- dy is dy/dx, change in y for every 1 change in x, -- which multiplied by 1-pixel-width is how much pixel area changes for each step in x -- so the area advances by 'step' every time @@ -61797,7 +69265,27 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t scanline_fill[x2 + 1] = scanline_fill[x2 + 1] + sign * (sy1 - sy0) end else + -- if edge goes outside of box we're drawing, we require + -- clipping logic. since this does not match the intended use + -- of this library, we use a different, very slow brute + -- force implementation + -- note though that this does happen some of the time because + -- x_top and x_bottom can be extrapolated at the top & bottom of + -- the shape and actually lie outside the bounding box for x = 0, len - 1 do + -- cases: + -- + -- there can be up to two intersections with the pixel. any intersection + -- with left or right edges can be handled by splitting into two (or three) + -- regions. intersections with top & bottom do not necessitate case-wise logic. + -- + -- the old way of doing this found the intersections with the left & right edges, + -- then used some simple logic to produce up to three segments in sorted order + -- from top-to-bottom. however, this had a problem: if an x edge was epsilon + -- across the x border, then the corresponding y position might not be distinct + -- from the other y segment, and it might ignored as an empty segment. to avoid + -- that, we need to explicitly produce segments based on x positions. + -- rename variables to clearly-defined pairs local y0 = y_top local x1 = x @@ -61841,6 +69329,7 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t end end +-- directly AA rasterize edges w/o supersampling --- @param result stbtt__bitmap --- @param e stbtt__edge --- @param n int @@ -61868,28 +69357,33 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of for i = 0, result.w - 1 do scanline[i] = 0 end for i = 0, result.w do scanline2[i] = 0 end + -- update all active edges; + -- remove all active edges that terminate before the top of this scanline local prev = nil local curr = active while curr do local next = curr.next if curr.ey <= scan_y_top then - if prev then prev.next = next + if prev then prev.next = next -- delete from list else active = next end curr.direction = 0 else - prev = curr + prev = curr -- advance through list end curr = next end + -- insert all edges that start before the bottom of this scanline local edge = e[p] while edge.y0 <= scan_y_bottom do if edge.y0 ~= edge.y1 then local z = stbtt__new_active(edge, off_x, scan_y_top) if j == 0 and off_y ~= 0 and z.ey < scan_y_top then + -- this can happen due to subpixel positioning and some kind of fp rounding error i think z.ey = scan_y_top end - STBTT_assert(z.ey >= scan_y_top) + STBTT_assert(z.ey >= scan_y_top) -- if we get really unlucky a tiny bit of an edge can be out of bounds + -- insert at front z.next = active active = z end @@ -61897,6 +69391,7 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of edge = e[p] end + -- now process all active edges if active then stbtt__fill_active_edges_new(scanline, scanline2, result.w, active, scan_y_top) end @@ -61915,10 +69410,11 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of end end + -- advance all the edges step = active while step do - step.fx = step.fx + step.fdx - step = step.next + step.fx = step.fx + step.fdx -- advance to position for current scanline + step = step.next -- advance through list end y = y + 1 @@ -61953,6 +69449,7 @@ end local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, shift_x, shift_y, off_x, off_y, invert) local y_scale_inv = (invert) and -scale_y or scale_y local vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2 + -- vsubsample should divide 255 evenly; otherwise we won't reach full opacity -- now we have to blow out the windings into explicit edge lists local n = 0 @@ -62020,8 +69517,7 @@ local function stbtt__add_point(points, n, x, y) points[n + 1].y = y end --- tessellate until threshold p is happy... --- TODO: warped to compensate for non-linear stretching +-- tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching --- @param points? stbtt__point[] --- @param num_points int --- @param x0 float @@ -62070,7 +69566,7 @@ end --- @param n int --- @return int num_points # updated num_points passed in local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2, x3, y3, objspace_flatness_squared, n) - -- TODO: this "flatness" calculation is just made-up nonsense that seems to work well enough + -- @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough local dx0 = x1 - x0 local dy0 = y1 - y0 local dx1 = x2 - x1 @@ -62113,6 +69609,7 @@ local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2 return num_points end +-- returns number of contours --- @param vertices stbtt_vertex[] --- @param num_verts int --- @param objspace_flatness float @@ -62189,6 +69686,7 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) return points, num_contours, contour_lengths end +-- rasterize a shape with quadratic beziers into a bitmap --- @param result stbtt__bitmap --- @param flatness_in_pixels float --- @param vertices stbtt_vertex[] @@ -62212,6 +69710,11 @@ local function stbtt_Rasterize(result, flatness_in_pixels, vertices, num_verts, end end +-- renders the glyph into storage you pass in for the bitmap, +-- in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap +-- is clipped to out_w/out_h bytes. Call stbtt_GetGlyphBitmapBox to get the +-- width and height and positioning info for it first. You can also specify +-- a subpixel shift for the character. --- @param info stbtt_fontinfo --- @param output unsigned_char[] --- @param out_w int @@ -62240,7 +69743,7 @@ end ----------------- ----------------- --- ---- Bitmap baking +--- bitmap baking --- --- @@ -62252,7 +69755,7 @@ end --------------------------- --------------------------- --- ---- Bitmap baking / packing +--- bitmap baking / packing --- --- @@ -62334,9 +69837,16 @@ local function stbtt__oversample_shift(oversample) if oversample == 0 then return 0.0 end + + -- The prefilter is a box filter of width "oversample", + -- which shifts phase by (oversample - 1)/2 pixels in + -- oversampled space. We want to shift in the opposite + -- direction to counter this. return -(oversample - 1) / (2.0 * oversample) end +-- same as stbtt_MakeGlyphBitmapSubpixel, but prefiltering +-- is performed. Returns (sub_x, sub_y). --- @param info stbtt_fontinfo --- @param output unsigned_char[] --- @param out_w int @@ -62369,7 +69879,7 @@ end ------------------- ------------------- --- ---- SDF computation +--- sdf computation --- --- @@ -62395,10 +69905,20 @@ end --- stbtt__matchpair --- stbtt__matches +-- Each .ttf/.ttc file may have more than one font. Each font has a sequential +-- index number starting from 0. Call this function to get the font offset for +-- a given index; it returns -1 if the index is out of range. A regular .ttf +-- file will only define one font and it always be at offset 0, so it will +-- return '0' for index 0, and -1 for all other indices. --- @param data table --- @param index int function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end +-- Given an offset into the file that defines a font, this function builds +-- the necessary cached info for the rest of the system. You must allocate +-- the stbtt_fontinfo yourself (see stbtt_fontinfo()), and stbtt_InitFont will fill it out. You don't +-- need to do anything special to free it, because the contents are pure +-- value data with no additional data structures. Returns false on failure. --- @param info stbtt_fontinfo --- @param data table --- @param offset int diff --git a/build/imgui_love.linemap.json b/build/imgui_love.linemap.json index 968f0ac..71ee378 100644 --- a/build/imgui_love.linemap.json +++ b/build/imgui_love.linemap.json @@ -1 +1 @@ -[[149, "imgui.lua"], [18647, "imgui_demo.lua"], [25932, "imgui_draw.lua"], [31170, "imgui_h.lua"], [33368, "imgui_impl_love.lua"], [33908, "imgui_internal.lua"], [37084, "imgui_tables.lua"], [41431, "imgui_widgets.lua"], [51186, "imstb_rectpack.lua"], [51632, "imstb_textedit.lua"], [52873, "imstb_truetype.lua"], [55341, "imstd_minstdio.lua"]] \ No newline at end of file +[[149, "imgui.lua"], [21425, "imgui_demo.lua"], [29843, "imgui_draw.lua"], [35613, "imgui_h.lua"], [38279, "imgui_impl_love.lua"], [38819, "imgui_internal.lua"], [42265, "imgui_tables.lua"], [47260, "imgui_widgets.lua"], [57871, "imstb_rectpack.lua"], [58535, "imstb_textedit.lua"], [60077, "imstb_truetype.lua"], [62865, "imstd_minstdio.lua"]] \ No newline at end of file diff --git a/build/imgui_love.lua b/build/imgui_love.lua index a9566a6..262595a 100644 --- a/build/imgui_love.lua +++ b/build/imgui_love.lua @@ -146,6 +146,422 @@ function IM_INCLUDE(name) end __FILES['imgui.lua'] = function() +-- dear imgui, v1.93 WIP (Luau port) +-- (main code and documentation) + +-- This file is a Lua/Luau port of Dear ImGui's imgui.cpp (docking branch, 1.93 WIP), following imgui.cpp function by function. +-- It runs on Roblox (Luau, primary target) and LÖVE (LuaJIT). Upstream documentation, examples and the demo apply almost directly. + +-- Help: +-- - Call and read ImGui.ShowDemoWindow() in imgui_demo.lua. All applications in examples/ are doing that. +-- - Read top of imgui.lua for more details, links and comments. +-- - ImVec2 and ImVec4 have arithmetic metamethods (a + b, a * 2.0, etc.); fields are .x, .y (.z, .w). +-- - See README.md "Differences from C++ Dear ImGui" for the Luau conventions (out-params become return values, flags enums, text buffers). + +-- Resources: +-- - FAQ ........................ https://dearimgui.com/faq (in upstream repository as docs/FAQ.md) +-- - Homepage ................... https://github.com/ocornut/imgui +-- - Releases & Changelog ....... https://github.com/ocornut/imgui/releases +-- - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!) +-- - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) +-- - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) +-- - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) +-- - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings + backends for various tech/engines) +-- - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools +-- - Glossary https://github.com/ocornut/imgui/wiki/Glossary +-- - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui +-- - Issues & support ........... https://github.com/ocornut/imgui/issues (upstream; for issues specific to this port, use this port's repository) +-- - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) +-- - Web version of the Demo .... https://pthom.github.io/imgui_explorer (w/ source code browser) + +-- Copyright (c) 2014-2026 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. +-- Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts. +-- PLEASE reach out at omar AT discohello DOT com. See https://github.com/ocornut/imgui/wiki/Funding +-- Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine. +-- This port is unofficial and not affiliated with the Dear ImGui project; it is distributed under the same license. + +-- It is recommended that you don't modify imgui.lua! It will become difficult for you to update the library. +-- Note that 'ImGui' being a plain table, you can add functions into it from your own source files, without +-- modifying imgui.lua. You may use the internal functions and data structures (imgui_internal.lua), but they don't +-- come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you +-- to a better solution or official support for them. + +-- +-- Index of this file: +-- +-- DOCUMENTATION +-- +-- - MISSION STATEMENT +-- - CONTROLS GUIDE +-- - PROGRAMMER GUIDE +-- - READ FIRST +-- - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI +-- - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE +-- - HOW A SIMPLE APPLICATION 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) +-- +-- CODE +-- (search for "[SECTION]" in the code to find them) +-- +-- [SECTION] INCLUDES +-- [SECTION] FORWARD DECLARATIONS +-- [SECTION] CONTEXT AND MEMORY ALLOCATORS +-- [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO) +-- [SECTION] MISC HELPERS/UTILITIES (Geometry functions) +-- [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) +-- [SECTION] MISC HELPERS/UTILITIES (File functions) +-- [SECTION] MISC HELPERS/UTILITIES (ImText* functions) +-- [SECTION] MISC HELPERS/UTILITIES (Color functions) +-- [SECTION] ImGuiStorage +-- [SECTION] ImGuiTextFilter +-- [SECTION] ImGuiTextBuffer, ImGuiTextIndex +-- [SECTION] ImGuiListClipper +-- [SECTION] STYLING +-- [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 +-- [SECTION] ITEM SUBMISSION +-- [SECTION] LAYOUT +-- [SECTION] SCROLLING +-- [SECTION] TOOLTIPS +-- [SECTION] POPUPS +-- [SECTION] WINDOW FOCUS +-- [SECTION] KEYBOARD/GAMEPAD NAVIGATION +-- [SECTION] DRAG AND DROP +-- [SECTION] LOGGING/CAPTURING +-- [SECTION] SETTINGS +-- [SECTION] LOCALIZATION +-- [SECTION] VIEWPORTS, PLATFORM WINDOWS +-- [SECTION] DOCKING +-- [SECTION] PLATFORM DEPENDENT HELPERS +-- [SECTION] METRICS/DEBUGGER WINDOW +-- [SECTION] DEBUG LOG WINDOW +-- [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL) +-- +-- (In this port, the sections keep upstream's names but may appear in a different order: +-- e.g. DRAG AND DROP and DOCKING are near the top of imgui.lua. Some are partial or empty, see docs/TODO.txt.) +-- + +------------------------------------------------------------------------------- +-- DOCUMENTATION +------------------------------------------------------------------------------- + +-- +-- MISSION STATEMENT +-- ================= +-- +-- - Easy to use to create code-driven and data-driven tools. +-- - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools. +-- - Easy to hack and improve. +-- - Minimize setup and maintenance. +-- - Minimize state storage on user side. +-- - Minimize state synchronization. +-- - Portable, minimize dependencies, run on target (consoles, phones, etc.). +-- - Efficient runtime and memory consumption. +-- +-- Designed primarily for developers and content-creators, not the typical end-user! +-- Some of the current weaknesses (which we aim to address in the future) includes: +-- +-- - Doesn't look fancy by default. +-- - Limited layout features, intricate layouts are typically crafted in code. +-- +-- +-- CONTROLS GUIDE +-- ============== +-- +-- - MOUSE CONTROLS +-- - Mouse wheel: Scroll vertically. +-- - Shift+Mouse wheel: Scroll horizontally. +-- - Click [X]: Close a window, available when an 'open' value is passed to ImGui.Begin() (open = ImGui.Begin(name, open)). +-- - Click ^, Double-Click title: Collapse window. +-- - Drag on corner/border: Resize window (double-click to auto fit window to its contents). +-- - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true). +-- - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack). +-- +-- - TEXT EDITOR +-- - Hold Shift or Drag Mouse: Select text. +-- - Ctrl+Left/Right: Word jump. +-- - Ctrl+Shift+Left/Right: Select words. +-- - Ctrl+A or Double-Click: Select All. +-- - Ctrl+X, Ctrl+C, Ctrl+V: Use OS clipboard (on Roblox, requires ImGui_ImplRoblox.SetTextProxy(true)). +-- - Ctrl+Z Undo. +-- - Ctrl+Y or Ctrl+Shift+Z: Redo. +-- - ESCAPE: Revert text to its original value. +-- - On macOS, controls are automatically adjusted to match standard macOS text editing and behaviors. +-- (for 99% of shortcuts, Ctrl is replaced by Cmd on macOS). +-- +-- - KEYBOARD CONTROLS +-- - Basic: +-- - Tab, Shift+Tab Cycle through text editable fields. +-- - Ctrl+Tab, Ctrl+Shift+Tab Cycle through windows. +-- - Ctrl+Click Input text into a Slider or Drag widget. +-- - Extended features with `io.ConfigFlags = bit32.bor(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard)`: +-- - Tab, Shift+Tab: Cycle through every items. +-- - Arrow keys Move through items using directional navigation. Tweak value. +-- - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys). +-- - Enter Activate item (prefer text input when possible). +-- - Space Activate item (prefer tweaking with arrows when possible). +-- - Escape Deactivate item, leave child window, close popup. +-- - Page Up, Page Down Previous page, next page. +-- - Home, End Scroll to top, scroll to bottom. +-- - Alt Toggle between scrolling layer and menu layer. +-- - Ctrl+Tab then Ctrl+Arrows Move window. Hold Shift to resize instead of moving. +-- - Menu or Shift+F10 Open context menu. +-- - Output when ImGuiConfigFlags.NavEnableKeyboard set, +-- - io.WantCaptureKeyboard flag is set when keyboard is claimed. +-- - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags.NoNavInputs flag set. +-- - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used). +-- +-- - GAMEPAD CONTROLS +-- - Enable with 'io.ConfigFlags = bit32.bor(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad)'. +-- - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse! +-- - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets +-- - Backend support: backend needs to: +-- - Set 'io.BackendFlags = bit32.bor(io.BackendFlags, ImGuiBackendFlags.HasGamepad)' + call io:AddKeyEvent()/io:AddKeyAnalogEvent() with ImGuiKey.GamepadXXX keys. +-- - For analog values (0.0 to 1.0), 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.). +-- - (The Roblox and LÖVE backends of this port currently handle mouse and keyboard only: gamepad and touch are not wired up yet.) +-- - 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. +-- +-- - REMOTE INPUTS SHARING & MOUSE EMULATION +-- - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions. +-- - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the io.ConfigNavMoveSetMousePos flag. +-- Enabling io.ConfigNavMoveSetMousePos + ImGuiBackendFlags.HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements. +-- When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved. +-- When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. +-- (If you set the io.ConfigNavMoveSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!) +-- +-- +-- PROGRAMMER GUIDE +-- ================ +-- +-- READ FIRST +-- ---------- +-- - Remember to check the wonderful Wiki: https://github.com/ocornut/imgui/wiki +-- - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone! +-- The UI can be highly dynamic, there are no construction or destruction steps, less superfluous +-- data retention on your side, less state duplication, less state synchronization, fewer bugs. +-- - Call and read ImGui.ShowDemoWindow() for demo code demonstrating most features (imgui_demo.lua, a port of imgui_demo.cpp). +-- Or browse pthom's online imgui_explorer: https://pthom.github.io/imgui_explorer for a web version w/ source code browser. +-- - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori). +-- You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki. +-- - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances. +-- For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI, +-- where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches. +-- - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right. +-- - IM_ASSERT() is used throughout the code, like upstream. +-- If you get an assert, read the messages and comments around the assert. +-- - This codebase aims to be highly optimized: +-- - A typical idle frame should allocate as little as possible (in Luau: avoid creating tables/closures per frame). +-- - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible. +-- - This codebase aims to be both highly opinionated and highly flexible: +-- - This code works because of the things it choose to solve or not solve. +-- - The port keeps upstream's structure (ImGui is a table of free functions, structures are plain tables) +-- so that upstream code, comments and documentation map almost 1:1. See docs/PORTING.md for the porting rules. +-- +-- +-- HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI +-- ---------------------------------------------- +-- - Update by re-pulling this repository (or updating the Wally package / downloading a newer release), +-- then rebuild the bundle (python3 tools/bundle.py, or --target love) and overwrite every file. +-- - This port tracks upstream; read upstream's "API BREAKING CHANGES" (see below) when the tracked upstream version changes. +-- If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed +-- from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will +-- likely be a comment about it. Please report any issue to the GitHub page! +-- - Try to keep your copy of Dear ImGui reasonably up to date! +-- +-- +-- GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE +-- --------------------------------------------------------------- +-- - See https://github.com/ocornut/imgui/wiki/Getting-Started, and README.md of this repository. +-- - Run and study the examples and demo in imgui_demo.lua to get acquainted with the library. +-- - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder +-- (backends/imgui_impl_roblox.lua for Roblox, backends/imgui_impl_love.lua for LÖVE). +-- - Build a single file with tools/bundle.py: build/ImGui.luau (Roblox ModuleScript) or build/imgui_love.lua (LÖVE), +-- then require() / load it. All exported names (ImGui, ImVec2, ImVec4, IM_COL32, every ImGui*Flags enum...) are fields of the returned table. +-- - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. +-- - Dear ImGui never touches or knows about your GPU state. The only function that knows about rendering is the draw function that you provide (the backend's RenderDrawData). +-- Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" +-- phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui.Render(). +-- - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code. +-- +-- +-- HOW A SIMPLE APPLICATION MAY LOOK LIKE +-- -------------------------------------- +-- +-- USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.lua files from the backends/ folder). +-- The sub-folders in examples/ contain examples applications following this structure. +-- +-- Roblox (LocalScript, see examples/example_roblox/main.client.luau): +-- +-- local G = require(ReplicatedStorage:WaitForChild("ImGui")) +-- local ImGui, ImGui_ImplRoblox = G.ImGui, G.ImGui_ImplRoblox +-- +-- -- Application init: create a dear imgui context, setup some options, load fonts +-- ImGui.CreateContext() +-- local io = ImGui.GetIO() +-- -- TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags = bit32.bor(io.ConfigFlags, G.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. +-- +-- -- Initialize helper Platform and Renderer backend (here we are using imgui_impl_roblox.lua) +-- ImGui_ImplRoblox.Init() +-- +-- -- Application main loop +-- RunService.Stepped:Connect(function() +-- -- Feed inputs to dear imgui, start new frame +-- ImGui_ImplRoblox.NewFrame() +-- ImGui.NewFrame() +-- +-- -- Any application code here +-- ImGui.Text("Hello, world!") +-- +-- -- Render dear imgui +-- ImGui.Render() +-- ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData()) +-- end) +-- +-- -- Shutdown +-- ImGui_ImplRoblox.Shutdown() +-- ImGui.DestroyContext() +-- +-- LÖVE (see examples/example_love/main.lua): +-- +-- function love.load() +-- ImGui.CreateContext() +-- G.ImGui_ImplLove.Init({ root = ROOT }) +-- end +-- function love.update(dt) +-- G.ImGui_ImplLove.NewFrame() +-- ImGui.NewFrame() +-- ImGui.Text("Hello, world!") +-- ImGui.Render() +-- end +-- function love.draw() +-- G.ImGui_ImplLove.RenderDrawData(ImGui.GetDrawData()) +-- end +-- -- + forward love.mousemoved/mousepressed/mousereleased/wheelmoved/keypressed/keyreleased/textinput/focus +-- -- to G.ImGui_ImplLove.MouseMoved/MousePressed/MouseReleased/WheelMoved/KeyPressed/KeyReleased/TextInput/Focus. +-- +-- 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. +-- +-- +-- USAGE +-- ----- +-- +-- Widget functions are called every frame; their return values tell you what the user did. +-- Out-parameters of the C++ API (bool* p_open, float* v, int* v...) are passed by value and the new value is returned: +-- +-- ImGui.Text("Hello, world %d", 123) +-- if ImGui.Button("Save") then +-- MySaveFunction() +-- end +-- ImGui.InputText("string", buf, 256) -- buf = ImGui.NewTextBuffer("...", 256), edited in place +-- f = ImGui.SliderFloat("float", f, 0.0, 1.0) -- returns (value, changed) +-- pressed, v = ImGui.Checkbox("checkbox", v) +-- +-- -- Create a window called "My First Tool", with a menu bar. +-- my_tool_active = ImGui.Begin("My First Tool", my_tool_active, ImGuiWindowFlags.MenuBar) -- returns (open, visible) +-- if ImGui.BeginMenuBar() then +-- if ImGui.BeginMenu("File") then +-- if ImGui.MenuItem("Close", "Ctrl+W") then my_tool_active = false end +-- ImGui.EndMenu() +-- end +-- ImGui.EndMenuBar() +-- end +-- ImGui.ColorEdit4("Color", my_color) -- ImVec4 / arrays are edited in place +-- ImGui.End() +-- +-- +-- USING CUSTOM BACKEND / CUSTOM ENGINE +-- ------------------------------------ +-- +-- A backend implements the usual Dear ImGui contract: Init, NewFrame, RenderDrawData, inputs -> io:AddXXXEvent(), +-- texture updates via ImTextureData. Adding another Lua host means a new backends/imgui_impl_.lua. +-- -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions. +-- -> the backends in backends/imgui_impl_roblox.lua and backends/imgui_impl_love.lua are complete implementations. +-- +-- Basic application/backend skeleton: +-- +-- -- Application init: create a Dear ImGui context, setup some options, load fonts +-- ImGui.CreateContext() +-- local io = ImGui.GetIO() +-- -- TODO: set io.ConfigXXX values, e.g. +-- io.ConfigFlags = bit32.bor(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) -- Enable keyboard controls +-- +-- -- TODO: Load TTF/OTF fonts if you don't want to use the default font. +-- io.Fonts:AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0) +-- +-- -- Application main loop (called once per frame) +-- local function OnFrame(dt) +-- -- Setup low-level inputs, or write to those fields from your input event handlers, etc. +-- -- (In the examples/ app this is usually done within the ImGui_ImplXXX.NewFrame() function from one of the Backends) +-- io.DeltaTime = dt -- set the time elapsed since the previous frame (in seconds) +-- io.DisplaySize.x = 1920.0 -- set the current display width +-- io.DisplaySize.y = 1280.0 -- set the current display height here +-- io:AddMousePosEvent(mouse_x, mouse_y) -- update mouse position +-- io:AddMouseButtonEvent(0, mouse_b0) -- update mouse button states +-- io:AddMouseButtonEvent(1, mouse_b1) -- update mouse button states +-- +-- -- Call NewFrame(), after this point you can use ImGui.* functions anytime +-- -- (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere) +-- ImGui.NewFrame() +-- +-- -- Most of your application code here +-- ImGui.Text("Hello, world!") +-- 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! +-- +-- -- 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() -- this is automatically called by Render(), but available +-- ImGui.Render() +-- +-- -- Update textures +-- local draw_data = ImGui.GetDrawData() +-- for _, tex in draw_data.Textures:iter() do +-- if tex.Status ~= ImTextureStatus.OK then +-- MyImGuiBackend_UpdateTexture(tex) +-- end +-- end +-- +-- -- Render dear imgui contents +-- MyImGuiBackend_RenderDrawData(draw_data) +-- end +-- +-- -- Shutdown +-- ImGui.DestroyContext() +-- +-- +-- +-- API BREAKING CHANGES +-- ==================== +-- +-- This port tracks upstream Dear ImGui 1.93 WIP (docking branch). +-- For the change-log of API breaking changes, see the top of upstream imgui.cpp, or https://github.com/ocornut/imgui/releases +-- +-- +-- FREQUENTLY ASKED QUESTIONS (FAQ) +-- ================================ +-- +-- Read all answers online: +-- https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url) +-- For questions specific to this port (Roblox, LÖVE, performance, differences from C++), see the FAQ in README.md of this repository. +-- + --- Dear ImGui WIP -- (Core Code) @@ -157,6 +573,9 @@ IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS = true -- Don't implement ImStd.ImFileOpen/ IMGUI_DISABLE_DEBUG_TOOLS = false -- Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty +-- Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be ~= nil. +-- - ImGui.CreateContext() will automatically set this pointer if it is nil. +-- Change to a different context by calling ImGui.SetCurrentContext(). --- @type ImGuiContext? local GImGui = nil @@ -174,10 +593,13 @@ local function LUA_TableConstructorWrapper(T, size, userdata) return p end +-- Memory Allocator functions. Use SetAllocatorFunctions() to change them. +-- - You probably don't want to modify that mid-program. local GImAllocatorAllocFunc = LUA_TableConstructorWrapper local GImAllocatorFreeFunc = function(p0, p1, p2) end local GImAllocatorUserData = nil +-- IM_ALLOC() == ImGui.MemAlloc() --- @param constructor function --- @param size int function ImGui.MemAlloc(constructor, size) @@ -189,6 +611,7 @@ function ImGui.MemAlloc(constructor, size) return p end +-- IM_FREE() == ImGui.MemFree() -- This does not set `owner[field]` to nil! --- @param owner table --- @param field string|int @@ -202,6 +625,7 @@ function ImGui.MemFree(owner, field) return GImAllocatorFreeFunc(owner, field, GImAllocatorUserData) end +-- We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames" --- @param info ImGuiDebugAllocInfo --- @param frame_count int --- @param ptr table @@ -242,6 +666,10 @@ do --[[ [SECTION] imgui_dragdrop (was imgui_dragdrop.lua) ]] -- Drag and drop: 1:1 port of imgui.cpp [SECTION] DRAG AND DROP (docking branch) -- Payload `Data` is any Lua value (no copy is made). `data_size` is optional and only kept for API parity. +------------------------------------------------------------------------------- +-- [SECTION] DRAG AND DROP +------------------------------------------------------------------------------- + function ImGui.IsDragDropActive() return ImGui.GetCurrentContext().DragDropActive end @@ -257,11 +685,20 @@ function ImGui.ClearDragDrop() g.DragDropAcceptFrameCount = -1 end +-- When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource() +-- If the item has an identifier: +-- - This assume/require the item to be activated (typically via ButtonBehavior). +-- - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button. +-- - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag. +-- If the item has no identifier: +-- - Currently always assume left mouse button. function ImGui.BeginDragDropSource(flags) if flags == nil then flags = 0 end local g = ImGui.GetCurrentContext() local window = g.CurrentWindow + -- FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button, + -- in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic). local mouse_button = ImGuiMouseButton.Left local source_drag_active = false @@ -270,19 +707,30 @@ function ImGui.BeginDragDropSource(flags) if bit32.band(flags, ImGuiDragDropFlags.SourceExtern) == 0 then source_id = g.LastItemData.ID if source_id ~= 0 then + -- Common path: items with ID if g.ActiveId ~= source_id then return false end if g.ActiveIdMouseButton ~= -1 then mouse_button = g.ActiveIdMouseButton end if g.IO.MouseDown[mouse_button] == false or window.SkipItems then return false end g.ActiveIdAllowOverlap = false else + -- Uncommon path: items without ID if g.IO.MouseDown[mouse_button] == false or window.SkipItems then return false end if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) == 0 and (g.ActiveId == 0 or g.ActiveIdWindow ~= window) then return false end + + -- If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to: + -- A) Read the explanation below, B) Use the ImGuiDragDropFlags.SourceAllowNullID flag. if bit32.band(flags, ImGuiDragDropFlags.SourceAllowNullID) == 0 then IM_ASSERT(false, "Use ImGuiDragDropFlags.SourceAllowNullID for items without an ID") return false end + + -- Magic fallback to handle items with no assigned ID, e.g. Text(), Image() + -- We build a throwaway ID based on current ID stack + relative AABB of items in window. + -- THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZING OF THE WIDGET, so if your widget moves your dragging operation will be canceled. + -- We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive. + -- Rely on keeping other window.LastItemXXX fields intact. source_id = window:GetIDFromRectangle(g.LastItemData.Rect) g.LastItemData.ID = source_id ImGui.KeepAliveID(source_id) @@ -291,14 +739,16 @@ function ImGui.BeginDragDropSource(flags) ImGui.SetActiveID(source_id, window) ImGui.FocusWindow(window) end - if g.ActiveId == source_id then g.ActiveIdAllowOverlap = is_hovered end + if g.ActiveId == source_id then g.ActiveIdAllowOverlap = is_hovered end -- Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker. end if g.ActiveId ~= source_id then return false end source_parent_id = window.IDStack.Data[window.IDStack.Size] source_drag_active = ImGui.IsMouseDragging(mouse_button) + -- Disable navigation and key inputs while dragging + cancel existing request if any ImGui.SetActiveIdUsingAllKeyboardKeys() else + -- When ImGuiDragDropFlags.SourceExtern is set: window = nil source_id = ImHashStr("#SourceExtern") source_drag_active = true @@ -307,9 +757,10 @@ function ImGui.BeginDragDropSource(flags) ImGui.SetActiveID(source_id, nil) end - IM_ASSERT(g.DragDropWithinTarget == false) + IM_ASSERT(g.DragDropWithinTarget == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() if not source_drag_active then return false end + -- Activate drag and drop if not g.DragDropActive then IM_ASSERT(source_id ~= 0) ImGui.ClearDragDrop() @@ -325,13 +776,15 @@ function ImGui.BeginDragDropSource(flags) g.DragDropWithinSource = true if bit32.band(flags, ImGuiDragDropFlags.SourceNoPreviewTooltip) == 0 then + -- Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit) + -- We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents. local ret if g.DragDropAcceptIdPrev ~= 0 and bit32.band(g.DragDropAcceptFlagsPrev, ImGuiDragDropFlags.AcceptNoPreviewTooltip) ~= 0 then ret = ImGui.BeginTooltipHidden() else ret = ImGui.BeginTooltip() end - IM_ASSERT(ret) + IM_ASSERT(ret) -- FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", nil, ImGuiWindowFlags.NoSavedSettings) + SetWindowHiddenAndSkipItemsForCurrentFrame(). end if bit32.band(flags, ImGuiDragDropFlags.SourceNoDisableHover) == 0 and bit32.band(flags, ImGuiDragDropFlags.SourceExtern) == 0 then @@ -349,10 +802,12 @@ function ImGui.EndDragDropSource() ImGui.EndTooltip() end + -- Discard the drag if have not called SetDragDropPayload() if g.DragDropPayload.DataFrameCount == -1 then ImGui.ClearDragDrop() end g.DragDropWithinSource = false end +-- Use 'cond' to choose to submit payload on drag start or every frame --- @param data any # any Lua value --- @return bool accepted function ImGui.SetDragDropPayload(type, data, data_size, cond) @@ -363,15 +818,17 @@ function ImGui.SetDragDropPayload(type, data, data_size, cond) IM_ASSERT(type ~= nil) IM_ASSERT(#type < 32, "Payload type can be at most 32 characters long") IM_ASSERT(cond == ImGuiCond.Always or cond == ImGuiCond.Once) - IM_ASSERT(payload.SourceId ~= 0) + IM_ASSERT(payload.SourceId ~= 0) -- Not called between BeginDragDropSource() and EndDragDropSource() if cond == ImGuiCond.Always or payload.DataFrameCount == -1 then + -- Copy payload payload.DataType = type payload.Data = data payload.DataSize = data_size or ((data ~= nil) and 1 or 0) end payload.DataFrameCount = g.FrameCount + -- Return whether the payload has been accepted return (g.DragDropAcceptFrameCount == g.FrameCount) or (g.DragDropAcceptFrameCount == g.FrameCount - 1) end @@ -386,15 +843,19 @@ function ImGui.BeginDragDropTargetCustom(bb, id) if not ImGui.IsMouseHoveringRect(bb.Min, bb.Max) or (id == g.DragDropPayload.SourceId) then return false end if window.SkipItems then return false end - IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) + IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() g.DragDropTargetRect = ImRect(bb.Min, bb.Max) - g.DragDropTargetClipRect = ImRect(window.ClipRect.Min, window.ClipRect.Max) + g.DragDropTargetClipRect = ImRect(window.ClipRect.Min, window.ClipRect.Max) -- May want to be overridden by user depending on use case? g.DragDropTargetId = id g.DragDropTargetFullViewport = 0 g.DragDropWithinTarget = true return true end +-- Typical usage would be: +-- if not ImGui.IsWindowHovered(bit32.bor(ImGuiHoveredFlags.AnyWindow, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem)) then +-- if ImGui.BeginDragDropTargetViewport(ImGui.GetMainViewport(), nil) then +-- But we are leaving the hover test to the caller for maximum flexibility. function ImGui.BeginDragDropTargetViewport(viewport, p_bb) local g = ImGui.GetCurrentContext() if not g.DragDropActive then return false end @@ -405,7 +866,7 @@ function ImGui.BeginDragDropTargetViewport(viewport, p_bb) return false end - IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) + IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() g.DragDropTargetRect = ImRect(bb.Min, bb.Max) g.DragDropTargetClipRect = ImRect(bb.Min, bb.Max) g.DragDropTargetId = id @@ -414,6 +875,10 @@ function ImGui.BeginDragDropTargetViewport(viewport, p_bb) return true end +-- We don't use BeginDragDropTargetCustom() and duplicate its code because: +-- 1) we use LastItemData's ImGuiItemStatusFlags.HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them. +-- 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can. +-- Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case) function ImGui.BeginDragDropTarget() local g = ImGui.GetCurrentContext() if not g.DragDropActive then return false end @@ -431,7 +896,7 @@ function ImGui.BeginDragDropTarget() end if g.DragDropPayload.SourceId == id then return false end - IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) + IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() g.DragDropTargetRect = ImRect(display_rect.Min, display_rect.Max) local clip = (bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasClipRect) ~= 0) and g.LastItemData.ClipRect or window.ClipRect g.DragDropTargetClipRect = ImRect(clip.Min, clip.Max) @@ -450,10 +915,12 @@ function ImGui.AcceptDragDropPayload(type, flags) if flags == nil then flags = 0 end local g = ImGui.GetCurrentContext() local payload = g.DragDropPayload - IM_ASSERT(g.DragDropActive) - IM_ASSERT(payload.DataFrameCount ~= -1) + IM_ASSERT(g.DragDropActive) -- Not called between BeginDragDropTarget() and EndDragDropTarget() ? + IM_ASSERT(payload.DataFrameCount ~= -1) -- Forgot to call EndDragDropTarget() ? if type ~= nil and not ImGuiPayload_IsDataType(payload, type) then return nil end + -- Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints. + -- NB: We currently accept nil id as target. However, overlapping targets requires a unique ID to function! local was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId) local r = g.DragDropTargetRect local r_surface = r:GetWidth() * r:GetHeight() @@ -462,9 +929,11 @@ function ImGui.AcceptDragDropPayload(type, flags) g.DragDropAcceptFlagsCurr = flags g.DragDropAcceptIdCurr = g.DragDropTargetId g.DragDropAcceptIdCurrRectSurface = r_surface + -- IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId) + -- Render default drop visuals payload.Preview = was_accepted_previously - flags = bit32.bor(flags, bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.AcceptNoDrawDefaultRect)) + flags = bit32.bor(flags, bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.AcceptNoDrawDefaultRect)) -- Source can also inhibit the preview (useful for external sources that live for 1 frame) local draw_target_rect = payload.Preview and bit32.band(flags, ImGuiDragDropFlags.AcceptNoDrawDefaultRect) == 0 if draw_target_rect and g.DragDropTargetFullViewport ~= 0 then ImGui.RenderDragDropTargetRectForViewport(g.DragDropTargetFullViewport, g.DragDropTargetRect) @@ -476,17 +945,18 @@ function ImGui.AcceptDragDropPayload(type, flags) if bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceExtern) ~= 0 and g.DragDropMouseButton == -1 then payload.Delivery = was_accepted_previously and (g.DragDropSourceFrameCount < g.FrameCount) else - payload.Delivery = was_accepted_previously and not ImGui.IsMouseDown(g.DragDropMouseButton) + payload.Delivery = was_accepted_previously and not ImGui.IsMouseDown(g.DragDropMouseButton) -- For extern drag sources affecting OS window focus, it's easier to just test not IsMouseDown() instead of IsMouseReleased() end if not payload.Delivery and bit32.band(flags, ImGuiDragDropFlags.AcceptBeforeDelivery) == 0 then return nil end return payload end +-- FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target. function ImGui.RenderDragDropTargetRectForItem(bb) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow local bb_display = ImRect(bb.Min, bb.Max) - bb_display:ClipWith(g.DragDropTargetClipRect) + bb_display:ClipWith(g.DragDropTargetClipRect) -- Clip THEN expand so we have a way to visualize that target is not entirely visible. bb_display:Expand(g.Style.DragDropTargetPadding) local push_clip_rect = not window.ClipRect:Contains(bb_display) if push_clip_rect then window.DrawList:PushClipRectFullScreen() end @@ -520,6 +990,8 @@ function ImGui.EndDragDropTarget() IM_ASSERT(g.DragDropActive) IM_ASSERT(g.DragDropWithinTarget) g.DragDropWithinTarget = false + + -- Clear drag and drop state payload right after delivery if g.DragDropPayload.Delivery then ImGui.ClearDragDrop() end end @@ -539,54 +1011,129 @@ do --[[ [SECTION] imgui_docking (was imgui_docking.lua) ]] -- - node.ChildNodes is a table indexed [0] and [1] like upstream. -- - ImGuiDockPreviewData.DropRectsDraw is indexed [dir + 1] with dir in -1..3 (so keys 0..4), like upstream. +------------------------------------------------------------------------------- +-- [SECTION] DOCKING +------------------------------------------------------------------------------- +-- Docking: Internal Types +-- Docking: Forward Declarations +-- Docking: ImGuiDockContext +-- Docking: ImGuiDockContext Docking/Undocking functions +-- Docking: ImGuiDockNode +-- Docking: ImGuiDockNode Tree manipulation functions +-- Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) +-- Docking: Builder Functions +-- Docking: Begin/End Support Functions (called from Begin/End) +-- Docking: Settings +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- Typical Docking call flow: (root level is generally public API): +------------------------------------------------------------------------------- +-- - NewFrame() new dear imgui frame +-- | DockContextNewFrameUpdateUndocking() - process queued undocking requests +-- | - DockContextProcessUndockWindow() - process one window undocking request +-- | - DockContextProcessUndockNode() - process one whole node undocking request +-- | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes +-- | - update g.HoveredDockNode - [debug] update node hovered by mouse +-- | - DockContextProcessDock() - process one docking request +-- | - DockNodeUpdate() +-- | - DockNodeUpdateForRootNode() +-- | - DockNodeUpdateFlagsAndCollapse() +-- | - DockNodeFindInfo() +-- | - destroy unused node or tab bar +-- | - create dock node host window +-- | - Begin() etc. +-- | - DockNodeStartMouseMovingWindow() +-- | - DockNodeTreeUpdatePosSize() +-- | - DockNodeTreeUpdateSplitter() +-- | - draw node background +-- | - DockNodeUpdateTabBar() - create/update tab bar for a docking node +-- | - DockNodeAddTabBar() +-- | - DockNodeWindowMenuUpdate() +-- | - DockNodeCalcTabBarLayout() +-- | - BeginTabBarEx() +-- | - TabItemEx() calls +-- | - EndTabBar() +-- | - BeginDockableDragDropTarget() +-- | - DockNodeUpdate() - recurse into child nodes... +------------------------------------------------------------------------------- +-- - DockSpace() user submit a dockspace into a window +-- | Begin(Child) - create a child window +-- | DockNodeUpdate() - call main dock node update function +-- | End(Child) +-- | ItemSize() +------------------------------------------------------------------------------- +-- - Begin() +-- | BeginDocked() +-- | BeginDockableDragDropSource() +-- | BeginDockableDragDropTarget() +-- | - DockNodePreviewDockRender() +------------------------------------------------------------------------------- +-- - EndFrame() +-- | DockContextEndFrame() +------------------------------------------------------------------------------- + local MT = ImGui.GetMetatables() -IMGUI_PAYLOAD_TYPE_WINDOW = "_IMWINDOW" +IMGUI_PAYLOAD_TYPE_WINDOW = "_IMWINDOW" -- Payload == ImGuiWindow local DOCKING_HOST_DRAW_CHANNEL_BG = 0 -- Dock host: background fill local DOCKING_HOST_DRAW_CHANNEL_FG = 1 -- Dock host: decorations and contents local DOCKING_SPLITTER_SIZE = 2.0 ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: flags & enums ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Flags for ImGui.DockSpace(), shared/inherited by child nodes. +-- (Some flags can be applied to individual nodes directly) +-- FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api. ImGuiDockNodeFlags = { None = 0, - KeepAliveOnly = bit32.lshift(1, 0), - NoDockingOverCentralNode = bit32.lshift(1, 2), - PassthruCentralNode = bit32.lshift(1, 3), - NoDockingSplit = bit32.lshift(1, 4), - NoResize = bit32.lshift(1, 5), - AutoHideTabBar = bit32.lshift(1, 6), - NoUndocking = bit32.lshift(1, 7), + KeepAliveOnly = bit32.lshift(1, 0), -- -- Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. + -- NoCentralNode = bit32.lshift(1, 1), -- -- Disable Central Node (the node which can stay empty) + NoDockingOverCentralNode = bit32.lshift(1, 2), -- -- Disable docking over the Central Node, which will be always kept empty. + PassthruCentralNode = bit32.lshift(1, 3), -- -- Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol.WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. + NoDockingSplit = bit32.lshift(1, 4), -- -- Disable other windows/nodes from splitting this node. + NoResize = bit32.lshift(1, 5), -- Saved -- Disable resizing node using the splitter/separators. Useful with programmatically setup dockspaces. + AutoHideTabBar = bit32.lshift(1, 6), -- -- Tab bar will automatically hide when there is a single window in the dock node. + NoUndocking = bit32.lshift(1, 7), -- -- Disable undocking this node. + + -- Extend ImGuiDockNodeFlags_ (ImGuiDockNodeFlagsPrivate_) -- [Internal] - DockSpace = bit32.lshift(1, 10), - CentralNode = bit32.lshift(1, 11), - NoTabBar = bit32.lshift(1, 12), - HiddenTabBar = bit32.lshift(1, 13), - NoWindowMenuButton = bit32.lshift(1, 14), - NoCloseButton = bit32.lshift(1, 15), - NoResizeX = bit32.lshift(1, 16), - NoResizeY = bit32.lshift(1, 17), - DockedWindowsInFocusRoute = bit32.lshift(1, 18), - NoDockingSplitOther = bit32.lshift(1, 19), - NoDockingOverMe = bit32.lshift(1, 20), - NoDockingOverOther = bit32.lshift(1, 21), - NoDockingOverEmpty = bit32.lshift(1, 22), + DockSpace = bit32.lshift(1, 10), -- Saved -- A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. + CentralNode = bit32.lshift(1, 11), -- Saved -- The central node has 2 main properties: stay visible when empty, only use "remaining" spaces from its neighbor. + NoTabBar = bit32.lshift(1, 12), -- Saved -- Tab bar is completely unavailable. No triangle in the corner to enable it back. + HiddenTabBar = bit32.lshift(1, 13), -- Saved -- Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) + NoWindowMenuButton = bit32.lshift(1, 14), -- Saved -- Disable window/docking menu (that one that appears instead of the collapse button) + NoCloseButton = bit32.lshift(1, 15), -- Saved -- Disable close button + NoResizeX = bit32.lshift(1, 16), -- -- + NoResizeY = bit32.lshift(1, 17), -- -- + DockedWindowsInFocusRoute = bit32.lshift(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. + NoDockingSplitOther = bit32.lshift(1, 19), -- -- Disable this node from splitting other windows/nodes. + NoDockingOverMe = bit32.lshift(1, 20), -- -- Disable other windows/nodes from being docked over this node. + NoDockingOverOther = bit32.lshift(1, 21), -- -- Disable this node from being docked over another window or non-empty node. + NoDockingOverEmpty = bit32.lshift(1, 22), -- -- Disable this node from being docked over an empty node (e.g. DockSpace with no other windows) } do local F = ImGuiDockNodeFlags - F.NoSplit = F.NoDockingSplit - F.NoDockingInCentralNode = F.NoDockingOverCentralNode + F.NoSplit = F.NoDockingSplit -- Renamed in 1.90 + F.NoDockingInCentralNode = F.NoDockingOverCentralNode -- Renamed in 1.90 F.NoDocking = bit32.bor(F.NoDockingOverMe, F.NoDockingOverOther, F.NoDockingOverEmpty, F.NoDockingSplit, F.NoDockingSplitOther) + -- Masks F.SharedFlagsInheritMask_ = 0xFFFFFFFF F.NoResizeFlagsMask_ = bit32.bor(F.NoResize, F.NoResizeX, F.NoResizeY) + -- When splitting, those local flags are moved to the inheriting child, never duplicated F.LocalFlagsTransferMask_ = bit32.bor(F.NoDockingSplit, F.NoResizeFlagsMask_, F.AutoHideTabBar, F.CentralNode, F.NoTabBar, F.HiddenTabBar, F.NoWindowMenuButton, F.NoCloseButton) F.SavedFlagsMask_ = bit32.bor(F.NoResizeFlagsMask_, F.DockSpace, F.CentralNode, F.NoTabBar, F.HiddenTabBar, F.NoWindowMenuButton, F.NoCloseButton) end +-- Store the source authority (dock node vs window) of a field ImGuiDataAuthority = { Auto = 0, DockNode = 1, Window = 2 } ImGuiDockNodeState = { @@ -596,35 +1143,50 @@ ImGuiDockNodeState = { HostWindowVisible = 3, } +-- List of colors that are stored at the time of Begin() into Docked Windows. +-- We currently store the packed colors in a simple array window.DockStyle.Colors[]. +-- A better solution may involve appending into a log of colors in ImGuiContext + store offsets into those arrays in ImGuiWindow, +-- but it would be more complex as we'd need to double-buffer both as e.g. drop target may refer to window from last frame. ImGuiWindowDockStyleCol = { Text = 0, TabHovered = 1, TabFocused = 2, TabSelected = 3, TabSelectedOverline = 4, TabDimmed = 5, TabDimmedSelected = 6, TabDimmedSelectedOverline = 7, UnsavedMarker = 8, COUNT = 9, } -local ImGuiDockRequestType = { None = 0, Dock = 1, Undock = 2, Split = 3 } - ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Internal Types ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - ImGuiDockRequestType +-- - ImGuiDockRequest +-- - ImGuiDockPreviewData +-- - ImGuiDockNodeSettings +-- - ImGuiDockContext +------------------------------------------------------------------------------- + +local ImGuiDockRequestType = { None = 0, Dock = 1, Undock = 2, Split = 3 } -- Split is the same as Dock but without a DockPayload local function ImGuiDockRequest() return { Type = ImGuiDockRequestType.None, + -- DockTargetWindow: Destination/Target Window to dock into (may be a loose window or a DockNode, might be nil in which case DockTargetNode cannot be nil) + -- DockTargetNode: Destination/Target Node to dock into + -- DockPayload: Source/Payload window to dock (may be a loose window or a DockNode), [Optional] DockTargetWindow = nil, DockTargetNode = nil, DockPayload = nil, DockSplitDir = ImGuiDir.None, DockSplitRatio = 0.5, DockSplitOuter = false, UndockTargetWindow = nil, UndockTargetNode = nil, } end +-- Persistent Settings data, stored contiguously in SettingsNodes local function ImGuiDockNodeSettings() return { ID = 0, ParentNodeId = 0, ParentWindowId = 0, SelectedTabId = 0, - SplitAxis = ImGuiAxis.None, Depth = 0, Flags = 0, + SplitAxis = ImGuiAxis.None, Depth = 0, Flags = 0, -- Flags: NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags.SavedFlagsMask_) Pos = ImVec2(0, 0), Size = ImVec2(0, 0), SizeRef = ImVec2(0, 0), } end function ImGuiDockContext() + -- Nodes: Map ID -> ImGuiDockNode: Active nodes return { Nodes = {}, Requests = ImVector(), NodesSettings = ImVector(), WantFullRebuild = false } end @@ -635,25 +1197,44 @@ local DN = MT.ImGuiDockNode function ImGuiDockNode(id) return setmetatable({ ID = id, + -- SharedFlags: (Write) Flags shared by all nodes of a same dockspace hierarchy (inherited from the root node) + -- LocalFlags: (Write) Flags specific to this node + -- LocalFlagsInWindows: (Write) Flags specific to this node, applied from windows + -- MergedFlags: (Read) Effective flags (== SharedFlags | LocalFlagsInNode | LocalFlagsInWindows) SharedFlags = 0, LocalFlags = 0, LocalFlagsInWindows = 0, MergedFlags = 0, State = ImGuiDockNodeState.Unknown, ParentNode = nil, - ChildNodes = { [0] = nil, [1] = nil }, - Windows = ImVector(), + ChildNodes = { [0] = nil, [1] = nil }, -- [Split node only] Child nodes (left/right or top/bottom). Consider switching to an array. + Windows = ImVector(), -- Note: unordered list! Iterate TabBar.Tabs for user-order. TabBar = nil, + -- Pos: Current position + -- Size: Current size + -- SizeRef: [Split node only] Last explicitly written-to size (overridden when using a splitter affecting the node), used to calculate Size. Pos = ImVec2(0, 0), Size = ImVec2(0, 0), SizeRef = ImVec2(0, 0), - SplitAxis = ImGuiAxis.None, + SplitAxis = ImGuiAxis.None, -- [Split node only] Split axis (X or Y) LastBgColor = IM_COL32_WHITE, - WindowClass = ImGuiWindowClass(), + WindowClass = ImGuiWindowClass(), -- [Root node only] + -- VisibleWindow: Generally point to window which is ID is == SelectedTabID, but when CTRL+Tabbing this can be a different window. HostWindow = nil, VisibleWindow = nil, + -- CentralNode: [Root node only] Pointer to central node. + -- OnlyNodeWithWindows: [Root node only] Set when there is a single visible node within the hierarchy. CentralNode = nil, OnlyNodeWithWindows = nil, - CountNodeWithWindows = 0, + CountNodeWithWindows = 0, -- [Root node only] + -- LastFrameAlive: Last frame number the node was updated or kept alive explicitly with DockSpace() + ImGuiDockNodeFlags.KeepAliveOnly + -- LastFrameActive: Last frame number the node was updated. + -- LastFrameFocused: Last frame number the node was focused. LastFrameAlive = -1, LastFrameActive = -1, LastFrameFocused = -1, + -- LastFocusedNodeId: [Root node only] Which of our child docking node (any ancestor in the hierarchy) was last focused. + -- SelectedTabId: [Leaf node only] Which of our tab/window is selected. + -- WantCloseTabId: [Leaf node only] Set when closing a specific tab/window. + -- RefViewportId: Reference viewport ID from visible window when HostWindow == nil. LastFocusedNodeId = 0, SelectedTabId = 0, WantCloseTabId = 0, RefViewportId = 0, - AuthorityForPos = ImGuiDataAuthority.DockNode, AuthorityForSize = ImGuiDataAuthority.DockNode, + AuthorityForPos = ImGuiDataAuthority.DockNode, AuthorityForSize = ImGuiDataAuthority.DockNode, -- ImGuiDataAuthority AuthorityForViewport = ImGuiDataAuthority.Auto, - IsVisible = true, IsFocused = false, IsBgDrawnThisFrame = false, - HasCloseButton = false, HasWindowMenuButton = false, HasCentralNodeChild = false, + IsVisible = true, IsFocused = false, IsBgDrawnThisFrame = false, -- IsVisible: Set to false when the node is hidden (usually disabled as it has no active window) + HasCloseButton = false, HasWindowMenuButton = false, HasCentralNodeChild = false, -- HasCloseButton: Provide space for a close button (if any of the docked window has one). Note that button may be hidden on window without one. + -- WantCloseAll: Set when closing all tabs at once. + -- WantMouseMove: After a node extraction we need to transition toward moving the newly created host window WantCloseAll = false, WantLockSizeOnce = false, WantMouseMove = false, WantHiddenTabBarUpdate = false, WantHiddenTabBarToggle = false, }, DN) @@ -663,8 +1244,8 @@ function DN:IsRootNode() return self.ParentNode == nil end function DN:IsDockSpace() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.DockSpace) ~= 0 end function DN:IsFloatingNode() return self.ParentNode == nil and bit32.band(self.MergedFlags, ImGuiDockNodeFlags.DockSpace) == 0 end function DN:IsCentralNode() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.CentralNode) ~= 0 end -function DN:IsHiddenTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.HiddenTabBar) ~= 0 end -function DN:IsNoTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.NoTabBar) ~= 0 end +function DN:IsHiddenTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.HiddenTabBar) ~= 0 end -- Hidden tab bar can be shown back by clicking the small triangle +function DN:IsNoTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.NoTabBar) ~= 0 end -- Never show a tab bar function DN:IsSplitNode() return self.ChildNodes[0] ~= nil end function DN:IsLeafNode() return self.ChildNodes[0] == nil end function DN:IsEmpty() return self.ChildNodes[0] == nil and self.Windows.Size == 0 end @@ -675,9 +1256,11 @@ function DN:UpdateMergedFlags() self.MergedFlags = bit32.bor(self.SharedFlags, s local function ImGuiDockPreviewData() local d = { FutureNode = ImGuiDockNode(0), + -- IsSidesAvailable: Hold your breath, grammar freaks.. + -- IsSplitDirExplicit: Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window) IsDropAllowed = false, IsCenterAvailable = false, IsSidesAvailable = false, IsSplitDirExplicit = false, SplitNode = nil, SplitDir = ImGuiDir.None, SplitRatio = 0.0, - DropRectsDraw = {}, + DropRectsDraw = {}, -- May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects() } for n = 0, 4 do d.DropRectsDraw[n] = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX) end return d @@ -698,20 +1281,51 @@ local function DockContextNodesSorted(ctx) end ImGui.DockContextNodesSorted = DockContextNodesSorted ---------------------------------------------------------------------------------------- --- Docking: ImGuiDockContext ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Docking: Forward Declarations +------------------------------------------------------------------------------- +-- Settings local DockSettingsHandler_ClearAll, DockSettingsHandler_ApplyAll, DockSettingsHandler_ReadOpen, DockSettingsHandler_ReadLine, DockSettingsHandler_WriteAll local DockSettingsRenameNodeReferences, DockSettingsRemoveNodeReferences, DockSettingsFindNodeSettings +------------------------------------------------------------------------------- +-- Docking: ImGuiDockContext +------------------------------------------------------------------------------- +-- The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings, +-- or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active. +-- At boot time only, we run a simple GC to remove nodes that have no references. +-- Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures), +-- we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does). +-- This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data. +------------------------------------------------------------------------------- +-- - DockContextInitialize() +-- - DockContextShutdown() +-- - DockContextClearNodes() +-- - DockContextRebuildNodes() +-- - DockContextNewFrameUpdateUndocking() +-- - DockContextNewFrameUpdateDocking() +-- - DockContextEndFrame() +-- - DockContextFindNodeByID() +-- - DockContextBindNodeToWindow() +-- - DockContextGenNodeID() +-- - DockContextAddNode() +-- - DockContextRemoveNode() +-- - ImGuiDockContextPruneNodeData +-- - DockContextPruneUnusedSettingsNodes() +-- - DockContextBuildNodesFromSettings() +-- - DockContextBuildAddWindowsToNodes() +------------------------------------------------------------------------------- + function ImGui.DockContextInitialize(ctx) local g = ctx + + -- Add .ini handle for persistent docking data local ini_handler = ImGuiSettingsHandler() ini_handler.TypeName = "Docking" ini_handler.TypeHash = ImHashStr("Docking") ini_handler.ClearAllFn = DockSettingsHandler_ClearAll - ini_handler.ReadInitFn = DockSettingsHandler_ClearAll + ini_handler.ReadInitFn = DockSettingsHandler_ClearAll -- Also clear on read ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen ini_handler.ReadLineFn = DockSettingsHandler_ReadLine ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll @@ -733,15 +1347,18 @@ function ImGui.DockContextClearNodes(ctx, root_id, clear_settings_refs) ImGui.DockBuilderRemoveNodeChildNodes(root_id) end +-- [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch +-- (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!) function ImGui.DockContextRebuildNodes(ctx) local dc = ctx.DockContext ImGui.SaveIniSettingsToMemory() - local root_id = 0 + local root_id = 0 -- Rebuild all ImGui.DockContextClearNodes(ctx, root_id, false) ImGui.DockContextBuildNodesFromSettings(ctx, dc.NodesSettings.Data, dc.NodesSettings.Size) ImGui.DockContextBuildAddWindowsToNodes(ctx, root_id) end +-- Docking context update function, called by NewFrame() function ImGui.DockContextNewFrameUpdateUndocking(ctx) local g = ctx local dc = ctx.DockContext @@ -752,20 +1369,24 @@ function ImGui.DockContextNewFrameUpdateUndocking(ctx) return end + -- Setting NoSplit at runtime merges all nodes if g.IO.ConfigDockingNoSplit then for _, id in ipairs(DockContextNodesSorted(ctx)) do local node = dc.Nodes[id] if node and node:IsRootNode() and node:IsSplitNode() then ImGui.DockBuilderRemoveNodeChildNodes(node.ID) + -- dc.WantFullRebuild = true end end end + -- Process full rebuild if dc.WantFullRebuild then ImGui.DockContextRebuildNodes(ctx) dc.WantFullRebuild = false end + -- Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame) for _, req in dc.Requests:iter() do if req.Type == ImGuiDockRequestType.Undock and req.UndockTargetWindow then ImGui.DockContextProcessUndockWindow(ctx, req.UndockTargetWindow) @@ -775,11 +1396,15 @@ function ImGui.DockContextNewFrameUpdateUndocking(ctx) end end +-- Docking context update function, called by NewFrame() function ImGui.DockContextNewFrameUpdateDocking(ctx) local g = ctx local dc = ctx.DockContext if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then return end + -- [DEBUG] Store hovered dock node. + -- We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using .DockNode is a good shortcut. + -- Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering. g.DebugHoveredDockNode = nil local hovered_window = g.HoveredWindowUnderMovingWindow if hovered_window then @@ -790,6 +1415,7 @@ function ImGui.DockContextNewFrameUpdateDocking(ctx) end end + -- Process Docking requests for _, req in dc.Requests:iter() do if req.Type == ImGuiDockRequestType.Dock then ImGui.DockContextProcessDock(ctx, req) @@ -797,6 +1423,7 @@ function ImGui.DockContextNewFrameUpdateDocking(ctx) end dc.Requests:resize(0) + -- Create windows for each automatic docking nodes for _, id in ipairs(DockContextNodesSorted(ctx)) do local node = dc.Nodes[id] if node and node:IsFloatingNode() then @@ -806,6 +1433,7 @@ function ImGui.DockContextNewFrameUpdateDocking(ctx) end function ImGui.DockContextEndFrame(ctx) + -- Draw backgrounds of node missing their window local g = ctx local dc = g.DockContext for _, id in ipairs(DockContextNodesSorted(ctx)) do @@ -824,17 +1452,23 @@ function ImGui.DockContextFindNodeByID(ctx, id) end function ImGui.DockContextGenNodeID(ctx) + -- Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used) + -- FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0 + -- We should poke in ctx.Nodes to find a suitable ID faster. Even more so trivial that ctx.Nodes lookup is already sorted. local id = 0x0001 while ImGui.DockContextFindNodeByID(ctx, id) ~= nil do id = id + 1 end return id end function ImGui.DockContextAddNode(ctx, id) + -- Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window. if id == 0 then id = ImGui.DockContextGenNodeID(ctx) else IM_ASSERT(ImGui.DockContextFindNodeByID(ctx, id) == nil) end + + -- We don't set node.LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings! local node = ImGuiDockNode(id) ctx.DockContext.Nodes[node.ID] = node return node @@ -863,12 +1497,14 @@ function ImGui.DockContextRemoveNode(ctx, node, merge_sibling_into_parent_node) end end +-- Raw-ish delete function ImGui.DockContextDeleteNode(ctx, node) local dc = ctx.DockContext node.TabBar = nil dc.Nodes[node.ID] = nil end +-- Garbage collect unused nodes (run once at init time) function ImGui.DockContextPruneUnusedSettingsNodes(ctx) local g = ctx local dc = ctx.DockContext @@ -881,9 +1517,10 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) return d end + -- Count child nodes and compute RootID for _, settings in dc.NodesSettings:iter() do if pool[settings.ID] ~= nil then - settings.ID = 0 + settings.ID = 0 -- Duplicate else local parent_data = (settings.ParentNodeId ~= 0) and pool[settings.ParentNodeId] or nil GetOrAdd(settings.ID).RootId = parent_data and parent_data.RootId or settings.ID @@ -894,6 +1531,8 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) end end + -- Count reference to dock ids from dockspaces + -- We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes() for _, settings in dc.NodesSettings:iter() do if settings.ParentWindowId ~= 0 then local window_settings = ImGui.FindWindowSettingsByID(settings.ParentWindowId) @@ -904,6 +1543,8 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) end end + -- Count reference to dock ids from window settings + -- We guard against the possibility of an invalid .ini file (RootID may point to a missing node) for _, settings in g.SettingsWindows:iter() do local dock_id = settings.DockId if dock_id and dock_id ~= 0 then @@ -916,6 +1557,7 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) end end + -- Prune for _, settings in dc.NodesSettings:iter() do local data = pool[settings.ID] if data ~= nil and data.CountWindows <= 1 then @@ -923,8 +1565,8 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) local data_parent = (settings.ParentNodeId ~= 0) and pool[settings.ParentNodeId] or nil local remove = false - remove = remove or (data.CountWindows == 1 and settings.ParentNodeId == 0 and data.CountChildNodes == 0 and bit32.band(settings.Flags, ImGuiDockNodeFlags.CentralNode) == 0) - remove = remove or (data.CountWindows == 0 and settings.ParentNodeId == 0 and data.CountChildNodes == 0) + remove = remove or (data.CountWindows == 1 and settings.ParentNodeId == 0 and data.CountChildNodes == 0 and bit32.band(settings.Flags, ImGuiDockNodeFlags.CentralNode) == 0) -- Floating root node with only 1 window + remove = remove or (data.CountWindows == 0 and settings.ParentNodeId == 0 and data.CountChildNodes == 0) -- Leaf nodes with 0 window remove = remove or (data_root == nil or data_root.CountChildWindows == 0) if remove then DockSettingsRemoveNodeReferences({ settings.ID }, 1) @@ -939,6 +1581,7 @@ end --- @param node_settings_array table # 1-based array function ImGui.DockContextBuildNodesFromSettings(ctx, node_settings_array, node_settings_count) + -- Build nodes for node_n = 1, node_settings_count do local settings = node_settings_array[node_n] if settings.ID ~= 0 and ImGui.DockContextFindNodeByID(ctx, settings.ID) == nil then @@ -959,6 +1602,8 @@ function ImGui.DockContextBuildNodesFromSettings(ctx, node_settings_array, node_ node.SplitAxis = settings.SplitAxis node:SetLocalFlags(bit32.band(settings.Flags, ImGuiDockNodeFlags.SavedFlagsMask_)) + -- Bind host window immediately if it already exist (in case of a rebuild) + -- This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node.HostWindow to be set. local root_node = ImGui.DockNodeGetRootNode(node) node.HostWindow = ImGui.FindWindowByName(DockNodeGetHostWindowTitle(root_node)) end @@ -966,11 +1611,12 @@ function ImGui.DockContextBuildNodesFromSettings(ctx, node_settings_array, node_ end function ImGui.DockContextBuildAddWindowsToNodes(ctx, root_id) + -- Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame) local g = ctx for _, window in g.Windows:iter() do if window.DockId ~= 0 and window.LastFrameActive >= g.FrameCount - 1 and window.DockNode == nil then local node = ImGui.DockContextFindNodeByID(ctx, window.DockId) - IM_ASSERT(node ~= nil) + IM_ASSERT(node ~= nil) -- This should have been called after DockContextBuildNodesFromSettings() if root_id == 0 or ImGui.DockNodeGetRootNode(node).ID == root_id then ImGui.DockNodeAddWindow(node, window, true) end @@ -978,9 +1624,18 @@ function ImGui.DockContextBuildAddWindowsToNodes(ctx, root_id) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: ImGuiDockContext Docking/Undocking functions ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockContextQueueDock() +-- - DockContextQueueUndockWindow() +-- - DockContextQueueUndockNode() +-- - DockContextQueueNotifyRemovedNode() +-- - DockContextProcessDock() +-- - DockContextProcessUndockWindow() +-- - DockContextProcessUndockNode() +-- - DockContextCalcDropPosForDocking() +------------------------------------------------------------------------------- function ImGui.DockContextQueueDock(ctx, target, target_node, payload, split_dir, split_ratio, split_outer) IM_ASSERT(target ~= payload) @@ -1020,26 +1675,30 @@ function ImGui.DockContextProcessDock(ctx, req) IM_ASSERT(req.DockTargetWindow ~= nil or req.DockTargetNode ~= nil) local g = ctx - local payload_window = req.DockPayload + local payload_window = req.DockPayload -- Optional local target_window = req.DockTargetWindow local node = req.DockTargetNode + -- Decide which Tab will be selected at the end of the operation local next_selected_id = 0 local payload_node = nil if payload_window then payload_node = payload_window.DockNodeAsHost - payload_window.DockNodeAsHost = nil + payload_window.DockNodeAsHost = nil -- Important to clear this as the node will have its life as a child which might be merged/deleted later. if payload_node and payload_node:IsLeafNode() then next_selected_id = (payload_node.TabBar.NextSelectedTabId ~= 0) and payload_node.TabBar.NextSelectedTabId or payload_node.TabBar.SelectedTabId end if payload_node == nil then next_selected_id = payload_window.TabId end end + -- FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well + -- When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==. if node then IM_ASSERT(node.LastFrameAlive <= g.FrameCount) end if node and target_window and node == target_window.DockNodeAsHost then IM_ASSERT(node.Windows.Size > 0 or node:IsSplitNode() or node:IsCentralNode()) end + -- Create new node and add existing window to it if node == nil then node = ImGui.DockContextAddNode(ctx, 0) node.Pos = ImVec2(target_window.Pos.x, target_window.Pos.y) @@ -1054,10 +1713,11 @@ function ImGui.DockContextProcessDock(ctx, req) local split_dir = req.DockSplitDir if split_dir ~= ImGuiDir.None then + -- Split into two, one side will be our payload node unless we are dropping a loose window local split_axis = (split_dir == ImGuiDir.Left or split_dir == ImGuiDir.Right) and ImGuiAxis.X or ImGuiAxis.Y - local split_inheritor_child_idx = (split_dir == ImGuiDir.Left or split_dir == ImGuiDir.Up) and 1 or 0 + local split_inheritor_child_idx = (split_dir == ImGuiDir.Left or split_dir == ImGuiDir.Up) and 1 or 0 -- Current contents will be moved to the opposite side local split_ratio = req.DockSplitRatio - ImGui.DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node) + ImGui.DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node) -- payload_node may be nil here! local new_node = node.ChildNodes[bit32.bxor(split_inheritor_child_idx, 1)] new_node.HostWindow = node.HostWindow node = new_node @@ -1065,6 +1725,7 @@ function ImGui.DockContextProcessDock(ctx, req) node:SetLocalFlags(bit32.band(node.LocalFlags, bit32.bnot(ImGuiDockNodeFlags.HiddenTabBar))) if node ~= payload_node then + -- Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!) if node.Windows.Size > 0 and node.TabBar == nil then ImGui.DockNodeAddTabBar(node) for n = 1, node.Windows.Size do @@ -1073,9 +1734,13 @@ function ImGui.DockContextProcessDock(ctx, req) end if payload_node ~= nil then + -- Transfer full payload node (with 1+ child windows or child nodes) if payload_node:IsSplitNode() then if node.Windows.Size > 0 then - IM_ASSERT(payload_node.OnlyNodeWithWindows ~= nil) + -- We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node. + -- In this situation, we move the windows of the target node into the currently visible node of the payload. + -- This allows us to preserve some of the underlying dock tree settings nicely. + IM_ASSERT(payload_node.OnlyNodeWithWindows ~= nil) -- The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted. local visible_node = payload_node.OnlyNodeWithWindows if visible_node.TabBar then IM_ASSERT(visible_node.TabBar.Tabs.Size > 0) end ImGui.DockNodeMoveWindows(node, visible_node) @@ -1083,6 +1748,8 @@ function ImGui.DockContextProcessDock(ctx, req) DockSettingsRenameNodeReferences(node.ID, visible_node.ID) end if node:IsCentralNode() then + -- Central node property needs to be moved to a leaf node, pick the last focused one. + -- FIXME-DOCK: If we had to transfer other flags here, what would the policy be? local last_focused_node = ImGui.DockContextFindNodeByID(ctx, payload_node.LastFocusedNodeId) IM_ASSERT(last_focused_node ~= nil) local last_focused_root_node = ImGui.DockNodeGetRootNode(last_focused_node) @@ -1101,6 +1768,7 @@ function ImGui.DockContextProcessDock(ctx, req) end ImGui.DockContextRemoveNode(ctx, payload_node, true) elseif payload_window then + -- Transfer single window local payload_dock_id = payload_window.DockId node.VisibleWindow = payload_window ImGui.DockNodeAddWindow(node, payload_window, true) @@ -1109,14 +1777,24 @@ function ImGui.DockContextProcessDock(ctx, req) end end else + -- When docking a floating single window node we want to reevaluate auto-hiding of the tab bar node.WantHiddenTabBarUpdate = true end + -- Update selection immediately local tab_bar = node.TabBar if tab_bar then tab_bar.NextSelectedTabId = next_selected_id end ImGui.MarkIniSettingsDirty() end +-- Problem: +-- Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more +-- than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic +-- with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be +-- due to missing ImGuiBackendFlags.HasMouseCursors backend flag). +-- Solution: +-- When undocking a window we currently force its maximum size to 90% of the host viewport. +-- Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch). local function FixLargeWindowsWhenUndocking(size, ref_viewport) if ref_viewport == nil then return size end local max_size = ImTrunc(ref_viewport.WorkSize * 0.90) @@ -1145,6 +1823,7 @@ function ImGui.DockContextProcessUndockNode(ctx, node) IM_ASSERT(node.Windows.Size >= 1) if node:IsRootNode() or node:IsCentralNode() then + -- In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload. local new_node = ImGui.DockContextAddNode(ctx, 0) new_node.Pos = ImVec2(node.Pos.x, node.Pos.y) new_node.Size = ImVec2(node.Size.x, node.Size.y) @@ -1153,11 +1832,12 @@ function ImGui.DockContextProcessUndockNode(ctx, node) DockSettingsRenameNodeReferences(node.ID, new_node.ID) node = new_node else + -- Otherwise extract our node and merge our sibling back into the parent node. IM_ASSERT(node.ParentNode.ChildNodes[0] == node or node.ParentNode.ChildNodes[1] == node) local index_in_parent = (node.ParentNode.ChildNodes[0] == node) and 0 or 1 node.ParentNode.ChildNodes[index_in_parent] = nil ImGui.DockNodeTreeMerge(ctx, node.ParentNode, node.ParentNode.ChildNodes[bit32.bxor(index_in_parent, 1)]) - node.ParentNode.AuthorityForViewport = ImGuiDataAuthority.Window + node.ParentNode.AuthorityForViewport = ImGuiDataAuthority.Window -- The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport node.ParentNode = nil end for _, window in node.Windows:iter() do @@ -1172,9 +1852,13 @@ function ImGui.DockContextProcessUndockNode(ctx, node) ImGui.MarkIniSettingsDirty() end +-- This is mostly used for automation. --- @return bool ok, ImVec2? out_pos function ImGui.DockContextCalcDropPosForDocking(target, target_node, payload_window, payload_node, split_dir, split_outer) if target ~= nil and target_node == nil then target_node = target.DockNode end + + -- In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects + -- (which would be functionally identical) we only show the outer one. Reflect this here. if target_node and target_node.ParentNode == nil and target_node:IsCentralNode() and split_dir ~= ImGuiDir.None then split_outer = true end @@ -1185,9 +1869,38 @@ function ImGui.DockContextCalcDropPosForDocking(target, target_node, payload_win return true, r:GetCenter() end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: ImGuiDockNode ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockNodeGetTabOrder() +-- - DockNodeAddWindow() +-- - DockNodeRemoveWindow() +-- - DockNodeMoveChildNodes() +-- - DockNodeMoveWindows() +-- - DockNodeApplyPosSizeToWindows() +-- - DockNodeHideHostWindow() +-- - ImGuiDockNodeFindInfoResults +-- - DockNodeFindInfo() +-- - DockNodeFindWindowByID() +-- - DockNodeUpdateFlagsAndCollapse() +-- - DockNodeUpdateHasCentralNodeFlag() +-- - DockNodeUpdateVisibleFlag() +-- - DockNodeStartMouseMovingWindow() +-- - DockNodeUpdate() +-- - DockNodeUpdateWindowMenu() +-- - DockNodeBeginAmendTabBar() +-- - DockNodeEndAmendTabBar() +-- - DockNodeUpdateTabBar() +-- - DockNodeAddTabBar() +-- - DockNodeRemoveTabBar() +-- - DockNodeIsDropAllowedOne() +-- - DockNodeIsDropAllowed() +-- - DockNodeCalcTabBarLayout() +-- - DockNodeCalcSplitRects() +-- - DockNodeCalcDropRectsAndTestMousePos() +-- - DockNodePreviewDockSetup() +-- - DockNodePreviewDockRender() +------------------------------------------------------------------------------- function ImGui.DockNodeGetTabOrder(window) local tab_bar = window.DockNode.TabBar @@ -1203,11 +1916,15 @@ end function ImGui.DockNodeAddWindow(node, window, add_to_tab_bar) if window.DockNode then + -- Can overwrite an existing window.DockNode (e.g. pointing to a disabled DockSpace node) IM_ASSERT(window.DockNode.ID ~= node.ID) ImGui.DockNodeRemoveWindow(window.DockNode, window, 0) end IM_ASSERT(window.DockNode == nil or window.DockNodeAsHost == nil) + -- If more than 2 windows appeared on the same frame leading to the creation of a new hosting window, + -- we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame). + -- We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin() if node.HostWindow == nil and node.Windows.Size == 1 and node.Windows.Data[1].WasActive == false then DockNodeHideWindowDuringHostWindowCreation(node.Windows.Data[1]) end @@ -1219,17 +1936,22 @@ function ImGui.DockNodeAddWindow(node, window, add_to_tab_bar) window.DockIsActive = (node.Windows.Size > 1) window.DockTabWantClose = false + -- When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage. + -- In particular it is important we init the viewport from the first window so we don't create two viewports and drop one. if node.HostWindow == nil and node:IsFloatingNode() then if node.AuthorityForPos == ImGuiDataAuthority.Auto then node.AuthorityForPos = ImGuiDataAuthority.Window end if node.AuthorityForSize == ImGuiDataAuthority.Auto then node.AuthorityForSize = ImGuiDataAuthority.Window end if node.AuthorityForViewport == ImGuiDataAuthority.Auto then node.AuthorityForViewport = ImGuiDataAuthority.Window end end + -- Add to tab bar if requested if add_to_tab_bar then if node.TabBar == nil then ImGui.DockNodeAddTabBar(node) node.TabBar.SelectedTabId = node.SelectedTabId node.TabBar.NextSelectedTabId = node.SelectedTabId + + -- Add existing windows for n = 1, node.Windows.Size - 1 do ImGui.TabBarAddTab(node.TabBar, ImGuiTabItemFlags.None, node.Windows.Data[n]) end @@ -1239,6 +1961,7 @@ function ImGui.DockNodeAddWindow(node, window, add_to_tab_bar) ImGui.DockNodeUpdateVisibleFlag(node) + -- Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame. if node.HostWindow then ImGui.UpdateWindowParentAndRootLinks(window, bit32.bor(window.Flags, ImGuiWindowFlags.ChildWindow), node.HostWindow) end @@ -1246,6 +1969,8 @@ end function ImGui.DockNodeRemoveWindow(node, window, save_dock_id) IM_ASSERT(window.DockNode == node) + -- IM_ASSERT(window.RootWindowDockTree == node.HostWindow) + -- IM_ASSERT(window.LastFrameActive < g.FrameCount) -- We may call this from Begin() IM_ASSERT(save_dock_id == 0 or save_dock_id == node.ID) window.DockNode = nil @@ -1254,20 +1979,24 @@ function ImGui.DockNodeRemoveWindow(node, window, save_dock_id) window.DockId = save_dock_id window.Flags = bit32.band(window.Flags, bit32.bnot(ImGuiWindowFlags.ChildWindow)) if window.ParentWindow then window.ParentWindow.DC.ChildWindows:find_erase(window) end - ImGui.UpdateWindowParentAndRootLinks(window, window.Flags, nil) + ImGui.UpdateWindowParentAndRootLinks(window, window.Flags, nil) -- Update immediately if node.HostWindow and node.HostWindow.ViewportOwned then + -- When undocking from a user interaction this will always run in NewFrame() and have not much effect. + -- But mid-frame, if we clear viewport we need to mark window as hidden as well. window.Viewport = nil window.ViewportId = 0 window.ViewportOwned = false window.Hidden = true end + -- Remove window local idx = node.Windows:find_index(window) IM_ASSERT(idx ~= nil) node.Windows:erase(idx) if node.VisibleWindow == window then node.VisibleWindow = nil end + -- Remove tab and possibly tab bar node.WantHiddenTabBarUpdate = true if node.TabBar then ImGui.TabBarRemoveTab(node.TabBar, window.TabId) @@ -1276,16 +2005,20 @@ function ImGui.DockNodeRemoveWindow(node, window, save_dock_id) ImGui.DockNodeRemoveTabBar(node) end end + if node.Windows.Size == 0 and not node:IsCentralNode() and not node:IsDockSpace() and window.DockId ~= node.ID then + -- Automatic dock node delete themselves if they are not holding at least one tab ImGui.DockContextRemoveNode(ImGui.GetCurrentContext(), node, true) return end if node.Windows.Size == 1 and not node:IsCentralNode() and node.HostWindow then local remaining_window = node.Windows.Data[1] + -- Note: we used to transport viewport ownership here. remaining_window.Collapsed = node.HostWindow.Collapsed end + -- Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree ImGui.DockNodeUpdateVisibleFlag(node) end @@ -1302,16 +2035,19 @@ function ImGui.DockNodeMoveChildNodes(dst_node, src_node) end function ImGui.DockNodeMoveWindows(dst_node, src_node) + -- Insert tabs in the same orders as currently ordered (node.Windows isn't ordered) IM_ASSERT(src_node and dst_node and dst_node ~= src_node) local src_tab_bar = src_node.TabBar if src_tab_bar ~= nil then IM_ASSERT(src_node.Windows.Size <= src_node.TabBar.Tabs.Size) end + -- If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.) local move_tab_bar = (src_tab_bar ~= nil) and (dst_node.TabBar == nil) if move_tab_bar then dst_node.TabBar = src_node.TabBar src_node.TabBar = nil end + -- Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar(). -- Snapshot: DockNodeAddWindow() won't touch src_node.Windows since window.DockNode is cleared first local windows = {} for i = 1, src_node.Windows.Size do windows[i] = src_node.Windows.Data[i] end @@ -1330,7 +2066,7 @@ end function ImGui.DockNodeApplyPosSizeToWindows(node) for _, window in node.Windows:iter() do - ImGui.SetWindowPos(window, node.Pos, ImGuiCond.Always) + ImGui.SetWindowPos(window, node.Pos, ImGuiCond.Always) -- We don't assign directly to Pos because it can break the calculation of SizeContents on next frame ImGui.SetWindowSize(window, node.Size, ImGuiCond.Always) end end @@ -1347,13 +2083,14 @@ function ImGui.DockNodeHideHostWindow(node) if node.TabBar then ImGui.DockNodeRemoveTabBar(node) end end +-- Search function called once by root node in DockNodeUpdate() local function DockNodeFindInfo(node, info) if node.Windows.Size > 0 then if info.FirstNodeWithWindows == nil then info.FirstNodeWithWindows = node end info.CountNodesWithWindows = info.CountNodesWithWindows + 1 end if node:IsCentralNode() then - IM_ASSERT(info.CentralNode == nil) + IM_ASSERT(info.CentralNode == nil) -- Should be only one IM_ASSERT(node:IsLeafNode(), "If you get this assert: please submit .ini file + repro of actions leading to this.") info.CentralNode = node end @@ -1370,18 +2107,27 @@ function ImGui.DockNodeFindWindowByID(node, id) return nil end +-- - Remove inactive windows/nodes. +-- - Update visibility flag. function ImGui.DockNodeUpdateFlagsAndCollapse(node) local g = ImGui.GetCurrentContext() IM_ASSERT(node.ParentNode == nil or node.ParentNode.ChildNodes[0] == node or node.ParentNode.ChildNodes[1] == node) + -- Inherit most flags if node.ParentNode then node.SharedFlags = bit32.band(node.ParentNode.SharedFlags, ImGuiDockNodeFlags.SharedFlagsInheritMask_) end + -- Recurse into children + -- There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'. + -- If 'node.ChildNode[0]' delete itself, then 'node.ChildNode[1].Windows' will be moved into 'node' + -- If 'node.ChildNode[1]' delete itself, then 'node.ChildNode[0].Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless) node.HasCentralNodeChild = false if node.ChildNodes[0] then ImGui.DockNodeUpdateFlagsAndCollapse(node.ChildNodes[0]) end if node.ChildNodes[1] then ImGui.DockNodeUpdateFlagsAndCollapse(node.ChildNodes[1]) end + -- Remove inactive windows, collapse nodes + -- Merge node flags overrides stored in windows node.LocalFlagsInWindows = ImGuiDockNodeFlags.None local window_n = 1 while window_n <= node.Windows.Size do @@ -1390,35 +2136,40 @@ function ImGui.DockNodeUpdateFlagsAndCollapse(node) local node_was_active = (node.LastFrameActive + 1 == g.FrameCount) local remove = false - remove = remove or (node_was_active and (window.WasActive == false)) - remove = remove or (node_was_active and (node.WantCloseAll or node.WantCloseTabId == window.TabId) and window.HasCloseButton and bit32.band(window.Flags, ImGuiWindowFlags.UnsavedDocument) == 0) + remove = remove or (node_was_active and (window.WasActive == false)) -- Can't use 'window.LastFrameActive + 1 < g.FrameCount'. (see #9151) + remove = remove or (node_was_active and (node.WantCloseAll or node.WantCloseTabId == window.TabId) and window.HasCloseButton and bit32.band(window.Flags, ImGuiWindowFlags.UnsavedDocument) == 0) -- Submit all _expected_ closure from last frame remove = remove or window.DockTabWantClose if remove then window.DockTabWantClose = false if node.Windows.Size == 1 and not node:IsCentralNode() then ImGui.DockNodeHideHostWindow(node) node.State = ImGuiDockNodeState.HostWindowHiddenBecauseSingleWindow - ImGui.DockNodeRemoveWindow(node, window, node.ID) + ImGui.DockNodeRemoveWindow(node, window, node.ID) -- Will delete the node so it'll be invalid on return return end ImGui.DockNodeRemoveWindow(node, window, node.ID) else + -- FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this. + -- node.LocalFlagsInWindow = bit32.band(node.LocalFlagsInWindow, bit32.bnot(window.WindowClass.DockNodeFlagsOverrideClear)) node.LocalFlagsInWindows = bit32.bor(node.LocalFlagsInWindows, window.WindowClass.DockNodeFlagsOverrideSet) window_n = window_n + 1 end end node:UpdateMergedFlags() + -- Auto-hide tab bar option local node_flags = node.MergedFlags if node.WantHiddenTabBarUpdate and node.Windows.Size == 1 and bit32.band(node_flags, ImGuiDockNodeFlags.AutoHideTabBar) ~= 0 and not node:IsHiddenTabBar() then node.WantHiddenTabBarToggle = true end node.WantHiddenTabBarUpdate = false + -- Cancel toggling if we know our tab bar is enforced to be hidden at all times if node.WantHiddenTabBarToggle and node.VisibleWindow and bit32.band(node.VisibleWindow.WindowClass.DockNodeFlagsOverrideSet, ImGuiDockNodeFlags.HiddenTabBar) ~= 0 then node.WantHiddenTabBarToggle = false end + -- Apply toggles at a single point of the frame (here!) local prev_local_flags = node.LocalFlags if node.Windows.Size > 1 then node:SetLocalFlags(bit32.band(node.LocalFlags, bit32.bnot(ImGuiDockNodeFlags.HiddenTabBar))) @@ -1426,13 +2177,14 @@ function ImGui.DockNodeUpdateFlagsAndCollapse(node) node:SetLocalFlags(bit32.bxor(node.LocalFlags, ImGuiDockNodeFlags.HiddenTabBar)) end if bit32.band(bit32.bxor(node.LocalFlags, prev_local_flags), ImGuiDockNodeFlags.SavedFlagsMask_) ~= 0 then - ImGui.MarkIniSettingsDirty() + ImGui.MarkIniSettingsDirty() -- Bit flaky to only do this here. Perhaps compare node flags every frame? #9380 end node.WantHiddenTabBarToggle = false ImGui.DockNodeUpdateVisibleFlag(node) end +-- This is rarely called as DockNodeUpdateForRootNode() generally does it most frames. function ImGui.DockNodeUpdateHasCentralNodeChild(node) node.HasCentralNodeChild = false if node.ChildNodes[0] then ImGui.DockNodeUpdateHasCentralNodeChild(node.ChildNodes[0]) end @@ -1447,6 +2199,7 @@ function ImGui.DockNodeUpdateHasCentralNodeChild(node) end function ImGui.DockNodeUpdateVisibleFlag(node) + -- Update visibility flag local is_visible = (node.ParentNode == nil) and node:IsDockSpace() or node:IsCentralNode() is_visible = is_visible or (node.Windows.Size > 0) is_visible = is_visible or (node.ChildNodes[0] ~= nil and node.ChildNodes[0].IsVisible) @@ -1459,13 +2212,17 @@ function ImGui.DockNodeStartMouseMovingWindow(node, window) IM_ASSERT(node.WantMouseMove == true) ImGui.StartMouseMovingWindow(window) ImVec2_Copy(g.ActiveIdClickOffset, g.IO.MouseClickedPos[0] - node.Pos) - g.MovingWindow = window + g.MovingWindow = window -- If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision. node.WantMouseMove = false end +-- Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class. function ImGui.DockNodeUpdateForRootNode(node) ImGui.DockNodeUpdateFlagsAndCollapse(node) + -- - Setup central node pointers + -- - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!) + -- Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing local info = { CentralNode = nil, FirstNodeWithWindows = nil, CountNodesWithWindows = 0 } DockNodeFindInfo(node, info) node.CentralNode = info.CentralNode @@ -1475,6 +2232,9 @@ function ImGui.DockNodeUpdateForRootNode(node) node.LastFocusedNodeId = info.FirstNodeWithWindows.ID end + -- Copy the window class from of our first window so it can be used for proper dock filtering. + -- When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy. + -- FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec. local first_node_with_windows = info.FirstNodeWithWindows if first_node_with_windows then node.WindowClass = first_node_with_windows.Windows.Data[1].WindowClass @@ -1494,6 +2254,11 @@ function ImGui.DockNodeUpdateForRootNode(node) end local function DockNodeSetupHostWindow(node, host_window) + -- Remove ourselves from any previous different host window + -- This can happen if a user mistakenly does (see #4295 for details): + -- - N+0: DockBuilderAddNode(id, 0) -- missing ImGuiDockNodeFlags.DockSpace + -- - N+1: NewFrame() -- will create floating host window for that node + -- - N+1: DockSpace(id) -- requalify node as dockspace, moving host window if node.HostWindow and node.HostWindow ~= host_window and node.HostWindow.DockNodeAsHost == node then node.HostWindow.DockNodeAsHost = nil end @@ -1511,8 +2276,10 @@ function ImGui.DockNodeUpdate(node) node.OnlyNodeWithWindows = nil if node:IsRootNode() then ImGui.DockNodeUpdateForRootNode(node) end + -- Remove tab bar if not needed if node.TabBar and node:IsNoTabBar() then ImGui.DockNodeRemoveTabBar(node) end + -- Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId) local want_to_hide_host_window = false if node:IsFloatingNode() then if node.Windows.Size <= 1 and node:IsLeafNode() then @@ -1524,6 +2291,7 @@ function ImGui.DockNodeUpdate(node) end if want_to_hide_host_window then if node.Windows.Size == 1 then + -- Floating window pos/size is authoritative local single_window = node.Windows.Data[1] node.Pos = ImVec2(single_window.Pos.x, single_window.Pos.y) node.Size = ImVec2(single_window.SizeFull.x, single_window.SizeFull.y) @@ -1531,6 +2299,7 @@ function ImGui.DockNodeUpdate(node) node.AuthorityForSize = ImGuiDataAuthority.Window node.AuthorityForViewport = ImGuiDataAuthority.Window + -- Transfer focus immediately so when we revert to a regular window it is immediately selected if node.HostWindow and g.NavWindow == node.HostWindow then ImGui.FocusWindow(single_window) end @@ -1555,9 +2324,20 @@ function ImGui.DockNodeUpdate(node) return end + -- In some circumstance we will defer creating the host window (so everything will be kept hidden), + -- while the expected visible window is resizing itself. + -- This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled, + -- otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up: + -- N+0: Begin(): window created (with no known size), node is created + -- N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible + -- N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible + -- We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code. + -- It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin(). + -- In reality it isn't very important as user quickly ends up with size data in .ini file. if node.IsVisible and node.HostWindow == nil and node:IsFloatingNode() and node:IsLeafNode() then IM_ASSERT(node.Windows.Size > 0) local ref_window = nil + -- Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them! if node.SelectedTabId ~= 0 then ref_window = ImGui.DockNodeFindWindowByID(node, node.SelectedTabId) end if ref_window == nil then ref_window = node.Windows.Data[1] end if ref_window.AutoFitFramesX > 0 or ref_window.AutoFitFramesY > 0 then @@ -1568,9 +2348,11 @@ function ImGui.DockNodeUpdate(node) local node_flags = node.MergedFlags + -- Decide if the node will have a close button and a window menu button node.HasWindowMenuButton = (node.Windows.Size > 0) and bit32.band(node_flags, ImGuiDockNodeFlags.NoWindowMenuButton) == 0 node.HasCloseButton = false for _, window in node.Windows:iter() do + -- FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call. node.HasCloseButton = node.HasCloseButton or window.HasCloseButton window.DockIsActive = (node.Windows.Size > 1) end @@ -1578,40 +2360,47 @@ function ImGui.DockNodeUpdate(node) node.HasCloseButton = false end + -- Bind or create host window local host_window = nil local beginned_into_host_window = false if node:IsDockSpace() then + -- [Explicit root dockspace node] IM_ASSERT(node.HostWindow) host_window = node.HostWindow else + -- [Automatic root or child nodes] if node:IsRootNode() and node.IsVisible then local ref_window = (node.Windows.Size > 0) and node.Windows.Data[1] or nil + -- Sync Pos if node.AuthorityForPos == ImGuiDataAuthority.Window and ref_window then ImGui.SetNextWindowPos(ref_window.Pos) elseif node.AuthorityForPos == ImGuiDataAuthority.DockNode then ImGui.SetNextWindowPos(node.Pos) end + -- Sync Size if node.AuthorityForSize == ImGuiDataAuthority.Window and ref_window then ImGui.SetNextWindowSize(ref_window.SizeFull) elseif node.AuthorityForSize == ImGuiDataAuthority.DockNode then ImGui.SetNextWindowSize(node.Size) end + -- Sync Collapsed if node.AuthorityForSize == ImGuiDataAuthority.Window and ref_window then ImGui.SetNextWindowCollapsed(ref_window.Collapsed) end ImGui.SetNextWindowClass(node.WindowClass) + -- Begin into the host window local window_label = DockNodeGetHostWindowTitle(node) local window_flags = bit32.bor(ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoScrollWithMouse, ImGuiWindowFlags.DockNodeHost) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoFocusOnAppearing) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoNavFocus, ImGuiWindowFlags.NoCollapse) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoTitleBar) - ImGui.SetNextWindowBgAlpha(0.0) + ImGui.SetNextWindowBgAlpha(0.0) -- Don't set ImGuiWindowFlags.NoBackground because it disables borders ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0, 0)) ImGui.Begin(window_label, nil, window_flags) ImGui.PopStyleVar() @@ -1623,6 +2412,12 @@ function ImGui.DockNodeUpdate(node) node.Pos = ImVec2(host_window.Pos.x, host_window.Pos.y) node.Size = ImVec2(host_window.Size.x, host_window.Size.y) + -- We set ImGuiWindowFlags.NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow) + -- But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags. + -- One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again. + -- When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window + -- during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back + -- after the dock host window, losing their top-most status. if node.HostWindow.Appearing then ImGui.BringWindowToDisplayFront(node.HostWindow) end node.AuthorityForPos = ImGuiDataAuthority.Auto @@ -1639,21 +2434,23 @@ function ImGui.DockNodeUpdate(node) ImGui.DockNodeStartMouseMovingWindow(node, node.HostWindow) end end - node.RefViewportId = 0 + node.RefViewportId = 0 -- Clear when we have a host window + -- Update focused node (the one whose title bar is highlight) within a node tree if node:IsSplitNode() then IM_ASSERT(node.TabBar == nil) end if node:IsRootNode() then local p_window = g.NavWindow and g.NavWindow.RootWindow or nil while p_window ~= nil and p_window.DockNode ~= nil do local p_node = ImGui.DockNodeGetRootNode(p_window.DockNode) if p_node == node then - node.LastFocusedNodeId = p_window.DockNode.ID + node.LastFocusedNodeId = p_window.DockNode.ID -- Note: not using root node ID! break end p_window = p_node.HostWindow and p_node.HostWindow.RootWindow or nil end end + -- Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace local central_node = node.CentralNode local central_node_hole = node:IsRootNode() and host_window ~= nil and bit32.band(node_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0 and central_node ~= nil and central_node:IsEmpty() local central_node_hole_register_hit_test_hole = central_node_hole @@ -1664,7 +2461,10 @@ function ImGui.DockNodeUpdate(node) end end if central_node_hole_register_hit_test_hole then - IM_ASSERT(node:IsDockSpace()) + -- We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily. + -- (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen + -- covering passthru node we'd have a gap on the edge not covered by the hole) + IM_ASSERT(node:IsDockSpace()) -- We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window.ParentNode local root_node = ImGui.DockNodeGetRootNode(central_node) local root_rect = ImRect(root_node.Pos, root_node.Pos + root_node.Size) local hole_rect = ImRect(central_node.Pos, central_node.Pos + central_node.Size) @@ -1672,6 +2472,7 @@ function ImGui.DockNodeUpdate(node) if hole_rect.Max.x < root_rect.Max.x then hole_rect.Max.x = hole_rect.Max.x - g.WindowsBorderHoverPadding end if hole_rect.Min.y > root_rect.Min.y then hole_rect.Min.y = hole_rect.Min.y + g.WindowsBorderHoverPadding end if hole_rect.Max.y < root_rect.Max.y then hole_rect.Max.y = hole_rect.Max.y - g.WindowsBorderHoverPadding end + -- GetForegroundDrawList():AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255)) if central_node_hole and not IsRectInverted(hole_rect) then ImGui.SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min) if host_window.ParentWindow then @@ -1680,6 +2481,7 @@ function ImGui.DockNodeUpdate(node) end end + -- Update position/size, process and draw resizing splitters if node:IsRootNode() and host_window then ImGui.DockNodeTreeUpdatePosSize(node, host_window.Pos, host_window.Size) ImGui.PushStyleColor(ImGuiCol.Separator, g.Style.Colors[ImGuiCol.Border]) @@ -1689,6 +2491,7 @@ function ImGui.DockNodeUpdate(node) ImGui.PopStyleColor(3) end + -- Draw empty node background (currently can only be the Central Node) if host_window and node:IsEmpty() and node.IsVisible then host_window.DrawList:ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG) node.LastBgColor = (bit32.band(node_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0) and 0 or ImGui.GetColorU32(ImGuiCol.DockingEmptyBg) @@ -1698,6 +2501,9 @@ function ImGui.DockNodeUpdate(node) node.IsBgDrawnThisFrame = true end + -- Draw whole dockspace background if ImGuiDockNodeFlags.PassthruCentralNode if set. + -- We need to draw a background at the root level if requested by ImGuiDockNodeFlags.PassthruCentralNode, but we will only know the correct pos/size + -- _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order! local render_dockspace_bg = node:IsRootNode() and host_window ~= nil and bit32.band(node_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0 if render_dockspace_bg and node.IsVisible then host_window.DrawList:ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG) @@ -1708,6 +2514,7 @@ function ImGui.DockNodeUpdate(node) end end + -- Draw and populate Tab Bar if host_window then host_window.DrawList:ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG) end if host_window and node.Windows.Size > 0 then ImGui.DockNodeUpdateTabBar(node, host_window) @@ -1722,20 +2529,27 @@ function ImGui.DockNodeUpdate(node) node.SelectedTabId = node.Windows.Data[1].TabId end + -- Draw payload drop target if host_window and node.IsVisible then if node:IsRootNode() and (g.MovingWindow == nil or g.MovingWindow.RootWindowDockTree ~= host_window) then ImGui.BeginDockableDragDropTarget(host_window) end end + -- We update this after DockNodeUpdateTabBar() node.LastFrameActive = g.FrameCount + -- Recurse into children + -- FIXME-DOCK FIXME-OPT: Should not need to recurse into children if host_window then if node.ChildNodes[0] then ImGui.DockNodeUpdate(node.ChildNodes[0]) end if node.ChildNodes[1] then ImGui.DockNodeUpdate(node.ChildNodes[1]) end + + -- Render outer borders last (after the tab bar) if node:IsRootNode() then ImGui.RenderWindowOuterBorders(host_window) end end + -- End host window if beginned_into_host_window then ImGui.End() end end @@ -1745,6 +2559,7 @@ local GWindowDockStyleColors = { } ImGui.GWindowDockStyleColors = GWindowDockStyleColors +-- Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame. local function TabItemComparerByDockOrder(ta, tb) local a, b = ta.Window, tb.Window local ao = (a.DockOrder == -1) and INT_MAX or a.DockOrder @@ -1753,12 +2568,19 @@ local function TabItemComparerByDockOrder(ta, tb) return a.BeginOrderWithinContext < b.BeginOrderWithinContext end +-- Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node. +-- This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented) +-- Custom overrides may want to decorate, group, sort entries. +-- Please note those are internal structures: if you copy this expect occasional breakage. +-- (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler) function ImGui.DockNodeWindowMenuHandler_Default(ctx, node, tab_bar) if tab_bar.Tabs.Size == 1 then + -- "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table. if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.DockingHideTabBar), nil, node:IsHiddenTabBar()) then node.WantHiddenTabBarToggle = true end else + -- Display a selectable list of windows in this docking node for tab_n = 1, tab_bar.Tabs.Size do local tab = tab_bar.Tabs.Data[tab_n] if bit32.band(tab.Flags, ImGuiTabItemFlags.Button) == 0 then @@ -1773,6 +2595,7 @@ function ImGui.DockNodeWindowMenuHandler_Default(ctx, node, tab_bar) end function ImGui.DockNodeWindowMenuUpdate(node, tab_bar) + -- Try to position the menu so it is more likely to stays within the same viewport local g = ImGui.GetCurrentContext() if g.Style.WindowMenuButtonPosition == ImGuiDir.Left then ImGui.SetNextWindowPos(ImVec2(node.Pos.x, node.Pos.y + ImGui.GetFrameHeight()), ImGuiCond.Always, ImVec2(0.0, 0.0)) @@ -1786,6 +2609,7 @@ function ImGui.DockNodeWindowMenuUpdate(node, tab_bar) end end +-- User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button. function ImGui.DockNodeBeginAmendTabBar(node) if node.TabBar == nil or node.HostWindow == nil then return false end if bit32.band(node.MergedFlags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then return false end @@ -1804,11 +2628,15 @@ function ImGui.DockNodeEndAmendTabBar() end local function IsDockNodeTitleBarHighlighted(node, root_node) + -- CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy) local g = ImGui.GetCurrentContext() if g.NavWindowingTarget then return g.NavWindowingTarget.DockNode == node end + + -- FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window) if g.NavWindow and root_node.LastFocusedNodeId == node.ID then + -- FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node) local parent_window = g.NavWindow.RootWindow while bit32.band(parent_window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 do parent_window = parent_window.ParentWindow.RootWindow @@ -1823,6 +2651,7 @@ local function IsDockNodeTitleBarHighlighted(node, root_node) return false end +-- Submit the tab bar corresponding to a dock node and various housekeeping details. function ImGui.DockNodeUpdateTabBar(node, host_window) local g = ImGui.GetCurrentContext() local style = g.Style @@ -1831,30 +2660,37 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) node.WantCloseAll = false node.WantCloseTabId = 0 + -- Decide if we should use a focused title bar color local is_focused = false local root_node = ImGui.DockNodeGetRootNode(node) if IsDockNodeTitleBarHighlighted(node, root_node) then is_focused = true end + -- Hidden tab bar will show a triangle on the upper-left (in Begin) if node:IsHiddenTabBar() or node:IsNoTabBar() then node.VisibleWindow = (node.Windows.Size > 0) and node.Windows.Data[1] or nil node.IsFocused = is_focused if is_focused then node.LastFrameFocused = g.FrameCount end if node.VisibleWindow then + -- Notify root of visible window (used to display title in OS task bar) if is_focused or root_node.VisibleWindow == nil then root_node.VisibleWindow = node.VisibleWindow end if node.TabBar then node.TabBar.VisibleTabId = node.VisibleWindow.TabId end end return end + -- Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed local backup_skip_item = host_window.SkipItems if not node:IsDockSpace() then host_window.SkipItems = false host_window.DC.NavLayerCurrent = ImGuiNavLayer.Menu end + -- Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID. + -- This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs, + -- as docked windows themselves will override the stack with their own root ID. ImGui.PushOverrideID(node.ID) local tab_bar = node.TabBar - local tab_bar_is_recreated = (tab_bar == nil) + local tab_bar_is_recreated = (tab_bar == nil) -- Tab bar are automatically destroyed when a node gets hidden if tab_bar == nil then ImGui.DockNodeAddTabBar(node) tab_bar = node.TabBar @@ -1866,6 +2702,8 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) local node_flags = node.MergedFlags local has_window_menu_button = bit32.band(node_flags, ImGuiDockNodeFlags.NoWindowMenuButton) == 0 and (style.WindowMenuButtonPosition ~= ImGuiDir.None) + -- In a dock node, the Collapse Button turns into the Window Menu button. + -- FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes? if has_window_menu_button and ImGui.IsPopupOpen("#WindowMenu") then local next_selected_tab_id = tab_bar.NextSelectedTabId ImGui.DockNodeWindowMenuUpdate(node, tab_bar) @@ -1875,8 +2713,10 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) is_focused = is_focused or node.IsFocused end + -- Layout local title_bar_rect, tab_bar_rect, window_menu_button_pos, close_button_pos = ImGui.DockNodeCalcTabBarLayout(node) + -- Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value. local tabs_count_old = tab_bar.Tabs.Size for window_n = 1, node.Windows.Size do local window = node.Windows.Data[window_n] @@ -1885,13 +2725,15 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) end end + -- Title bar if is_focused then node.LastFrameFocused = g.FrameCount end local title_bar_col = ImGui.GetColorU32(host_window.Collapsed and ImGuiCol.TitleBgCollapsed or (is_focused and ImGuiCol.TitleBgActive or ImGuiCol.TitleBg)) local rounding_flags = ImGui.CalcRoundingFlagsForRectInRect(title_bar_rect, host_window:Rect(), g.Style.DockingSeparatorSize) host_window.DrawList:AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window.WindowRounding, rounding_flags) + -- Docking/Collapse button if has_window_menu_button then - if ImGui.CollapseButton(host_window:GetID("#COLLAPSE"), window_menu_button_pos, node) then + if ImGui.CollapseButton(host_window:GetID("#COLLAPSE"), window_menu_button_pos, node) then -- == DockNodeGetWindowMenuButtonId(node) ImGui.OpenPopup("#WindowMenu") end if ImGui.IsItemActive() then focus_tab_id = tab_bar.SelectedTabId end @@ -1900,9 +2742,11 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) end end + -- If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value local tabs_unsorted_start = tab_bar.Tabs.Size -- 0-based local tab_n = tab_bar.Tabs.Size - 1 while tab_n >= 0 and bit32.band(tab_bar.Tabs.Data[tab_n + 1].Flags, ImGuiTabItemFlags.Unsorted) ~= 0 do + -- FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? local t = tab_bar.Tabs.Data[tab_n + 1] t.Flags = bit32.band(t.Flags, bit32.bnot(ImGuiTabItemFlags.Unsorted)) tabs_unsorted_start = tab_n @@ -1915,10 +2759,12 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) for i, t in ipairs(slice) do tab_bar.Tabs.Data[tabs_unsorted_start + i] = t end end + -- Apply NavWindow focus back to the tab bar if g.NavWindow and g.NavWindow.RootWindow.DockNode == node then tab_bar.SelectedTabId = g.NavWindow.RootWindow.TabId end + -- Selected newly added tabs, or persistent tab ID if the tab bar was just recreated if tab_bar_is_recreated and ImGui.TabBarFindTabByID(tab_bar, node.SelectedTabId) ~= nil then tab_bar.SelectedTabId = node.SelectedTabId tab_bar.NextSelectedTabId = node.SelectedTabId @@ -1927,27 +2773,32 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) tab_bar.NextSelectedTabId = tab_bar.SelectedTabId end - local tab_bar_flags = bit32.bor(ImGuiTabBarFlags.Reorderable, ImGuiTabBarFlags.AutoSelectNewTabs) + -- Begin tab bar + local tab_bar_flags = bit32.bor(ImGuiTabBarFlags.Reorderable, ImGuiTabBarFlags.AutoSelectNewTabs) -- | ImGuiTabBarFlags.NoTabListScrollingButtons) tab_bar_flags = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.SaveSettings, ImGuiTabBarFlags.DockNode) - tab_bar_flags = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.FittingPolicyMixed) + tab_bar_flags = bit32.bor(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 = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.DrawSelectedOverline) if not host_window.Collapsed and is_focused then tab_bar_flags = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.IsFocused) end - tab_bar.ID = node.ID - tab_bar.SeparatorMinX = node.Pos.x + host_window.WindowBorderSize + tab_bar.ID = node.ID -- GetID("#TabBar") + tab_bar.SeparatorMinX = node.Pos.x + host_window.WindowBorderSize -- Separator cover the whole node width tab_bar.SeparatorMaxX = node.Pos.x + node.Size.x - host_window.WindowBorderSize ImGui.BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags) + -- host_window.DrawList:AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255)) + -- Backup style colors local backup_style_cols = {} for color_n = 0, ImGuiWindowDockStyleCol.COUNT - 1 do local c = g.Style.Colors[GWindowDockStyleColors[color_n]] backup_style_cols[color_n] = ImVec4(c.x, c.y, c.z, c.w) end + -- Submit actual tabs node.VisibleWindow = nil for window_n = 1, node.Windows.Size do local window = node.Windows.Data[window_n] + -- FIXME: Not sure if that's still taken/useful, as windows are normally removed in DockNodeUpdateFlagsAndCollapse(). if not (window.LastFrameActive + 1 < g.FrameCount and node_was_active) then local tab_item_flags = 0 tab_item_flags = bit32.bor(tab_item_flags, window.WindowClass.TabItemFlagsOverrideSet or 0) @@ -1958,33 +2809,42 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) tab_item_flags = bit32.bor(tab_item_flags, ImGuiTabItemFlags.NoCloseWithMiddleMouseButton) end + -- Apply stored style overrides for the window for color_n = 0, ImGuiWindowDockStyleCol.COUNT - 1 do ImVec4_Copy(g.Style.Colors[GWindowDockStyleColors[color_n]], ImGui.ColorConvertU32ToFloat4(window.DockStyle.Colors[color_n])) end + -- Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so) local _, tab_open = ImGui.TabItemEx(tab_bar, window.Name, window.HasCloseButton and true or nil, tab_item_flags, window) if tab_open == false then node.WantCloseTabId = window.TabId end if tab_bar.VisibleTabId == window.TabId then node.VisibleWindow = window end + -- 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 = ImRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max) + -- Update navigation ID on menu layer if g.NavWindow and g.NavWindow.RootWindow == window and bit32.band(window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) == 0 then host_window.NavLastIds[1] = window.TabId end end end + -- Restore style colors for color_n = 0, ImGuiWindowDockStyleCol.COUNT - 1 do ImVec4_Copy(g.Style.Colors[GWindowDockStyleColors[color_n]], backup_style_cols[color_n]) end + -- Notify root of visible window (used to display title in OS task bar) if node.VisibleWindow then if is_focused or root_node.VisibleWindow == nil then root_node.VisibleWindow = node.VisibleWindow end end + -- Close button (after VisibleWindow was updated) + -- Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow.TabId may be ~= from tab_bar.SelectedTabId local close_button_is_enabled = node.HasCloseButton and node.VisibleWindow and node.VisibleWindow.HasCloseButton local close_button_is_visible = node.HasCloseButton + -- local close_button_is_visible = close_button_is_enabled -- Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one) if close_button_is_visible then if not close_button_is_enabled then ImGui.PushItemFlag(ImGuiItemFlags.Disabled, true) @@ -1995,39 +2855,55 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) node.WantCloseAll = true for n = 1, tab_bar.Tabs.Size do ImGui.TabBarCloseTab(tab_bar, tab_bar.Tabs.Data[n]) end end + -- if IsItemActive() then + -- focus_tab_id = tab_bar.SelectedTabId if not close_button_is_enabled then ImGui.PopStyleColor() ImGui.PopItemFlag() end end + -- When clicking on the title bar outside of tabs, we still focus the selected tab for that node + -- FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them. local title_bar_id = host_window:GetID("#TITLEBAR") if g.HoveredId == 0 or g.HoveredId == title_bar_id or g.ActiveId == title_bar_id then + -- AllowOverlap mode required for appending into dock node tab bar, + -- otherwise dragging window will steal HoveredId and amended tabs cannot get them. ImGui.KeepAliveID(title_bar_id) local _, _, held = ImGui.ButtonBehavior(title_bar_rect, title_bar_id, ImGuiButtonFlags.AllowOverlap) if g.HoveredId == title_bar_id then g.LastItemData.ID = title_bar_id end if held then if ImGui.IsMouseClicked(0) then focus_tab_id = tab_bar.SelectedTabId end + + -- Forward moving request to selected window local tab = ImGui.TabBarFindTabByID(tab_bar, tab_bar.SelectedTabId) if tab then - ImGui.StartMouseMovingWindowOrNode(tab.Window or node.HostWindow, node, false) + ImGui.StartMouseMovingWindowOrNode(tab.Window or node.HostWindow, node, false) -- Undock from tab bar empty space end end end + -- Forward focus from host node to selected window + -- if is_focused and g.NavWindow == host_window and not g.NavWindowingTarget then + -- focus_tab_id = tab_bar.SelectedTabId + + -- When clicked on a tab we requested focus to the docked child + -- This overrides the value set by "forward focus from host node to selected window". if tab_bar.NextSelectedTabId ~= 0 then focus_tab_id = tab_bar.NextSelectedTabId end + -- Apply navigation focus if focus_tab_id ~= 0 then local tab = ImGui.TabBarFindTabByID(tab_bar, focus_tab_id) if tab and tab.Window then ImGui.FocusWindow(tab.Window) - if g.NavId == 0 then ImGui.NavInitWindow(tab.Window, false) end + if g.NavId == 0 then ImGui.NavInitWindow(tab.Window, false) end -- only init if FocusWindow() didn't restore anything. end end ImGui.EndTabBar() ImGui.PopID() + -- Restore SkipItems flag if not node:IsDockSpace() then host_window.DC.NavLayerCurrent = ImGuiNavLayer.Main host_window.SkipItems = backup_skip_item @@ -2043,6 +2919,7 @@ function ImGui.DockNodeRemoveTabBar(node) if node.TabBar == nil then return end node.TabBar = nil end + local function DockNodeIsDropAllowedOne(payload, host_window) if host_window.DockNodeAsHost and host_window.DockNodeAsHost:IsDockSpace() and payload.BeginOrderWithinContext < host_window.BeginOrderWithinContext then return false @@ -2057,10 +2934,15 @@ local function DockNodeIsDropAllowedOne(payload, host_window) if not pass then return false end end + -- Prevent docking any window created above a popup + -- Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features), + -- by e.g. adding a 'if not ImGui.IsWindowWithinBeginStackOf(host_window, popup_window)' test. + -- But it would requires more work on our end because the dock host windows is technically created in NewFrame() + -- and our .ParentXXX and .RootXXX pointers inside windows are currently mislading or lacking. local g = ImGui.GetCurrentContext() for i = g.OpenPopupStack.Size, 1, -1 do local popup_window = g.OpenPopupStack.Data[i].Window - if popup_window and ImGui.IsWindowWithinBeginStackOf(payload, popup_window) then + if popup_window and ImGui.IsWindowWithinBeginStackOf(payload, popup_window) then -- Payload is created from within a popup begin stack. return false end end @@ -2068,7 +2950,7 @@ local function DockNodeIsDropAllowedOne(payload, host_window) end function ImGui.DockNodeIsDropAllowed(host_window, root_payload) - if root_payload.DockNodeAsHost and root_payload.DockNodeAsHost:IsSplitNode() then return true end + if root_payload.DockNodeAsHost and root_payload.DockNodeAsHost:IsSplitNode() then return true end -- FIXME-DOCK: Missing filtering local payload_count = root_payload.DockNodeAsHost and root_payload.DockNodeAsHost.Windows.Size or 1 for payload_n = 1, payload_count do local payload = root_payload.DockNodeAsHost and root_payload.DockNodeAsHost.Windows.Data[payload_n] or root_payload @@ -2077,6 +2959,8 @@ function ImGui.DockNodeIsDropAllowed(host_window, root_payload) return false end +-- window menu button == collapse button when not in a dock node. +-- FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code. --- @return ImRect title_rect, ImRect tab_bar_rect, ImVec2 window_menu_button_pos, ImVec2? close_button_pos function ImGui.DockNodeCalcTabBarLayout(node) local g = ImGui.GetCurrentContext() @@ -2115,6 +2999,7 @@ function ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir, pos_new[o] = pos_old[o] size_new[o] = size_old[o] + -- Distribute size on given axis (with a desired size or equally) local w_avail = size_old[a] - dock_spacing if size_new_desired[a] > 0.0 and size_new_desired[a] <= w_avail * 0.5 then size_new[a] = size_new_desired[a] @@ -2124,6 +3009,7 @@ function ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir, size_old[a] = IM_TRUNC(w_avail - size_new[a]) end + -- Position each node if dir == ImGuiDir.Right or dir == ImGuiDir.Down then pos_new[a] = pos_old[a] + size_old[a] + dock_spacing elseif dir == ImGuiDir.Left or dir == ImGuiDir.Up then @@ -2139,14 +3025,18 @@ local function ImGetDirQuadrantFromDeltaLocal(dx, dy) return (dy > 0.0) and ImGuiDir.Down or ImGuiDir.Up end +-- Retrieve the drop rectangles for a given direction or for the center + perform hit testing. --- @return bool hit, ImRect out_r function ImGui.DockNodeCalcDropRectsAndTestMousePos(parent, dir, outer_docking, test_mouse_pos) local g = ImGui.GetCurrentContext() local parent_smaller_axis = ImMin(parent:GetWidth(), parent:GetHeight()) local hs_for_central_nodes = ImMin(g.FontSize * 1.5, ImMax(g.FontSize * 0.5, parent_smaller_axis / 8.0)) - local hs_w, hs_h, off + local hs_w, hs_h, off -- Half-size, longer axis / Half-size, smaller axis / Distance from edge or center if outer_docking then + -- hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0, g.FontSize * 0.5, g.FontSize * 8.0)) + -- hs_h = ImTrunc(hs_w * 0.15) + -- off = ImVec2(ImTrunc(parent:GetWidth() * 0.5 - GetFrameHeightWithSpacing() * 1.4 - hs_h), ImTrunc(parent:GetHeight() * 0.5 - GetFrameHeightWithSpacing() * 1.4 - hs_h)) hs_w = ImTrunc(hs_for_central_nodes * 1.50) hs_h = ImTrunc(hs_for_central_nodes * 0.80) off = ImVec2(ImTrunc(parent:GetWidth() * 0.5 - hs_h), ImTrunc(parent:GetHeight() * 0.5 - hs_h)) @@ -2169,6 +3059,7 @@ function ImGui.DockNodeCalcDropRectsAndTestMousePos(parent, dir, outer_docking, local hit_r = ImRect(out_r.Min, out_r.Max) if not outer_docking then + -- Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides hit_r:Expand(ImTrunc(hs_w * 0.30)) local mdx, mdy = test_mouse_pos.x - c.x, test_mouse_pos.y - c.y local mouse_delta_len2 = mdx * mdx + mdy * mdy @@ -2184,13 +3075,19 @@ function ImGui.DockNodeCalcDropRectsAndTestMousePos(parent, dir, outer_docking, return hit_r:Contains(test_mouse_pos), out_r end +-- host_node may be nil if the window doesn't have a DockNode already. +-- FIXME-DOCK: This is misnamed since it's also doing the filtering. function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, payload_node, data, is_explicit_target, is_outer_docking) local g = ImGui.GetCurrentContext() + -- There is an edge case when docking into a dockspace which only has inactive nodes. + -- In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive. + -- Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference. if payload_node == nil then payload_node = payload_window.DockNodeAsHost end local ref_node_for_rect = (host_node and not host_node.IsVisible) and ImGui.DockNodeGetRootNode(host_node) or host_node if ref_node_for_rect then IM_ASSERT(ref_node_for_rect.IsVisible == true) end + -- Filter, figure out where we are allowed to dock local src_node_flags = payload_node and payload_node.MergedFlags or payload_window.WindowClass.DockNodeFlagsOverrideSet local dst_node_flags = host_node and host_node.MergedFlags or host_window.WindowClass.DockNodeFlagsOverrideSet data.IsCenterAvailable = true @@ -2202,7 +3099,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, data.IsCenterAvailable = false elseif host_node and bit32.band(dst_node_flags, ImGuiDockNodeFlags.NoDockingOverCentralNode) ~= 0 and host_node:IsCentralNode() then data.IsCenterAvailable = false - elseif (not host_node or not host_node:IsEmpty()) and payload_node and payload_node:IsSplitNode() and (payload_node.OnlyNodeWithWindows == nil) then + elseif (not host_node or not host_node:IsEmpty()) and payload_node and payload_node:IsSplitNode() and (payload_node.OnlyNodeWithWindows == nil) then -- Is _visibly_ split? data.IsCenterAvailable = false elseif bit32.band(src_node_flags, ImGuiDockNodeFlags.NoDockingOverOther) ~= 0 and (not host_node or not host_node:IsEmpty()) then data.IsCenterAvailable = false @@ -2219,6 +3116,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, data.IsSidesAvailable = false end + -- Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split) data.FutureNode.HasCloseButton = (host_node and host_node.HasCloseButton or (not host_node and host_window.HasCloseButton)) or payload_window.HasCloseButton data.FutureNode.HasWindowMenuButton = host_node and true or (bit32.band(host_window.Flags, ImGuiWindowFlags.NoCollapse) == 0) local rp = ref_node_for_rect and ref_node_for_rect.Pos or host_window.Pos @@ -2226,6 +3124,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, data.FutureNode.Pos = ImVec2(rp.x, rp.y) data.FutureNode.Size = ImVec2(rs.x, rs.y) + -- Calculate drop shapes geometry for allowed splitting directions data.SplitNode = host_node data.SplitDir = ImGuiDir.None data.IsSplitDirExplicit = false @@ -2242,11 +3141,13 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, end end + -- When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar data.IsDropAllowed = (data.SplitDir ~= ImGuiDir.None) or data.IsCenterAvailable if not is_explicit_target and not data.IsSplitDirExplicit and not g.IO.ConfigDockingWithShift then data.IsDropAllowed = false end + -- Calculate split area data.SplitRatio = 0.0 if data.SplitDir ~= ImGuiDir.None then local split_dir = data.SplitDir @@ -2255,6 +3156,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, local size_new, size_old = ImVec2(0, 0), ImVec2(data.FutureNode.Size.x, data.FutureNode.Size.y) ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window.Size) + -- Calculate split ratio so we can pass it down the docking request local split_ratio = ImSaturate(size_new[split_axis] / data.FutureNode.Size[split_axis]) data.FutureNode.Pos = pos_new data.FutureNode.Size = size_new @@ -2264,17 +3166,21 @@ end function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, data) local g = ImGui.GetCurrentContext() - IM_ASSERT(g.CurrentWindow == host_window) + IM_ASSERT(g.CurrentWindow == host_window) -- Because we rely on font size to calculate tab sizes + -- With this option, we only display the preview on the target viewport, and the payload viewport is made transparent. + -- To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes. local is_transparent_payload = g.IO.ConfigDockingTransparentPayload local overlay_draw_lists = { ImGui.GetForegroundDrawList(host_window.Viewport) } + -- Draw main preview rectangle local overlay_col_main = ImGui.GetColorU32(ImGuiCol.DockingPreview, is_transparent_payload and 0.60 or 0.40) local overlay_col_drop = ImGui.GetColorU32(ImGuiCol.DockingPreview, is_transparent_payload and 0.90 or 0.70) local overlay_col_drop_hovered = ImGui.GetColorU32(ImGuiCol.DockingPreview, is_transparent_payload and 1.20 or 1.00) local overlay_col_lines = ImGui.GetColorU32(ImGuiCol.NavWindowingHighlight, is_transparent_payload and 0.80 or 0.60) + -- Display area preview local can_preview_tabs = (root_payload.DockNodeAsHost == nil or root_payload.DockNodeAsHost.Windows.Size > 0) if data.IsDropAllowed then local overlay_rect = data.FutureNode:Rect() @@ -2288,27 +3194,32 @@ function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, d end end + -- Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read) if data.IsDropAllowed and can_preview_tabs and data.SplitDir == ImGuiDir.None and data.IsCenterAvailable then + -- Compute target tab bar geometry so we can locate our preview tabs local _, tab_bar_rect = ImGui.DockNodeCalcTabBarLayout(data.FutureNode) local tab_pos = ImVec2(tab_bar_rect.Min.x, tab_bar_rect.Min.y) if host_node and host_node.TabBar then if not host_node:IsHiddenTabBar() and not host_node:IsNoTabBar() then - tab_pos.x = tab_pos.x + host_node.TabBar.WidthAllTabs + g.Style.ItemInnerSpacing.x + tab_pos.x = tab_pos.x + host_node.TabBar.WidthAllTabs + g.Style.ItemInnerSpacing.x -- We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission. else tab_pos.x = tab_pos.x + g.Style.ItemInnerSpacing.x + ImGui.TabItemCalcSize(host_node.Windows.Data[1]).x end elseif bit32.band(host_window.Flags, ImGuiWindowFlags.DockNodeHost) == 0 then - tab_pos.x = tab_pos.x + g.Style.ItemInnerSpacing.x + ImGui.TabItemCalcSize(host_window).x + tab_pos.x = tab_pos.x + g.Style.ItemInnerSpacing.x + ImGui.TabItemCalcSize(host_window).x -- Account for slight offset which will be added when changing from title bar to tab bar end + -- Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows) if root_payload.DockNodeAsHost then IM_ASSERT(root_payload.DockNodeAsHost.Windows.Size <= root_payload.DockNodeAsHost.TabBar.Tabs.Size) end local tab_bar_with_payload = root_payload.DockNodeAsHost and root_payload.DockNodeAsHost.TabBar or nil local payload_count = tab_bar_with_payload and tab_bar_with_payload.Tabs.Size or 1 for payload_n = 1, payload_count do + -- DockNode's TabBar may have non-window Tabs manually appended by user local payload_window = tab_bar_with_payload and tab_bar_with_payload.Tabs.Data[payload_n].Window or root_payload if not (tab_bar_with_payload and payload_window == nil) and DockNodeIsDropAllowedOne(payload_window, host_window) then + -- Calculate the tab bounding box for each payload window local tab_size = ImGui.TabItemCalcSize(payload_window) local tab_bb = ImRect(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y) tab_pos.x = tab_pos.x + tab_size.x + g.Style.ItemInnerSpacing.x @@ -2330,7 +3241,8 @@ function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, d end end - local scale = g.Style._MainScale or 1.0 + -- Display drop boxes + local scale = g.Style._MainScale or 1.0 -- FIXME-DPI local overlay_rounding = ImMax(math.floor(3.0 * scale), g.Style.FrameRounding) for dir = ImGuiDir.None, ImGuiDir.COUNT - 1 do local draw_r = data.DropRectsDraw[dir + 1] @@ -2352,15 +3264,25 @@ function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, d end end end + + -- Stop after ImGuiDir.None if (host_node and bit32.band(host_node.MergedFlags, ImGuiDockNodeFlags.NoDockingSplit) ~= 0) or g.IO.ConfigDockingNoSplit then return end end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: ImGuiDockNode Tree manipulation functions ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockNodeTreeSplit() +-- - DockNodeTreeMerge() +-- - DockNodeTreeUpdatePosSize() +-- - DockNodeTreeUpdateSplitterFindTouchingNode() +-- - DockNodeTreeUpdateSplitter() +-- - DockNodeTreeFindFallbackLeafNode() +-- - DockNodeTreeFindNodeByPos() +------------------------------------------------------------------------------- function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_child_idx, split_ratio, new_node) local g = ImGui.GetCurrentContext() @@ -2385,7 +3307,7 @@ function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_c local a = split_axis local size_avail = parent_node.Size[a] - g.Style.DockingSeparatorSize size_avail = ImMax(size_avail, g.Style.WindowMinSize[a] * 2.0) - IM_ASSERT(size_avail > 0.0) + IM_ASSERT(size_avail > 0.0) -- If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting. child_0.SizeRef = ImVec2(parent_node.Size.x, parent_node.Size.y) child_1.SizeRef = ImVec2(parent_node.Size.x, parent_node.Size.y) child_0.SizeRef[a] = ImTrunc(size_avail * split_ratio) @@ -2396,6 +3318,7 @@ function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_c ImGui.DockNodeUpdateHasCentralNodeChild(ImGui.DockNodeGetRootNode(parent_node)) ImGui.DockNodeTreeUpdatePosSize(parent_node, parent_node.Pos, parent_node.Size) + -- Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags.CentralNode property) child_0.SharedFlags = bit32.band(parent_node.SharedFlags, ImGuiDockNodeFlags.SharedFlagsInheritMask_) child_1.SharedFlags = bit32.band(parent_node.SharedFlags, ImGuiDockNodeFlags.SharedFlagsInheritMask_) child_inheritor.LocalFlags = bit32.band(parent_node.LocalFlags, ImGuiDockNodeFlags.LocalFlagsTransferMask_) @@ -2409,6 +3332,7 @@ function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_c end function ImGui.DockNodeTreeMerge(ctx, parent_node, merge_lead_child) + -- When called from DockContextProcessUndockNode() it is possible that one of the child is nil. local child_0 = parent_node.ChildNodes[0] local child_1 = parent_node.ChildNodes[1] IM_ASSERT(child_0 or child_1) @@ -2421,7 +3345,7 @@ function ImGui.DockNodeTreeMerge(ctx, parent_node, merge_lead_child) local backup_last_explicit_size = ImVec2(parent_node.SizeRef.x, parent_node.SizeRef.y) ImGui.DockNodeMoveChildNodes(parent_node, merge_lead_child) if child_0 then - ImGui.DockNodeMoveWindows(parent_node, child_0) + ImGui.DockNodeMoveWindows(parent_node, child_0) -- Generally only 1 of the 2 child node will have windows DockSettingsRenameNodeReferences(child_0.ID, parent_node.ID) end if child_1 then @@ -2435,18 +3359,23 @@ function ImGui.DockNodeTreeMerge(ctx, parent_node, merge_lead_child) parent_node.VisibleWindow = merge_lead_child.VisibleWindow parent_node.SizeRef = backup_last_explicit_size + -- Flags transfer local M = ImGuiDockNodeFlags.LocalFlagsTransferMask_ - parent_node.LocalFlags = bit32.band(parent_node.LocalFlags, bit32.bnot(M)) + parent_node.LocalFlags = bit32.band(parent_node.LocalFlags, bit32.bnot(M)) -- Preserve Dockspace flag parent_node.LocalFlags = bit32.bor(parent_node.LocalFlags, bit32.band(child_0 and child_0.LocalFlags or 0, M)) parent_node.LocalFlags = bit32.bor(parent_node.LocalFlags, bit32.band(child_1 and child_1.LocalFlags or 0, M)) - parent_node.LocalFlagsInWindows = bit32.bor(child_0 and child_0.LocalFlagsInWindows or 0, child_1 and child_1.LocalFlagsInWindows or 0) + parent_node.LocalFlagsInWindows = bit32.bor(child_0 and child_0.LocalFlagsInWindows or 0, child_1 and child_1.LocalFlagsInWindows or 0) -- FIXME: Would be more consistent to update from actual windows parent_node:UpdateMergedFlags() if child_0 then ImGui.DockContextDeleteNode(ctx, child_0) end if child_1 then ImGui.DockContextDeleteNode(ctx, child_1) end end +-- Update Pos/Size for a node hierarchy (don't affect child Windows yet) +-- (Depth-first, Pre-Order) function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_node) + -- During the regular dock node update we write to all nodes. + -- 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away. local g = ImGui.GetCurrentContext() local write_to_node = only_write_to_single_node == nil or only_write_to_single_node == node if write_to_node then @@ -2471,8 +3400,15 @@ function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_n local a = node.SplitAxis local size_avail = ImMax(size[a] - spacing, 0.0) + -- Size allocation policy + -- 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows. local size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[a] * 2.0) * 0.5) + -- FIXME: Blocks 2) and 3) are essentially doing nearly the same thing. + -- Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc() + -- Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce + + -- 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge) if child_0.WantLockSizeOnce and not child_1.WantLockSizeOnce then child_0_size[a] = ImMin(size_avail - 1.0, child_0.Size[a]); child_0.SizeRef[a] = child_0_size[a] child_1_size[a] = size_avail - child_0_size[a]; child_1.SizeRef[a] = child_1_size[a] @@ -2480,9 +3416,13 @@ function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_n child_1_size[a] = ImMin(size_avail - 1.0, child_1.Size[a]); child_1.SizeRef[a] = child_1_size[a] child_0_size[a] = size_avail - child_1_size[a]; child_0.SizeRef[a] = child_0_size[a] elseif child_0.WantLockSizeOnce and child_1.WantLockSizeOnce then + -- FIXME-DOCK: We cannot honor the requested size, so apply ratio. + -- Currently this path will only be taken if code programmatically sets WantLockSizeOnce local split_ratio = child_0_size[a] / (child_0_size[a] + child_1_size[a]) child_0_size[a] = ImTrunc(size_avail * split_ratio); child_0.SizeRef[a] = child_0_size[a] child_1_size[a] = size_avail - child_0_size[a]; child_1.SizeRef[a] = child_1_size[a] + + -- 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node elseif child_0.SizeRef[a] ~= 0.0 and child_1.HasCentralNodeChild then child_0_size[a] = ImMin(size_avail - size_min_each, child_0.SizeRef[a]) child_1_size[a] = size_avail - child_0_size[a] @@ -2490,6 +3430,7 @@ function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_n child_1_size[a] = ImMin(size_avail - size_min_each, child_1.SizeRef[a]) child_0_size[a] = size_avail - child_1_size[a] else + -- 4) Otherwise distribute according to the relative ratio of each SizeRef value local split_ratio = child_0.SizeRef[a] / (child_0.SizeRef[a] + child_1.SizeRef[a]) child_0_size[a] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5)) child_1_size[a] = size_avail - child_0_size[a] @@ -2525,8 +3466,9 @@ local function DockNodeTreeUpdateSplitterFindTouchingNode(node, axis, side, touc end end -local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 +local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 -- Reduce visual noise by only highlighting the border after a certain time. +-- (Depth-First, Pre-Order) function ImGui.DockNodeTreeUpdateSplitter(node) if node:IsLeafNode() then return end @@ -2535,27 +3477,32 @@ function ImGui.DockNodeTreeUpdateSplitter(node) local child_0 = node.ChildNodes[0] local child_1 = node.ChildNodes[1] if child_0.IsVisible and child_1.IsVisible then + -- Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally) local axis = node.SplitAxis IM_ASSERT(axis ~= ImGuiAxis.None) local a, o = axis, 3 - axis -- the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index local bb = ImRect(ImVec2(child_0.Pos.x, child_0.Pos.y), ImVec2(child_1.Pos.x, child_1.Pos.y)) bb.Min[a] = bb.Min[a] + child_0.Size[a] bb.Max[o] = bb.Max[o] + child_1.Size[o] + -- if g.IO.KeyCtrl then GetForegroundDrawList(g.CurrentWindow.Viewport):AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255)) end - local merged_flags = bit32.bor(child_0.MergedFlags, child_1.MergedFlags) + local merged_flags = bit32.bor(child_0.MergedFlags, child_1.MergedFlags) -- Merged flags for BOTH childs local no_resize_axis_flag = (axis == ImGuiAxis.X) and ImGuiDockNodeFlags.NoResizeX or ImGuiDockNodeFlags.NoResizeY if bit32.band(merged_flags, ImGuiDockNodeFlags.NoResize) ~= 0 or bit32.band(merged_flags, no_resize_axis_flag) ~= 0 then local window = g.CurrentWindow window.DrawList:AddRectFilled(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.Separator), g.Style.FrameRounding) else + -- bb.Min[axis] = bb.Min[axis] + 1 -- Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node. + -- bb.Max[axis] = bb.Max[axis] - 1 ImGui.PushID(node.ID) + -- Find resizing limits by gathering list of nodes that are touching the splitter line. local touching_nodes = { [0] = {}, [1] = {} } local min_size = g.Style.WindowMinSize[a] local resize_limits = { [0] = node.ChildNodes[0].Pos[a] + min_size, [1] = node.ChildNodes[1].Pos[a] + node.ChildNodes[1].Size[a] - min_size } local splitter_id = ImGui.GetID("##Splitter") - if g.ActiveId == splitter_id then + if g.ActiveId == splitter_id then -- Only process when splitter is active DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, touching_nodes[0]) DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, touching_nodes[1]) for _, tn in ipairs(touching_nodes[0]) do @@ -2566,6 +3513,7 @@ function ImGui.DockNodeTreeUpdateSplitter(node) end end + -- Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters local cur_size_0 = child_0.Size[a] local cur_size_1 = child_1.Size[a] local min_size_0 = resize_limits[0] - child_0.Pos[a] @@ -2579,10 +3527,13 @@ function ImGui.DockNodeTreeUpdateSplitter(node) child_1.Pos[a] = child_1.Pos[a] - (cur_size_1 - child_1.Size[a]) child_1.Size[a] = cur_size_1; child_1.SizeRef[a] = cur_size_1 + -- Lock the size of every node that is a sibling of the node we are touching + -- This might be less desirable if we can merge sibling of a same axis into the same parental level. for side_n = 0, 1 do for _, touching_node in ipairs(touching_nodes[side_n]) do while touching_node.ParentNode ~= node do if touching_node.ParentNode.SplitAxis == axis then + -- Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize(). local node_to_preserve = touching_node.ParentNode.ChildNodes[side_n] node_to_preserve.WantLockSizeOnce = true end @@ -2615,6 +3566,7 @@ end function ImGui.DockNodeTreeFindVisibleNodeByPos(node, pos) if not node.IsVisible then return nil end + local r = ImRect(node.Pos, node.Pos + node.Size) if not r:Contains(pos) then return nil end if node:IsLeafNode() then return node end @@ -2622,22 +3574,32 @@ function ImGui.DockNodeTreeFindVisibleNodeByPos(node, pos) if hovered_node then return hovered_node end hovered_node = ImGui.DockNodeTreeFindVisibleNodeByPos(node.ChildNodes[1], pos) if hovered_node then return hovered_node end + + -- This means we are hovering over the splitter/spacing of a parent node return node end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - SetWindowDock() [Internal] +-- - DockSpace() +-- - DockSpaceOverViewport() +------------------------------------------------------------------------------- +-- [Internal] Called via SetNextWindowDockID() function ImGui.SetWindowDock(window, dock_id, cond) + -- Test condition (NB: bit 0 is always true) and clear flags for next time if cond and cond ~= 0 and bit32.band(window.SetWindowDockAllowFlags, cond) == 0 then return end window.SetWindowDockAllowFlags = bit32.band(window.SetWindowDockAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing))) if window.DockId == dock_id then return end + -- If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot local g = ImGui.GetCurrentContext() local new_node = ImGui.DockContextFindNodeByID(g, dock_id) if new_node and new_node:IsSplitNode() then + -- Policy: Find central node or latest focused node. We first move back to our root node. new_node = ImGui.DockNodeGetRootNode(new_node) if new_node.CentralNode then IM_ASSERT(new_node.CentralNode:IsCentralNode()) @@ -2653,6 +3615,10 @@ function ImGui.SetWindowDock(window, dock_id, cond) window.DockId = dock_id end +-- Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default. +-- The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors. +-- DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app. +-- When ImGuiDockNodeFlags.KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location). function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) if size_arg == nil then size_arg = ImVec2(0, 0) end if flags == nil then flags = 0 end @@ -2660,11 +3626,14 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) local window = ImGui.GetCurrentWindowRead() if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then return 0 end + -- Early out if parent window is hidden/collapsed + -- This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960. + -- If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true. if window.SkipItems then flags = bit32.bor(flags, ImGuiDockNodeFlags.KeepAliveOnly) end - if bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 then window = ImGui.GetCurrentWindow() end + if bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 then window = ImGui.GetCurrentWindow() end -- call to set window.WriteAccessed = true; - IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.DockSpace) == 0) - IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.CentralNode) == 0) + IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.DockSpace) == 0) -- Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! + IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.CentralNode) == 0) -- Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! (#8145) IM_ASSERT(dockspace_id ~= 0) local node = ImGui.DockContextFindNodeByID(g, dockspace_id) @@ -2675,6 +3644,8 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) node.SharedFlags = flags node.WindowClass = window_class or ImGuiWindowClass() + -- When a DockSpace transitioned form implicit to explicit this may be called a second time + -- It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again. if node.LastFrameActive == g.FrameCount and bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 then IM_ASSERT(node:IsDockSpace() == false, "Cannot call DockSpace() twice a frame with the same ID") node:SetLocalFlags(bit32.bor(node.LocalFlags, ImGuiDockNodeFlags.DockSpace)) @@ -2682,6 +3653,7 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) end node:SetLocalFlags(bit32.bor(node.LocalFlags, ImGuiDockNodeFlags.DockSpace)) + -- Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible if bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then node.LastFrameAlive = g.FrameCount return dockspace_id @@ -2689,7 +3661,7 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) local content_avail = ImGui.GetContentRegionAvail() local size = ImVec2(ImTrunc(size_arg.x), ImTrunc(size_arg.y)) - if size.x <= 0.0 then size.x = ImMax(content_avail.x + size.x, 4.0) end + if size.x <= 0.0 then size.x = ImMax(content_avail.x + size.x, 4.0) end -- Arbitrary minimum child size (0.0f causing too much issues) if size.y <= 0.0 then size.y = ImMax(content_avail.y + size.y, 4.0) end IM_ASSERT(size.x > 0.0 and size.y > 0.0) @@ -2700,6 +3672,8 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) ImGui.SetNextWindowSize(node.Size) g.NextWindowData.PosUndock = false + -- FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window? + -- FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented) local window_flags = bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.DockNodeHost) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoCollapse, ImGuiWindowFlags.NoTitleBar) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoScrollWithMouse) @@ -2718,29 +3692,41 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) IM_ASSERT(node:IsRootNode()) + -- We need to handle the rare case were a central node is missing. + -- This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags.Dockspace. + -- Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split. + -- It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining. + -- The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property, + -- as it doesn't make sense for an empty dockspace to not have this property. if node:IsLeafNode() and not node:IsCentralNode() then node:SetLocalFlags(bit32.bor(node.LocalFlags, ImGuiDockNodeFlags.CentralNode)) end + -- Update the node ImGui.DockNodeUpdate(node) ImGui.End() local bb = ImRect(node.Pos, node.Pos + size) ImGui.ItemSize(size) - ImGui.ItemAdd(bb, dockspace_id, nil, ImGuiItemFlags.NoNav) - if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) ~= 0 and ImGui.IsWindowChildOf(g.HoveredWindow, host_window, false, true) then + ImGui.ItemAdd(bb, dockspace_id, nil, ImGuiItemFlags.NoNav) -- Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?) + if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) ~= 0 and ImGui.IsWindowChildOf(g.HoveredWindow, host_window, false, true) then -- To fullfill IsItemHovered(), similar to EndChild() g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end return dockspace_id end +-- Tips: Use with ImGuiDockNodeFlags.PassthruCentralNode! +-- The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar(). +-- Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function. +-- If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it. function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, window_class) if dockspace_id == nil then dockspace_id = 0 end if dockspace_flags == nil then dockspace_flags = 0 end if viewport == nil then viewport = ImGui.GetMainViewport() end + -- Submit a window filling the entire viewport ImGui.SetNextWindowPos(viewport.WorkPos) ImGui.SetNextWindowSize(viewport.WorkSize) ImGui.SetNextWindowViewport(viewport.ID) @@ -2751,6 +3737,9 @@ function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, wi if bit32.band(dockspace_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0 then host_window_flags = bit32.bor(host_window_flags, ImGuiWindowFlags.NoBackground) end + + -- 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 bit32.band(dockspace_flags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then host_window_flags = bit32.bor(host_window_flags, ImGuiWindowFlags.NoMouseInputs) end @@ -2763,6 +3752,7 @@ function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, wi ImGui.Begin(label, nil, host_window_flags) ImGui.PopStyleVar(3) + -- Submit the dockspace if dockspace_id == 0 then dockspace_id = ImGui.GetID("DockSpace") end ImGui.DockSpace(dockspace_id, ImVec2(0.0, 0.0), dockspace_flags, window_class) @@ -2771,18 +3761,40 @@ function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, wi return dockspace_id end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Builder Functions ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Very early end-user API to manipulate dock nodes. +-- Only available in imgui_internal.h. Expect this API to change/break! +-- It is expected that those functions are all called _before_ the dockspace node submission. +------------------------------------------------------------------------------- +-- - DockBuilderDockWindow() +-- - DockBuilderGetNode() +-- - DockBuilderSetNodePos() +-- - DockBuilderSetNodeSize() +-- - DockBuilderAddNode() +-- - DockBuilderRemoveNode() +-- - DockBuilderRemoveNodeChildNodes() +-- - DockBuilderRemoveNodeDockedWindows() +-- - DockBuilderSplitNode() +-- - DockBuilderCopyNodeRec() +-- - DockBuilderCopyNode() +-- - DockBuilderCopyWindowSettings() +-- - DockBuilderCopyDockSpace() +-- - DockBuilderFinish() +------------------------------------------------------------------------------- function ImGui.DockBuilderDockWindow(window_name, node_id) + -- We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1) local window_id = ImHashStr(window_name) local window = ImGui.FindWindowByID(window_id) if window then + -- Apply to created window local prev_node_id = window.DockId ImGui.SetWindowDock(window, node_id, ImGuiCond.Always) if window.DockId ~= prev_node_id then window.DockOrder = -1 end else + -- Apply to settings local settings = ImGui.FindWindowSettingsByID(window_id) if settings == nil then settings = ImGui.CreateNewWindowSettings(window_name) end if settings.DockId ~= node_id then settings.DockOrder = -1 end @@ -2816,6 +3828,13 @@ function ImGui.DockBuilderSetNodeSize(node_id, size) node.AuthorityForSize = ImGuiDataAuthority.DockNode end +-- Make sure to use the ImGuiDockNodeFlags.DockSpace flag to create a dockspace node! Otherwise this will create a floating node! +-- - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node. +-- - Dockspace node: calling DockBuilderSetNodePos() is unnecessary. +-- - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand! +-- For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect. +-- - Use (id == 0) to let the system allocate a node identifier. +-- - Existing node with a same id will be removed. function ImGui.DockBuilderAddNode(node_id, flags) if node_id == nil then node_id = 0 end if flags == nil then flags = 0 end @@ -2830,7 +3849,7 @@ function ImGui.DockBuilderAddNode(node_id, flags) node = ImGui.DockContextAddNode(g, node_id) node:SetLocalFlags(flags) end - node.LastFrameAlive = g.FrameCount + node.LastFrameAlive = g.FrameCount -- Set this otherwise BeginDocked will undock during the same frame. return node.ID end @@ -2840,6 +3859,7 @@ function ImGui.DockBuilderRemoveNode(node_id) if node == nil then return end ImGui.DockBuilderRemoveNodeDockedWindows(node_id, true) ImGui.DockBuilderRemoveNodeChildNodes(node_id) + -- Node may have moved or deleted if e.g. any merge happened node = ImGui.DockContextFindNodeByID(g, node_id) if node == nil then return end if node:IsCentralNode() and node.ParentNode then @@ -2848,6 +3868,7 @@ function ImGui.DockBuilderRemoveNode(node_id) ImGui.DockContextRemoveNode(g, node, true) end +-- root_id = 0 to remove all, root_id != 0 to remove child of given node. function ImGui.DockBuilderRemoveNodeChildNodes(root_id) local g = ImGui.GetCurrentContext() local dc = g.DockContext @@ -2859,6 +3880,7 @@ function ImGui.DockBuilderRemoveNodeChildNodes(root_id) local backup_root_node_authority_for_pos = root_node and root_node.AuthorityForPos or ImGuiDataAuthority.Auto local backup_root_node_authority_for_size = root_node and root_node.AuthorityForSize or ImGuiDataAuthority.Auto + -- Process active windows local nodes_to_remove = {} for _, id in ipairs(DockContextNodesSorted(g)) do local node = dc.Nodes[id] @@ -2876,11 +3898,14 @@ function ImGui.DockBuilderRemoveNodeChildNodes(root_id) end end + -- DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge) + -- Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead) if root_node then root_node.AuthorityForPos = backup_root_node_authority_for_pos root_node.AuthorityForSize = backup_root_node_authority_for_size end + -- Apply to settings for _, settings in g.SettingsWindows:iter() do local window_settings_dock_id = settings.DockId if window_settings_dock_id and window_settings_dock_id ~= 0 then @@ -2893,6 +3918,7 @@ function ImGui.DockBuilderRemoveNodeChildNodes(root_id) end end + -- Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes if #nodes_to_remove > 1 then local depth = {} for _, n in ipairs(nodes_to_remove) do depth[n] = ImGui.DockNodeGetDepth(n) end @@ -2913,6 +3939,7 @@ end function ImGui.DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs) if clear_settings_refs == nil then clear_settings_refs = true end + -- Clear references in settings local g = ImGui.GetCurrentContext() if clear_settings_refs then for _, settings in g.SettingsWindows:iter() do @@ -2925,6 +3952,7 @@ function ImGui.DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs) end end + -- Clear references in windows for n = 1, g.Windows.Size do local window = g.Windows.Data[n] local want_removal = (root_id == 0) or (window.DockNode and ImGui.DockNodeGetRootNode(window.DockNode).ID == root_id) or (window.DockNodeAsHost and window.DockNodeAsHost.ID == root_id) @@ -2936,6 +3964,9 @@ function ImGui.DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs) end end +-- Returns (id_at_dir, id_at_opposite_dir): the IDs of the two new nodes created. +-- First return value is ID of the node at the specified direction. +-- FIXME-DOCK: We are not exposing nor using split_outer. --- @return ImGuiID id_at_dir, ImGuiID id_at_opposite_dir function ImGui.DockBuilderSplitNode(id, split_dir, size_ratio_for_node_at_dir) local g = ImGui.GetCurrentContext() @@ -3029,6 +4060,7 @@ function ImGui.DockBuilderCopyWindowSettings(src_name, dst_name) end end +-- FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed. --- @param in_window_remap_pairs table # 1-based array of window names: src0, dst0, src1, dst1, ... function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_window_remap_pairs) IM_ASSERT(src_dockspace_id ~= 0) @@ -3036,9 +4068,14 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w IM_ASSERT(in_window_remap_pairs ~= nil) IM_ASSERT((#in_window_remap_pairs % 2) == 0) + -- Duplicate entire dock + -- FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart, + -- whereas we could attempt to at least keep them together in a new, same floating node. local node_remap_pairs = {} ImGui.DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, node_remap_pairs) + -- Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes + -- (The windows associated to src_dockspace_id are staying in place) local src_windows = {} for remap_window_n = 1, #in_window_remap_pairs, 2 do local src_window_name = in_window_remap_pairs[remap_window_n] @@ -3046,6 +4083,7 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w local src_window_id = ImHashStr(src_window_name) src_windows[src_window_id] = true + -- Search in the remapping tables local src_dock_id = 0 local src_window = ImGui.FindWindowByID(src_window_id) if src_window then @@ -3058,17 +4096,24 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w for dock_remap_n = 1, #node_remap_pairs, 2 do if node_remap_pairs[dock_remap_n] == src_dock_id then dst_dock_id = node_remap_pairs[dock_remap_n + 1] + --node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0 -- Clear break end end if dst_dock_id ~= 0 then + -- Docked windows gets redocked into the new node hierarchy. ImGui.DockBuilderDockWindow(dst_window_name, dst_dock_id) else + -- Floating windows gets their settings transferred (regardless of whether the new window already exist or not) + -- When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together? ImGui.DockBuilderCopyWindowSettings(src_window_name, dst_window_name) end end + -- Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list. + -- Find those windows and move to them to the cloned dock node. This may be optional? + -- Dock those are a second step as undocking would invalidate source dock nodes. local dock_remaining_windows = {} for dock_remap_n = 1, #node_remap_pairs, 2 do local src_dock_id = node_remap_pairs[dock_remap_n] @@ -3077,6 +4122,7 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w local node = ImGui.DockBuilderGetNode(src_dock_id) for _, window in node.Windows:iter() do if not src_windows[window.ID] then + -- Docked windows gets redocked into the new node hierarchy. table.insert(dock_remaining_windows, { Window = window, DockId = dst_dock_id }) end end @@ -3087,19 +4133,27 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w end end +-- FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node. function ImGui.DockBuilderFinish(root_id) + --DockContextRebuild(g) ImGui.DockContextBuildAddWindowsToNodes(ImGui.GetCurrentContext(), root_id) end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Begin/End Support Functions (called from Begin/End) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - GetWindowAlwaysWantOwnTabBar() +-- - DockContextBindNodeToWindow() +-- - BeginDocked() +-- - BeginDockableDragDropSource() +-- - BeginDockableDragDropTarget() +------------------------------------------------------------------------------- function ImGui.GetWindowAlwaysWantOwnTabBar(window) local g = ImGui.GetCurrentContext() if g.IO.ConfigDockingAlwaysTabBar or window.WindowClass.DockingAlwaysTabBar then if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoDocking)) == 0 then - if not window.IsFallbackWindow then return true end + if not window.IsFallbackWindow then return true end -- We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise end end return false @@ -3110,11 +4164,13 @@ function ImGui.DockContextBindNodeToWindow(ctx, window) local node = ImGui.DockContextFindNodeByID(ctx, window.DockId) IM_ASSERT(window.DockNode == nil) + -- We should not be docking into a split node (SetWindowDock should avoid this) if node and node:IsSplitNode() then ImGui.DockContextProcessUndockWindow(ctx, window) return nil end + -- Create node if node == nil then node = ImGui.DockContextAddNode(ctx, window.DockId) node.AuthorityForPos = ImGuiDataAuthority.Window @@ -3123,6 +4179,10 @@ function ImGui.DockContextBindNodeToWindow(ctx, window) node.LastFrameAlive = g.FrameCount end + -- If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, + -- so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node). + -- If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout. + -- This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame. if not node.IsVisible then local ancestor_node = node while not ancestor_node.IsVisible and ancestor_node.ParentNode do @@ -3133,9 +4193,10 @@ function ImGui.DockContextBindNodeToWindow(ctx, window) ImGui.DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node.Pos, ancestor_node.Size, node) end + -- Add window to node local node_was_visible = node.IsVisible ImGui.DockNodeAddWindow(node, window, true) - node.IsVisible = node_was_visible + node.IsVisible = node_was_visible -- Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see) IM_ASSERT(node == window.DockNode) return node end @@ -3152,6 +4213,7 @@ ImGui.StoreDockStyleForWindow = StoreDockStyleForWindow function ImGui.BeginDocked(window, p_open) local g = ImGui.GetCurrentContext() + -- Specific extra processing for fallback window (#9151), could be in Begin() as well. if window.IsFallbackWindow and not window.WasActive then DockNodeHideWindowDuringHostWindowCreation(window) return p_open @@ -3164,6 +4226,7 @@ function ImGui.BeginDocked(window, p_open) window.DockId = ImGui.DockContextGenNodeID(g) end else + -- Calling SetNextWindowPos() undock windows by default (by setting PosUndock) local want_undock = false want_undock = want_undock or bit32.band(window.Flags, ImGuiWindowFlags.NoDocking) ~= 0 want_undock = want_undock or (bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) ~= 0 and bit32.band(window.SetWindowPosAllowFlags, g.NextWindowData.PosCond) ~= 0 and g.NextWindowData.PosUndock) @@ -3173,6 +4236,7 @@ function ImGui.BeginDocked(window, p_open) end end + -- Bind to our dock node local node = window.DockNode if node ~= nil then IM_ASSERT(window.DockId == node.ID) end if window.DockId ~= 0 and node == nil then @@ -3180,7 +4244,10 @@ function ImGui.BeginDocked(window, p_open) if node == nil then return p_open end end + -- Undock if our dockspace node disappeared + -- Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags.KeepAliveOnly. if node.LastFrameAlive < g.FrameCount then + -- If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking() local root_node = ImGui.DockNodeGetRootNode(node) if root_node.LastFrameAlive < g.FrameCount then ImGui.DockContextProcessUndockWindow(g, window) @@ -3190,47 +4257,58 @@ function ImGui.BeginDocked(window, p_open) return p_open end + -- Store style overrides StoreDockStyleForWindow(window) + -- Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window, + -- and never create neither a host window neither a tab bar. + -- FIXME-DOCK: replace .HostWindow nil compare with something more explicit (~was initially intended as a first frame test) if node.HostWindow == nil then if node.State == ImGuiDockNodeState.HostWindowHiddenBecauseWindowsAreResizing then window.DockIsActive = true end - if node.Windows.Size > 1 and window.Appearing then + if node.Windows.Size > 1 and window.Appearing then -- Only hide appearing window DockNodeHideWindowDuringHostWindowCreation(window) end return p_open end + -- We can have zero-sized nodes (e.g. children of a small-size dockspace) IM_ASSERT(node.HostWindow) IM_ASSERT(node:IsLeafNode()) IM_ASSERT(node.Size.x >= 0.0 and node.Size.y >= 0.0) node.State = ImGuiDockNodeState.HostWindowVisible + -- Undock if we are submitted earlier than the host window if bit32.band(node.MergedFlags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 and window.BeginOrderWithinContext < node.HostWindow.BeginOrderWithinContext then ImGui.DockContextProcessUndockWindow(g, window) return p_open end + -- Position/Size window ImGui.SetNextWindowPos(node.Pos) ImGui.SetNextWindowSize(node.Size) - g.NextWindowData.PosUndock = false + g.NextWindowData.PosUndock = false -- Cancel implicit undocking of SetNextWindowPos() window.DockIsActive = true window.DockNodeIsVisible = true window.DockTabIsVisible = false if bit32.band(node.MergedFlags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then return p_open end + -- When the window is selected we mark it as visible. if node.VisibleWindow == window then window.DockTabIsVisible = true end + -- Update window flag IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0) window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.NoResize) window.ChildFlags = bit32.bor(window.ChildFlags, ImGuiChildFlags.AlwaysUseWindowPadding) if node:IsHiddenTabBar() or node:IsNoTabBar() then window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.NoTitleBar) else - window.Flags = bit32.band(window.Flags, bit32.bnot(ImGuiWindowFlags.NoTitleBar)) + window.Flags = bit32.band(window.Flags, bit32.bnot(ImGuiWindowFlags.NoTitleBar)) -- Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed! end + -- Save new dock order only if the window has been visible once already + -- This allows multiple windows to be created in the same frame and have their respective dock orders preserved. if node.TabBar and window.WasActive then window.DockOrder = ImGui.DockNodeGetTabOrder(window) end @@ -3239,6 +4317,7 @@ function ImGui.BeginDocked(window, p_open) p_open = false end + -- Update ChildId to allow returning from Child to Parent with Escape local parent_window = window.DockNode.HostWindow window.ChildId = parent_window:GetID(window.Name) return p_open @@ -3250,7 +4329,11 @@ function ImGui.BeginDockableDragDropSource(window) IM_ASSERT(g.MovingWindow == window) IM_ASSERT(g.CurrentWindow == window) + -- 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking. if g.IO.ConfigDockingWithShift ~= g.IO.KeyShift then + -- When ConfigDockingWithShift is set, display a tooltip to increase UI affordance. + -- We cannot set for HoveredWindowUnderMovingWindow ~= nil 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) if g.IO.ConfigDockingWithShift and g.MouseStationaryTimer >= 1.0 and g.ActiveId >= 1 then ImGui.SetTooltip("%s", ImGui.LocalizeGetMsg(ImGuiLocKey.DockingHoldShiftToDock)) end @@ -3260,21 +4343,26 @@ function ImGui.BeginDockableDragDropSource(window) g.LastItemData.ID = window.MoveId window = window.RootWindowDockTree IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.NoDocking) == 0) - local is_drag_docking = g.IO.ConfigDockingWithShift or ImRect(0, 0, window.SizeFull.x, ImGui.GetFrameHeight()):Contains(g.ActiveIdClickOffset) + local is_drag_docking = g.IO.ConfigDockingWithShift or ImRect(0, 0, window.SizeFull.x, ImGui.GetFrameHeight()):Contains(g.ActiveIdClickOffset) -- FIXME-DOCKING: Need to make this stateful and explicit local drag_drop_flags = bit32.bor(ImGuiDragDropFlags.SourceNoPreviewTooltip, ImGuiDragDropFlags.SourceNoHoldToOpenOthers, ImGuiDragDropFlags.PayloadAutoExpire, ImGuiDragDropFlags.PayloadNoCrossContext, ImGuiDragDropFlags.PayloadNoCrossProcess) if is_drag_docking and ImGui.BeginDragDropSource(drag_drop_flags) then ImGui.SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, window) ImGui.EndDragDropSource() - StoreDockStyleForWindow(window) + StoreDockStyleForWindow(window) -- Store style overrides while dragging (even when not docked) because docking preview may need it. end end function ImGui.BeginDockableDragDropTarget(window) local g = ImGui.GetCurrentContext() + + --IM_ASSERT(window.RootWindowDockTree == window) -- May also be a DockSpace IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.NoDocking) == 0) if not g.DragDropActive then return end + --GetForegroundDrawList(window):AddRect(window.Pos, window.Pos + window.Size, IM_COL32(255, 255, 0, 255)) if not ImGui.BeginDragDropTargetCustom(window:Rect(), window.ID) then return end + -- Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering + -- (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly) local payload = g.DragDropPayload if not ImGuiPayload_IsDataType(payload, IMGUI_PAYLOAD_TYPE_WINDOW) or not ImGui.DockNodeIsDropAllowed(window, payload.Data) then ImGui.EndDragDropTarget() @@ -3283,10 +4371,17 @@ function ImGui.BeginDockableDragDropTarget(window) local payload_window = payload.Data if ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, bit32.bor(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoDrawDefaultRect)) then + -- Select target node + -- (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation) local dock_into_floating_window = false local node = nil if window.DockNodeAsHost then + -- Cannot assume that node will ~= nil even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos(). node = ImGui.DockNodeTreeFindVisibleNodeByPos(window.DockNodeAsHost, g.IO.MousePos) + + -- There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active) + -- In this case we need to fallback into any leaf mode, possibly the central node. + -- FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. if node and node:IsDockSpace() and node:IsRootNode() then node = (node.CentralNode and node:IsLeafNode()) and node.CentralNode or ImGui.DockNodeTreeFindFallbackLeafNode(node) end @@ -3294,7 +4389,7 @@ function ImGui.BeginDockableDragDropTarget(window) if window.DockNode then node = window.DockNode else - dock_into_floating_window = true + dock_into_floating_window = true -- Dock into a regular window end end @@ -3306,8 +4401,11 @@ function ImGui.BeginDockableDragDropTarget(window) end local is_explicit_target = g.IO.ConfigDockingWithShift or ImGui.IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max) + -- Preview docking request and find out split direction/ratio + --local do_preview = true -- Ignore testing for payload:IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window. local do_preview = ImGuiPayload_IsPreview(payload) or ImGuiPayload_IsDelivery(payload) if do_preview and (node ~= nil or dock_into_floating_window) then + -- If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear. local split_inner = ImGuiDockPreviewData() local split_outer = ImGuiDockPreviewData() local split_data = split_inner @@ -3323,9 +4421,11 @@ function ImGui.BeginDockableDragDropTarget(window) end if split_data == split_outer then split_inner.IsDropAllowed = false end + -- Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes ImGui.DockNodePreviewDockRender(window, node, payload_window, split_inner) ImGui.DockNodePreviewDockRender(window, node, payload_window, split_outer) + -- Queue docking request if split_data.IsDropAllowed and ImGuiPayload_IsDelivery(payload) then ImGui.DockContextQueueDock(g, window, split_data.SplitNode, payload_window, split_data.SplitDir, split_data.SplitRatio, split_data == split_outer) end @@ -3334,24 +4434,36 @@ function ImGui.BeginDockableDragDropTarget(window) ImGui.EndDragDropTarget() end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Settings ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockSettingsRenameNodeReferences() +-- - DockSettingsRemoveNodeReferences() +-- - DockSettingsFindNodeSettings() +-- - DockSettingsHandler_ApplyAll() +-- - DockSettingsHandler_ReadOpen() +-- - DockSettingsHandler_ReadLine() +-- - DockSettingsHandler_DockNodeToSettings() +-- - DockSettingsHandler_WriteAll() +------------------------------------------------------------------------------- DockSettingsRenameNodeReferences = function(old_node_id, new_node_id) local g = ImGui.GetCurrentContext() for _, window in g.Windows:iter() do if window.DockId == old_node_id and window.DockNode == nil then window.DockId = new_node_id end end + ---- FIXME-OPT: We could remove this loop by storing the index in the map for _, settings in g.SettingsWindows:iter() do if settings.DockId == old_node_id then settings.DockId = new_node_id end end end +-- Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings --- @param node_ids table # 1-based array DockSettingsRemoveNodeReferences = function(node_ids, node_ids_count) local g = ImGui.GetCurrentContext() local found = 0 + ---- FIXME-OPT: We could remove this loop by storing the index in the map for _, settings in g.SettingsWindows:iter() do for node_n = 1, node_ids_count do if settings.DockId == node_ids[node_n] then @@ -3366,19 +4478,23 @@ DockSettingsRemoveNodeReferences = function(node_ids, node_ids_count) end DockSettingsFindNodeSettings = function(ctx, id) + -- FIXME-OPT for _, s in ctx.DockContext.NodesSettings:iter() do if s.ID == id then return s end end return nil end +-- Clear settings data DockSettingsHandler_ClearAll = function(ctx, handler) local dc = ctx.DockContext dc.NodesSettings:clear() ImGui.DockContextClearNodes(ctx, 0, true) end +-- Recreate nodes based on settings data DockSettingsHandler_ApplyAll = function(ctx, handler) + -- Prune settings at boot time only local dc = ctx.DockContext if ctx.Windows.Size == 0 then ImGui.DockContextPruneUnusedSettingsNodes(ctx) end ImGui.DockContextBuildNodesFromSettings(ctx, dc.NodesSettings.Data or {}, dc.NodesSettings.Size) @@ -3391,6 +4507,10 @@ DockSettingsHandler_ReadOpen = function(ctx, handler, name) end DockSettingsHandler_ReadLine = function(ctx, handler, entry, line) + -- Parsing, e.g. + -- " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 " + -- " DockNode ID=0x00000002 Parent=0x00000001 " + -- Important: this code expect currently fields in a fixed order. local node = ImGuiDockNodeSettings() line = line:gsub("^[ \t]+", "") if line:sub(1, 8) == "DockNode" then @@ -3472,6 +4592,8 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) local dc = ctx.DockContext if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then return end + -- Gather settings data + -- (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer) dc.NodesSettings:resize(0) for _, id in ipairs(DockContextNodesSorted(ctx)) do local node = dc.Nodes[id] @@ -3483,9 +4605,10 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) local max_depth = 0 for _, s in dc.NodesSettings:iter() do max_depth = ImMax(s.Depth, max_depth) end + -- Write to text buffer buf:appendf("[%s][Data]\n", handler.TypeName) for _, s in dc.NodesSettings:iter() do - buf:append(string.rep(" ", s.Depth * 2) .. ((bit32.band(s.Flags, ImGuiDockNodeFlags.DockSpace) ~= 0) and "DockSpace" or "DockNode ") .. string.rep(" ", (max_depth - s.Depth) * 2)) + buf:append(string.rep(" ", s.Depth * 2) .. ((bit32.band(s.Flags, ImGuiDockNodeFlags.DockSpace) ~= 0) and "DockSpace" or "DockNode ") .. string.rep(" ", (max_depth - s.Depth) * 2)) -- Text align nodes to facilitate looking at .ini file buf:appendf(" ID=0x%08X", s.ID) if s.ParentNodeId ~= 0 then buf:appendf(" Parent=0x%08X SizeRef=%d,%d", s.ParentNodeId, s.SizeRef.x, s.SizeRef.y) @@ -3506,9 +4629,9 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) buf:append("\n") end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: helpers (imgui_internal.h inlines) + widgets used by docking ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.DockNodeGetRootNode(node) while node.ParentNode do node = node.ParentNode end @@ -3548,10 +4671,14 @@ function ImGui.SetNextWindowDockID(id, cond) g.NextWindowData.DockId = id end +-- We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them. function ImGui.StartMouseMovingWindowOrNode(window, node, undock) local g = ImGui.GetCurrentContext() local can_undock_node = false if undock and node ~= nil and node.VisibleWindow and bit32.band(node.VisibleWindow.Flags, ImGuiWindowFlags.NoMove) == 0 and bit32.band(node.MergedFlags, ImGuiDockNodeFlags.NoUndocking) == 0 then + -- 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. Undocking from a fixed/central node will create a new node and copy windows. local root_node = ImGui.DockNodeGetRootNode(node) if root_node.OnlyNodeWithWindows ~= node or root_node.CentralNode ~= nil then can_undock_node = true @@ -3561,18 +4688,21 @@ function ImGui.StartMouseMovingWindowOrNode(window, node, undock) local clicked = ImGui.IsMouseClicked(0) local dragging = ImGui.IsMouseDragging(0) if can_undock_node and dragging then - ImGui.DockContextQueueUndockNode(g, node) + ImGui.DockContextQueueUndockNode(g, node) -- Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame elseif not can_undock_node and (clicked or dragging) and g.MovingWindow ~= window then ImGui.StartMouseMovingWindow(window) end end +-- This is less wide than RenderArrow() and we use in dock nodes instead of the regular RenderArrow() to denote a change of functionality, +-- and because the saved space means that the left-most tab label can stay at exactly the same position as the label of a loose window. function ImGui.RenderArrowDockMenu(draw_list, p_min, sz, col) draw_list:AddRectFilled(p_min + ImVec2(sz * 0.20, sz * 0.15), p_min + ImVec2(sz * 0.80, sz * 0.30), col) ImGui.RenderArrowPointingAt(draw_list, p_min + ImVec2(sz * 0.50, sz * 0.85), ImVec2(sz * 0.30, sz * 0.40), ImGuiDir.Down, col) end -- Upstream CollapseButton (docking branch): replaces the port's simpler version +-- The Collapse button also functions as a Dock Menu button. function ImGui.CollapseButton(id, pos, dock_node) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow @@ -3582,6 +4712,8 @@ function ImGui.CollapseButton(id, pos, dock_node) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, ImGuiButtonFlags.None) if is_clipped then return pressed end + -- Render + --local is_dock_menu = (window.DockNodeAsHost and not window.Collapsed) local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.ButtonActive or (hovered and ImGuiCol.ButtonHovered or ImGuiCol.Button)) local text_col = ImGui.GetColorU32(ImGuiCol.Text) if hovered or held then @@ -3595,13 +4727,15 @@ function ImGui.CollapseButton(id, pos, dock_node) ImGui.RenderArrow(window.DrawList, bb.Min, text_col, window.Collapsed and ImGuiDir.Right or ImGuiDir.Down, 1.0) end + -- Switch to moving the window after mouse is moved beyond the initial drag threshold if ImGui.IsItemActive() and ImGui.IsMouseDragging(0) then - ImGui.StartMouseMovingWindowOrNode(window, dock_node, true) + ImGui.StartMouseMovingWindowOrNode(window, dock_node, true) -- Undock from window/collapse menu button end return pressed end +-- Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise. --- @return bool held, float size1, float size2 function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2, hover_extend, hover_visibility_delay, bg_col) hover_extend = hover_extend or 0.0 @@ -3612,13 +4746,16 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 if not ImGui.ItemAdd(bb, id, nil, ImGuiItemFlags.NoNav) then return false, size1, size2 end + -- FIXME: AFAIK the only leftover reason for passing ImGuiButtonFlags.AllowOverlap here is + -- to allow caller of SplitterBehavior() to call SetItemAllowOverlap() after the item. + -- Nowadays we would instead want to use SetNextItemAllowOverlap() before the item. local button_flags = bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.AllowOverlap) local bb_interact = ImRect(bb.Min, bb.Max) bb_interact:Expand(axis == ImGuiAxis.Y and ImVec2(0.0, hover_extend) or ImVec2(hover_extend, 0.0)) local _, hovered, held = ImGui.ButtonBehavior(bb_interact, id, button_flags) if hovered then - g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) + g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) -- for IsItemHovered(), because bb_interact is larger than bb end if held or (hovered and g.HoveredIdPreviousFrame == id and g.HoveredIdTimer >= hover_visibility_delay) then @@ -3630,11 +4767,13 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 local d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min local mouse_delta = d[axis] + -- Minimum pane size local size_1_maximum_delta = ImMax(0.0, size1 - min_size1) local size_2_maximum_delta = ImMax(0.0, size2 - min_size2) if mouse_delta < -size_1_maximum_delta then mouse_delta = -size_1_maximum_delta end if mouse_delta > size_2_maximum_delta then mouse_delta = size_2_maximum_delta end + -- Apply resize if mouse_delta ~= 0.0 then size1 = ImMax(size1 + mouse_delta, min_size1) size2 = ImMax(size2 - mouse_delta, min_size2) @@ -3643,6 +4782,7 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 end end + -- Render at new position if bit32.band(bg_col, IM_COL32_A_MASK) ~= 0 then window.DrawList:AddRectFilled(bb_render.Min, bb_render.Max, bg_col, 0.0) end @@ -3653,19 +4793,22 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 end end --[[ [SECTION] imgui_docking (was imgui_docking.lua) ]] -local IMGUI_DEBUG_NAV_SCORING = false -local IMGUI_DEBUG_NAV_RECTS = false +-- Debug options +local IMGUI_DEBUG_NAV_SCORING = false -- Display navigation scoring preview when hovering items. Hold Ctrl to display for all candidates. Ctrl+Arrow to change last direction. +local IMGUI_DEBUG_NAV_RECTS = false -- Display the reference navigation rectangle for each window +-- Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls. local FONT_DEFAULT_SIZE_BASE = 20 -local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 -local WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70 +local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 -- Reduce visual noise by only highlighting the border after a certain time. +local WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70 -- Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved. +-- Tooltip offset local TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10) -- Multiplied by g.Style.MouseCursorScale local TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20) -- Multiplied by g.Style.MouseCursorScale local TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5, 1.0) -- Multiplied by g.Style.MouseCursorScale -local IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111 +local 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. local string = string ImFormatString = string.format -- TODO: an simplified version that operates on byte tables directly? @@ -3676,9 +4819,9 @@ ImStd.sscanf = IM_INCLUDE"imstd_minstdio.lua" local math = math local bit32 = bit32 ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] MISC HELPERS/UTILITIES (File functions) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- This closes the _file. --- @param _file any # File object @@ -3714,6 +4857,7 @@ if gmod then IM_FILE_READ = FindMetaTable("File").Read --- @type function end +-- Default file functions if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then --- [GMod] Another Platform specific if gmod then @@ -3743,6 +4887,8 @@ if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then end end + -- Helper: Load file content into memory + -- This can't really be used with "rt" because fseek size won't match read size. --- @param filename string --- @param mode string --- @return table?, integer? @@ -3774,6 +4920,9 @@ local CalcNextScrollFromScrollTargetAndClamp local MT = ImGui.GetMetatables() +-- Scale all spacing/padding/thickness values. Do not scale fonts. +-- Consider not calling this if your initial scale factor if <1.0. +-- 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. --- @param scale_factor float function MT.ImGuiStyle:ScaleAllSizes(scale_factor) self._MainScale = self._MainScale * scale_factor @@ -3830,17 +4979,20 @@ function MT.ImGuiStyle:ScaleAllSizes(scale_factor) self.MouseCursorScale = ImTrunc(self.MouseCursorScale * scale_factor) end +-- Data for resizing from resize grip / corner local ImGuiResizeGripDef = { - {CornerPosN = ImVec2(1, 1), InnerDir = ImVec2(-1, -1), AngleMin12 = 0, AngleMax12 = 3}, -- Bottom right grip - {CornerPosN = ImVec2(0, 1), InnerDir = ImVec2( 1, -1), AngleMin12 = 3, AngleMax12 = 6} -- Bottom left + {CornerPosN = ImVec2(1, 1), InnerDir = ImVec2(-1, -1), AngleMin12 = 0, AngleMax12 = 3}, -- Lower-right + {CornerPosN = ImVec2(0, 1), InnerDir = ImVec2( 1, -1), AngleMin12 = 3, AngleMax12 = 6} -- Lower-left } +-- Data for resizing from borders +-- InnerDir: Normal toward inside, SegmentN1/SegmentN2: End positions, normalized (0,0: upper left), OuterAngle: Angle toward outside --- [1] Left, [2] Right, [3] Up, [4] Down local ImGuiResizeBorderDef = { - {InnerDir = ImVec2( 1, 0), SegmentN1 = ImVec2( 0, 1), SegmentN2 = ImVec2( 0, 0), OuterAngle = IM_PI * 1.00}, - {InnerDir = ImVec2(-1, 0), SegmentN1 = ImVec2( 1, 0), SegmentN2 = ImVec2( 1, 1), OuterAngle = IM_PI * 0.00}, - {InnerDir = ImVec2( 0, 1), SegmentN1 = ImVec2( 0, 0), SegmentN2 = ImVec2( 1, 0), OuterAngle = IM_PI * 1.50}, - {InnerDir = ImVec2( 0, -1), SegmentN1 = ImVec2( 1, 1), SegmentN2 = ImVec2( 0, 1), OuterAngle = IM_PI * 0.50} + {InnerDir = ImVec2( 1, 0), SegmentN1 = ImVec2( 0, 1), SegmentN2 = ImVec2( 0, 0), OuterAngle = IM_PI * 1.00}, -- Left + {InnerDir = ImVec2(-1, 0), SegmentN1 = ImVec2( 1, 0), SegmentN2 = ImVec2( 1, 1), OuterAngle = IM_PI * 0.00}, -- Right + {InnerDir = ImVec2( 0, 1), SegmentN1 = ImVec2( 0, 0), SegmentN2 = ImVec2( 1, 0), OuterAngle = IM_PI * 1.50}, -- Up + {InnerDir = ImVec2( 0, -1), SegmentN1 = ImVec2( 1, 1), SegmentN2 = ImVec2( 0, 1), OuterAngle = IM_PI * 0.50} -- Down } --- @param window ImGuiWindow @@ -3870,6 +5022,8 @@ local function GetResizeBorderRect(window, border_n, perp_padding, thickness) return ImRect() end +-- Known size hash +-- It is ok to call ImHashData on a string with known length but the ### operator won't be supported. --- @param data table|number --- @param size int? # size = -1 to indicate that `data` is a single number --- @param seed int? @@ -3896,6 +5050,8 @@ function ImHashData(data, size, seed) return hash end +-- Zero-terminated string hash, with support for ### to reset back to seed value. +-- e.g. "label###id" outputs the same hash as "id" (and "label" is generally displayed by the UI functions) -- Use FNV1a, as one ImGui FIXME suggested --- @param str string --- @param size int? @@ -3965,6 +5121,9 @@ local shifte = {0, 6, 4, 2, 0} local s = {0, 0, 0, 0} +-- Convert UTF-8 to 32-bit character, process single character input. +-- A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8). +-- We handle UTF-8 decoding error by skipping forward. --- @param in_text ImString --- @param pos int --- @param in_text_end int @@ -3974,15 +5133,19 @@ function ImStd.ImTextCharFromUtf8(in_text, pos, in_text_end) local len = lengths[bit32.rshift(ImStrByte(in_text, pos), 3) + 1] local wanted = len > 0 and len or 1 + -- IMPORTANT: if in_text_end == nil it assume we have enough space! if in_text_end == nil then - in_text_end = pos + wanted + in_text_end = pos + wanted -- Max length, nulls will be taken into account. end + -- Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here, + -- so it is fast even with excessive branching. s[1] = (pos < in_text_end) and ImStrByte(in_text, pos) or 0 s[2] = (pos + 1 < in_text_end) and ImStrByte(in_text, pos + 1) or 0 s[3] = (pos + 2 < in_text_end) and ImStrByte(in_text, pos + 2) or 0 s[4] = (pos + 3 < in_text_end) and ImStrByte(in_text, pos + 3) or 0 + -- Assume a four-byte character and load four bytes. Unused bits are shifted out. local out_char out_char = bit32.lshift(bit32.band(s[1], masks[len + 1]), 18) out_char = bit32.bor(out_char, bit32.lshift(bit32.band(s[2], 0x3f), 12)) @@ -3990,17 +5153,22 @@ function ImStd.ImTextCharFromUtf8(in_text, pos, in_text_end) out_char = bit32.bor(out_char, bit32.lshift(bit32.band(s[4], 0x3f), 0)) out_char = bit32.rshift(out_char, shiftc[len + 1]) + -- Accumulate the various error conditions. local e = 0 - e = bit32.lshift((out_char < mins[len + 1]) and 1 or 0, 6) - e = bit32.bor(e, bit32.lshift((bit32.rshift(out_char, 11) == 0x1b) and 1 or 0, 7)) - e = bit32.bor(e, bit32.lshift((out_char > IM_UNICODE_CODEPOINT_MAX) and 1 or 0, 8)) + e = bit32.lshift((out_char < mins[len + 1]) and 1 or 0, 6) -- non-canonical encoding + e = bit32.bor(e, bit32.lshift((bit32.rshift(out_char, 11) == 0x1b) and 1 or 0, 7)) -- surrogate half? + e = bit32.bor(e, bit32.lshift((out_char > IM_UNICODE_CODEPOINT_MAX) and 1 or 0, 8)) -- out of range we can store in ImWchar (FIXME: May evolve) e = bit32.bor(e, bit32.rshift(bit32.band(s[2], 0xc0), 2)) e = bit32.bor(e, bit32.rshift(bit32.band(s[3], 0xc0), 4)) e = bit32.bor(e, bit32.rshift(s[4], 6)) - e = bit32.bxor(e, 0x2a) + e = bit32.bxor(e, 0x2a) -- top two bits of each tail byte correct? e = bit32.rshift(e, shifte[len + 1]) if e ~= 0 then + -- No bytes are consumed when in_text[pos] == 0 || pos == in_text_end. + -- One byte is consumed in case of invalid first byte of in_text. + -- All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes. + -- Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s. wanted = ImMin(wanted, (s[1] ~= 0 and 1 or 0) + (s[2] ~= 0 and 1 or 0) + (s[3] ~= 0 and 1 or 0) + (s[4] ~= 0 and 1 or 0)) out_char = IM_UNICODE_CODEPOINT_INVALID end @@ -4010,6 +5178,7 @@ end end +-- Based on stb_to_utf8() from github.com/nothings/stb/ --- @param buf char[] --- @param buf_size int --- @param c unsigned_int @@ -4058,6 +5227,7 @@ function ImStd.ImTextCharToUtf8(out_buf, c) return count end +-- Not optimal but we very rarely use this function. --- @param in_text ImString --- @param pos int --- @param in_text_end int @@ -4189,6 +5359,7 @@ function ImStd.ImStrncpy(dst, dst_pos, src, src_pos, count) dst[dst_pos + (count - 1)] = 0 end +-- find beginning-of-line --- @param str char[] --- @param mid_line int --- @param begin int @@ -4200,31 +5371,55 @@ function ImStd.ImStrbol(str, mid_line, begin) return mid_line end +-- Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. --- @param buf char[] function ImStd.ImStrTrimBlanks(buf) local p = 1 -- buf_begin - while buf[p] == 32 or buf[p] == 9 do + while buf[p] == 32 or buf[p] == 9 do -- Leading blanks p = p + 1 end local p_start = p - while buf[p] ~= 0 do + while buf[p] ~= 0 do -- Find end of string p = p + 1 end - while p > p_start and (buf[p - 1] == 32 or buf[p - 1] == 9) do + while p > p_start and (buf[p - 1] == 32 or buf[p - 1] == 9) do -- Trailing blanks p = p - 1 end - if p_start > 1 then + if p_start > 1 then -- Copy memory if we had leading blanks ImStd.memmove(buf, 1, buf, p_start, p - p_start) end - buf[p - p_start + 1] = 0 + buf[p - p_start + 1] = 0 -- Zero terminate end +------------------------------------------------------------------------------- +-- [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] +-- - RegisterFontAtlas() [Internal] +-- - UnregisterFontAtlas() [Internal] +-- - SetCurrentFont() [Internal] +-- - UpdateCurrentFontSize() [Internal] +-- - PushFont() +-- - PopFont() +------------------------------------------------------------------------------- + function ImGui.UpdateCurrentFontSize(restore_font_size_after_scaling) local g = GImGui local window = g.CurrentWindow g.Style.FontSizeBase = g.FontSizeBase + -- Early out to avoid hidden window keeping bakes referenced and out of GC reach. + -- - However this leave a pretty subtle and damning error surface area if g.FontBaked was mismatching. + -- Probably needs to be reevaluated into e.g. setting g.FontBaked = nil to mark it as dirty. + -- - Note that 'PushFont(); Begin(); End(); PopFont()' from within any collapsed window is not compromised, because Begin() calls SetCurrentWindow()->...->UpdateCurrentSize() -- if (window ~= nil and window.SkipItems) then -- local table = g.CurrentTable -- if (table == nil or (table.CurrentColumn ~= -1 and table.Columns[table.CurrentColumn].IsSkipItems == false)) then @@ -4232,17 +5427,24 @@ function ImGui.UpdateCurrentFontSize(restore_font_size_after_scaling) -- end -- end + -- Restoring is pretty much only used by PopFont() local final_size = (restore_font_size_after_scaling > 0.0) and restore_font_size_after_scaling or 0.0 if final_size == 0.0 then final_size = g.FontSizeBase - final_size = final_size * g.Style.FontScaleMain - final_size = final_size * g.Style.FontScaleDpi + -- Global scale factors + final_size = final_size * g.Style.FontScaleMain -- Main global scale factor + final_size = final_size * g.Style.FontScaleDpi -- Per-monitor/viewport DPI scale factor (in docking branch: automatically updated when io.ConfigDpiScaleFonts is enabled). + + -- Window scale (mostly obsolete now) if window ~= nil then final_size = final_size * window.FontWindowScale end end + -- 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 = ImGui.GetRoundedFontSize(final_size) final_size = ImClamp(final_size, 4.0, IMGUI_FONT_SIZE_MAX) if (g.Font ~= nil and bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) ~= 0) then @@ -4255,6 +5457,14 @@ function ImGui.UpdateCurrentFontSize(restore_font_size_after_scaling) g.DrawListSharedData.FontScale = g.FontBakedScale end +-- 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() ? function ImGui.SetCurrentFont(font, font_size_before_scaling, font_size_after_scaling) local g = GImGui @@ -4263,7 +5473,7 @@ function ImGui.SetCurrentFont(font, font_size_before_scaling, font_size_after_sc ImGui.UpdateCurrentFontSize(font_size_after_scaling) if font ~= nil then - IM_ASSERT(font and font:IsLoaded()) + IM_ASSERT(font and font:IsLoaded()) -- Font Atlas not created. Did you call io.Fonts:GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? local atlas = font.OwnerAtlas g.DrawListSharedData.FontAtlas = atlas g.DrawListSharedData.Font = font @@ -4274,10 +5484,11 @@ function ImGui.SetCurrentFont(font, font_size_before_scaling, font_size_after_sc end end +-- If you want to scale an existing font size! Read comments in imgui.h! function ImGui.PushFont(font, font_size_base) local g = GImGui - if font == nil then + if font == nil then -- Before 1.92 (June 2025), PushFont(nil) == PushFont(GetDefaultFont()) font = g.Font end @@ -4287,7 +5498,7 @@ function ImGui.PushFont(font, font_size_base) g.FontStack:push_back(ImFontStackData(font, g.FontSizeBase, g.FontSize)) if font_size_base == 0.0 then - font_size_base = g.FontSizeBase + font_size_base = g.FontSizeBase -- Keep current font size end ImGui.SetCurrentFont(font, font_size_base, 0.0) @@ -4309,12 +5520,17 @@ function ImGui.PopFont() end function 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. local g = GImGui local has_textures = bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) ~= 0 for _, atlas in g.FontAtlases:iter() do if (atlas.OwnerContext == g) then 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 ~= nil and atlas.Builder.FrameCount ~= -1) IM_ASSERT(atlas.RendererHasTextures == has_textures) end @@ -4325,11 +5541,14 @@ function ImGui.UpdateTexturesNewFrame() end end +-- Build a single texture list function ImGui.UpdateTexturesEndFrame() local g = GImGui g.PlatformIO.Textures:resize(0) for _, atlas in g.FontAtlases:iter() do for _, tex in atlas.TexList:iter() do + -- 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 = atlas.RefCount g.PlatformIO.Textures:push_back(tex) end @@ -4352,16 +5571,18 @@ function ImGui.UpdateFontsNewFrame() g.Style._NextFrameFontSizeBase = 0.0 end + -- Apply default font size the first time local font = ImGui.GetDefaultFont() if g.Style.FontSizeBase <= 0.0 then g.Style.FontSizeBase = ((font.LegacySize > 0.0) and font.LegacySize or FONT_DEFAULT_SIZE_BASE) end + -- Set initial font g.Font = font g.FontSizeBase = g.Style.FontSizeBase g.FontSize = 0.0 - local font_stack_data = ImFontStackData(font, g.Style.FontSizeBase, g.Style.FontSizeBase) - ImGui.SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0) + local font_stack_data = ImFontStackData(font, g.Style.FontSizeBase, g.Style.FontSizeBase) -- <--- Will restore FontSize + ImGui.SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0) -- <--- but use 0.0f to enable scale g.FontStack:push_back(font_stack_data) IM_ASSERT(g.Font:IsLoaded()) end @@ -4406,6 +5627,11 @@ function ImGui.UnregisterFontAtlas(atlas) end end +------------------------------------------------------------------------------- +-- [SECTION] INITIALIZATION, SHUTDOWN +------------------------------------------------------------------------------- + +-- Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself function ImGui.GetCurrentContext() return GImGui end @@ -4437,12 +5663,14 @@ local function ImGuiLocEntry(key, text) return { Key = key, Text = text } end +-- IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation. local GLocalizationEntriesEnUS = { ImGuiLocEntry(ImGuiLocKey.VersionStr, "Dear ImGui WIP"), ImGuiLocEntry(ImGuiLocKey.TableSizeOne, "Size column to fit###SizeOne"), ImGuiLocEntry(ImGuiLocKey.TableSizeAllFit, "Size all columns to fit###SizeAll"), ImGuiLocEntry(ImGuiLocKey.TableSizeAllDefault, "Size all columns to default###SizeAll"), ImGuiLocEntry(ImGuiLocKey.TableReset, "Reset"), + --ImGuiLocEntry(ImGuiLocKey.TableResetAll, "Reset to default###ResetAll"), ImGuiLocEntry(ImGuiLocKey.TableResetOrder, "Reset order###ResetOrder"), ImGuiLocEntry(ImGuiLocKey.TableResetVisibility, "Reset visibility###ResetVisibility"), ImGuiLocEntry(ImGuiLocKey.WindowingMainMenuBar, "(Main menu bar)"), @@ -4459,11 +5687,15 @@ function ImGui.Initialize() local g = GImGui IM_ASSERT(not g.Initialized and not g.SettingsLoaded) + -- Add .ini handle for ImGuiWindow and ImGuiTable types ImGui.WindowSettingsAddSettingsHandler() if ImGui.TableSettingsAddSettingsHandler then ImGui.TableSettingsAddSettingsHandler() end + -- Initialize Docking ImGui.DockContextInitialize(g) + -- Setup default localization table ImGui.LocalizeRegisterEntries(GLocalizationEntriesEnUS, #GLocalizationEntriesEnUS) + -- Create default viewport local viewport = ImGuiViewportP() viewport.ID = IMGUI_VIEWPORT_DEFAULT_ID viewport.Idx = 1 @@ -4473,6 +5705,7 @@ function ImGui.Initialize() g.ViewportCreatedCount = g.ViewportCreatedCount + 1 g.PlatformIO.Viewports:push_back(g.Viewports.Data[1]) + -- Build KeysMayBeCharInput[] lookup table (1 bit per named key) for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do if (key >= ImGuiKey.K0 and key <= ImGuiKey.K9) or (key >= ImGuiKey.A and key <= ImGuiKey.Z) or (key >= ImGuiKey.Keypad0 and key <= ImGuiKey.Keypad9) or key == ImGuiKey.Tab or key == ImGuiKey.Space or key == ImGuiKey.Apostrophe or key == ImGuiKey.Comma or key == ImGuiKey.Minus or key == ImGuiKey.Period @@ -4482,6 +5715,8 @@ function ImGui.Initialize() end end + -- 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. local atlas = g.IO.Fonts g.DrawListSharedData.Context = g ImGui.RegisterFontAtlas(atlas) @@ -4512,6 +5747,7 @@ function ImGui.DestroyContext(ctx) ImGui.SetCurrentContext((prev_ctx ~= ctx) and prev_ctx or nil) end +-- This is faster if you are holding on a Window already as we don't need to perform a search. --- @param window ImGuiWindow --- @return any function ImGui.FindWindowSettingsByWindow(window) @@ -4522,6 +5758,8 @@ function ImGui.FindWindowSettingsByWindow(window) return ImGui.FindWindowSettingsByID(window.ID) end +-- We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names. +-- This is called once per window .ini entry + once per newly instantiated window. --- @param id ImGuiID --- @return any function ImGui.FindWindowSettingsByID(id) @@ -4597,6 +5835,8 @@ local function ApplyWindowSettings(window, settings) end end +-- Note that 'settings' may be nil. +-- Sets _Once, _Appearing, _FirstUseEver. _FirstUseEver will be cleared again if there are settings. --- @param window ImGuiWindow --- @param settings ImGuiWindowSettings local function InitOrLoadWindowSettings(window, settings) @@ -4621,6 +5861,8 @@ end --- @param flags ImGuiWindowFlags --- @return ImGuiWindow local function CreateNewWindow(name, flags) + -- Create window the first time + --IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags) local g = GImGui local window_id = ImHashStr(name) @@ -4643,7 +5885,7 @@ local function CreateNewWindow(name, flags) InitOrLoadWindowSettings(window, settings) if bit32.band(flags, ImGuiWindowFlags.NoBringToFrontOnFocus) ~= 0 then - g.Windows:push_front(window) + g.Windows:push_front(window) -- Quite slow but rare and only once else g.Windows:push_back(window) end @@ -4652,21 +5894,41 @@ local function CreateNewWindow(name, flags) end ---------------------------------------------------------------------------------------- --- [SECTION] SETTINGS (in-memory .ini; Roblox has no disk) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] SETTINGS +-- (in-memory .ini; Roblox has no disk) +------------------------------------------------------------------------------- +-- - UpdateSettings() [Internal] +-- - MarkIniSettingsDirty() [Internal] +-- - FindSettingsHandler() [Internal] +-- - ClearIniSettings() [Internal] +-- - LoadIniSettingsFromDisk() +-- - LoadIniSettingsFromMemory() +-- - SaveIniSettingsToDisk() +-- - SaveIniSettingsToMemory() +------------------------------------------------------------------------------- +-- - CreateNewWindowSettings() [Internal] +-- - FindWindowSettingsByID() [Internal] +-- - FindWindowSettingsByWindow() [Internal] +-- - ClearWindowSettings() [Internal] +-- - WindowSettingsHandler_***() [Internal] +------------------------------------------------------------------------------- +-- Called by NewFrame() function ImGui.UpdateSettings() + -- Load settings on first frame (if not explicitly loaded manually before) local g = GImGui if not g.SettingsLoaded then if g.IO.IniFilename then ImGui.LoadIniSettingsFromDisk(g.IO.IniFilename) end g.SettingsLoaded = true end + + -- Save settings (with a delay after the last modification, so we don't spam disk too much) if g.SettingsDirtyTimer > 0.0 then g.SettingsDirtyTimer = g.SettingsDirtyTimer - g.IO.DeltaTime if g.SettingsDirtyTimer <= 0.0 then -- No disk: always let the user know they can call SaveIniSettingsToMemory() - g.IO.WantSaveIniSettings = true + g.IO.WantSaveIniSettings = true -- Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. g.SettingsDirtyTimer = 0.0 end end @@ -4704,6 +5966,7 @@ function ImGui.FindSettingsHandler(type_name) return nil end +-- Clear all settings (windows, tables, docking etc.) function ImGui.ClearIniSettings() local g = GImGui g.SettingsIniData = "" @@ -4731,13 +5994,20 @@ function ImGui.LoadIniSettingsFromDisk(ini_filename) ImGui.LoadIniSettingsFromMemory(table.concat(parts)) end ---- Zero-tolerance, cheap .ini parsing. `ini_size` ignored (Lua strings know their length). +-- Zero-tolerance, no error reporting, cheap .ini parsing +-- Set ini_size==0 (or nil) to use the whole string (Lua strings know their length). function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) local g = GImGui IM_ASSERT(g.Initialized) + --IM_ASSERT(not g.WithinFrameScope, "Cannot be called between NewFrame() and EndFrame()") + --IM_ASSERT(g.SettingsLoaded == false and g.FrameCount == 0) + + -- For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). if ini_size and ini_size > 0 then ini_data = ini_data:sub(1, ini_size) end g.SettingsIniData = ini_data + -- Call pre-read handlers + -- Some types will clear their data (e.g. dock information) some types will allow merge/override (window) for _, handler in g.SettingsHandlers:iter() do if handler.ReadInitFn then handler.ReadInitFn(g, handler) end end @@ -4748,7 +6018,7 @@ function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) if c == ";" then -- comment elseif c == "[" and line:sub(-1) == "]" then - -- "[Type][Name]" (Name may contain [] characters) + -- Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. local type_name, name = line:match("^%[([^%]]*)%]%[(.*)%]$") if type_name then entry_handler = ImGui.FindSettingsHandler(type_name) @@ -4757,11 +6027,13 @@ function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) entry_handler, entry_data = nil, nil end elseif entry_handler ~= nil and entry_data ~= nil then + -- Let type handler parse the line entry_handler.ReadLineFn(g, entry_handler, entry_data, line) end end g.SettingsLoaded = true + -- Call post-read handlers for _, handler in g.SettingsHandlers:iter() do if handler.ApplyAllFn then handler.ApplyAllFn(g, handler) end end @@ -4773,6 +6045,7 @@ function ImGui.SaveIniSettingsToDisk(ini_filename) -- Roblox: no disk. Call SaveIniSettingsToMemory() and persist the string yourself (e.g. DataStore). end +-- Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer --- @return string ini_data, int size function ImGui.SaveIniSettingsToMemory() local g = GImGui @@ -4787,6 +6060,8 @@ end function ImGui.CreateNewWindowSettings(name) local g = GImGui + + -- Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier. if not g.IO.ConfigDebugIniSettings then -- ImHashSkipUncontributingPrefix: skip everything up to the last "###" local p = name:match("^.*()###") @@ -4799,7 +6074,9 @@ function ImGui.CreateNewWindowSettings(name) return settings end +-- This will revert window to its initial state, including enabling the ImGuiCond.FirstUseEver/ImGuiCond.Once conditions once more. function ImGui.ClearWindowSettings(name) + --IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name) local window = ImGui.FindWindowByName(name) if window ~= nil then window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.NoSavedSettings) @@ -4822,6 +6099,7 @@ local function WindowSettingsHandler_ReadOpen(ctx, handler, name) local id = ImHashStr(name) local settings = ImGui.FindWindowSettingsByID(id) if settings then + -- Clear existing if recycling previous entry local fresh = ImGuiWindowSettings() for k, v in pairs(fresh) do settings[k] = v end settings.Name = name @@ -4856,6 +6134,7 @@ local function WindowSettingsHandler_ReadLine(ctx, handler, settings, line) if x then settings.ClassId = tonumber(x, 16) return end end +-- Apply to existing windows (if any) local function WindowSettingsHandler_ApplyAll(ctx, handler) local g = ctx for _, settings in g.SettingsWindows:iter() do @@ -4868,6 +6147,8 @@ local function WindowSettingsHandler_ApplyAll(ctx, handler) end local function WindowSettingsHandler_WriteAll(ctx, handler, buf) + -- Gather data from windows that were active during this session + -- (if a window wasn't opened in this session we preserve its settings) local g = ctx for _, window in g.Windows:iter() do if bit32.band(window.Flags, ImGuiWindowFlags.NoSavedSettings) == 0 then @@ -4885,14 +6166,15 @@ local function WindowSettingsHandler_WriteAll(ctx, handler, buf) settings.ClassId = window.WindowClass and window.WindowClass.ClassId or 0 settings.DockOrder = window.DockOrder or -1 settings.Collapsed = window.Collapsed - settings.IsChild = (window.RootWindow ~= window) + settings.IsChild = (window.RootWindow ~= window) -- Cannot rely on ImGuiWindowFlags.ChildWindow here as docked windows have this set. settings.WantDelete = false end end + -- Write to text buffer for _, settings in g.SettingsWindows:iter() do if not settings.WantDelete then - buf:appendf("[%s][%s]\n", handler.TypeName, settings.Name) + buf:appendf("[%s][%s]\n", handler.TypeName, settings.Name) -- [Window][name] if settings.IsChild then buf:appendf("IsChild=1\n") buf:appendf("Size=%d,%d\n", settings.Size.x, settings.Size.y) @@ -4909,6 +6191,7 @@ local function WindowSettingsHandler_WriteAll(ctx, handler, buf) end buf:appendf("Collapsed=%d\n", settings.Collapsed and 1 or 0) if settings.DockId ~= 0 then + --buf:appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings.ID)) -- window.TabId: this is not read back but writing it makes "debugging" the .ini data easier. if settings.DockOrder == -1 then buf:appendf("DockId=0x%08X\n", settings.DockId) else @@ -4934,14 +6217,18 @@ function ImGui.WindowSettingsAddSettingsHandler() ImGui.AddSettingsHandler(ini_handler) end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] LOGGING/CAPTURING ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- All text output from the interface can be captured into tty/file/clipboard. +-- By default, tree nodes are automatically opened during logging. +------------------------------------------------------------------------------- ImGuiLogFlags = ImGuiLogFlags or { None = 0, OutputTTY = 1, OutputFile = 2, OutputBuffer = 4, OutputClipboard = 8, OutputMask_ = 15, } +-- Pass text data straight to log (without being displayed) local function LogTextV_Internal(g, fmt, ...) local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt if g.LogFile then @@ -4958,7 +6245,9 @@ function ImGui.LogText(fmt, ...) end ImGui.LogTextV = ImGui.LogText ---- Internal version that takes a position to decide on newline placement and pad items according to their depth. +-- Internal version that takes a position to decide on newline placement and pad items according to their depth. +-- We split text into individual lines to add current tree level padding +-- FIXME: This code is a little complicated perhaps, considering simplifying the whole system. --- `text` is a Lua string, `text_begin/text_end` optional 1-based byte range (text_end exclusive). function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) local g = GImGui @@ -4977,13 +6266,16 @@ function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) g.LogLineFirstItem = true end - if prefix then ImGui.LogRenderedText(ref_pos, prefix, #prefix + 1) end + if prefix then ImGui.LogRenderedText(ref_pos, prefix, #prefix + 1) end -- 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 then g.LogDepthRef = window.DC.TreeDepth end local tree_depth = window.DC.TreeDepth - g.LogDepthRef local text_remaining = text_begin while true do + -- Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry. + -- We don't add a trailing \n yet to allow a subsequent item on the same line to be captured. local line_start = text_remaining local nl = string.find(text, "\n", line_start, true) local line_end = (nl and nl < text_end) and nl or text_end @@ -5004,6 +6296,7 @@ function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) if suffix then ImGui.LogRenderedText(ref_pos, suffix, #suffix + 1) end end +-- Start logging/capturing text output function ImGui.LogBegin(flags, auto_open_depth) local g = GImGui local window = g.CurrentWindow @@ -5019,6 +6312,7 @@ function ImGui.LogBegin(flags, auto_open_depth) g.LogBuffer = ImGuiTextBuffer() end +-- Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText) function ImGui.LogSetNextTextDecoration(prefix, suffix) local g = GImGui g.LogNextPrefix = prefix @@ -5032,11 +6326,13 @@ function ImGui.LogToTTY(auto_open_depth) g.LogFile = "stdout" end +-- Start logging/capturing text output to given file function ImGui.LogToFile(auto_open_depth, filename) -- Roblox: no file access. Falls back to TTY (output window). ImGui.LogToTTY(auto_open_depth) end +-- Start logging/capturing text output to clipboard function ImGui.LogToClipboard(auto_open_depth) local g = GImGui if g.LogEnabled then return end @@ -5063,6 +6359,8 @@ function ImGui.LogFinish() g.LogBuffer = ImGuiTextBuffer() end +-- Helper to display logging buttons +-- FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!) function ImGui.LogButtons() local g = GImGui ImGui.PushID("LogButtons") @@ -5074,6 +6372,8 @@ function ImGui.LogButtons() g.LogDepthToExpandDefault = ImGui.SliderInt("Default Depth", g.LogDepthToExpandDefault, 0, 9, nil) ImGui.PopItemFlag() ImGui.PopID() + + -- Start logging at the end of the function so that the buttons don't appear in the log if log_to_tty then ImGui.LogToTTY() end if log_to_file then ImGui.LogToFile() end if log_to_clipboard then ImGui.LogToClipboard() end @@ -5089,6 +6389,7 @@ local function GetWindowForTitleDisplay(window) end end +-- Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID(). --- @param id ImGuiID function ImGui.KeepAliveID(id) @@ -5103,6 +6404,9 @@ function ImGui.KeepAliveID(id) end end +-- Test if mouse cursor is hovering given rectangle +-- NB- Rectangle is clipped by our current clip setting +-- NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) --- @param r_min ImVec2 --- @param r_max ImVec2 --- @param clip? bool @@ -5112,6 +6416,7 @@ function ImGui.IsMouseHoveringRect(r_min, r_max, clip) local g = GImGui -- [Luau] scalar version of: rect_clipped = ImRect(r_min, r_max); ClipWith(window.ClipRect); ContainsWithPad(); viewport Overlaps() + -- Clip local x0, y0, x1, y1 = r_min.x, r_min.y, r_max.x, r_max.y if clip then local cr = g.CurrentWindow.ClipRect @@ -5120,6 +6425,7 @@ function ImGui.IsMouseHoveringRect(r_min, r_max, clip) x1 = math.min(x1, cmax.x); y1 = math.min(y1, cmax.y) end + -- Hit testing, expanded for touch input local p, pad = g.IO.MousePos, g.Style.TouchExtraPadding if not (p.x >= x0 - pad.x and p.y >= y0 - pad.y and p.x < x1 + pad.x and p.y < y1 + pad.y) then return false @@ -5162,6 +6468,8 @@ function ImGui.IsMouseDragging(button, lock_threshold) return ImGui.IsMouseDragPastThreshold(button, lock_threshold) end +-- This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well. +-- It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags.HasSetMousePos) is set and supported by backend. --- @param pos ImVec2 function ImGui.TeleportMousePos(pos) local g = GImGui @@ -5172,11 +6480,12 @@ function ImGui.TeleportMousePos(pos) -- IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y) end +-- Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData --- @param id ImGuiID function ImGui.ItemHandleShortcut(id) local g = GImGui local flags = g.NextItemData.ShortcutFlags - IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetNextItemShortcut)) == 0) + IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetNextItemShortcut)) == 0) -- Passing flags not supported by SetNextItemShortcut()! if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.Disabled) ~= 0 then return @@ -5189,13 +6498,19 @@ function ImGui.ItemHandleShortcut(id) return end - g.NavActivateId = id + -- FIXME: Generalize Activation queue? + g.NavActivateId = id -- Will effectively disable clipping. g.NavActivateFlags = bit32.bor(ImGuiActivateFlags.PreferInput, ImGuiActivateFlags.FromShortcut) + -- if (g.ActiveId == 0 || g.ActiveId == id) g.NavActivateDownId = id g.NavActivatePressedId = id ImGui.NavHighlightActivated(id) end +-- Declare item bounding box for clipping and interaction. +-- Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface +-- declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction. +-- THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN) --- @param bb ImRect --- @param id ImGuiID --- @param nav_bb_arg? ImRect @@ -5207,16 +6522,30 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) local g = GImGui local window = g.CurrentWindow + -- Set item data + -- (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags.HasDisplayRect is set) g.LastItemData.ID = id ImRect_Copy(g.LastItemData.Rect, bb) ImRect_Copy(g.LastItemData.NavRect, nav_bb_arg and nav_bb_arg or bb) g.LastItemData.ItemFlags = bit32.bor(g.CurrentItemFlags, g.NextItemData.ItemFlagsSet, extra_flags) g.LastItemData.StatusFlags = ImGuiItemStatusFlags.None + -- Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared. if id ~= 0 then ImGui.KeepAliveID(id) + -- Directional navigation processing + -- Runs prior to clipping early-out + -- (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget + -- (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests + -- unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of + -- thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. + -- We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able + -- to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick). + -- We intentionally don't check if g.NavWindow ~= nil because g.NavAnyRequest should only be set when it is non nil. + -- If we crash on a nil g.NavWindow we need to fix the bug elsewhere. if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoNav) == 0 then + -- FIXME-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test. window.DC.NavLayersActiveMaskNext = bit32.bor(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, window.DC.NavLayerCurrent)) if g.NavId == id or g.NavAnyRequest then @@ -5233,9 +6562,13 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) end end + -- Lightweight clear of SetNextItemXXX data. g.NextItemData.HasFlags = ImGuiNextItemDataFlags.None g.NextItemData.ItemFlagsSet = ImGuiItemFlags.None + -- Clipping test + -- (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false') + -- g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts) local bmin, bmax, cr = bb.Min, bb.Max, window.ClipRect local is_rect_visible = bmin.x <= cr.Max.x and bmax.x >= cr.Min.x and bmin.y <= cr.Max.y and bmax.y >= cr.Min.y if not is_rect_visible then @@ -5248,6 +6581,7 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) g.DeactivatedItemData.ElapseFrame = g.FrameCount end + -- 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 then g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) end @@ -5259,6 +6593,39 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) return true end +------------------------------------------------------------------------------- +-- [SECTION] LAYOUT +------------------------------------------------------------------------------- +-- - ItemSize() +-- - SameLine() +-- - GetCursorScreenPos() +-- - SetCursorScreenPos() +-- - GetCursorPos(), GetCursorPosX(), GetCursorPosY() +-- - SetCursorPos(), SetCursorPosX(), SetCursorPosY() +-- - GetCursorStartPos() +-- - Indent() +-- - Unindent() +-- - SetNextItemWidth() +-- - PushItemWidth() +-- - PushMultiItemsWidths() +-- - PopItemWidth() +-- - CalcItemWidth() +-- - CalcItemSize() +-- - GetTextLineHeight() +-- - GetTextLineHeightWithSpacing() +-- - GetFrameHeight() +-- - GetFrameHeightWithSpacing() +-- - GetContentRegionMax() +-- - GetContentRegionAvail(), +-- - BeginGroup() +-- - EndGroup() +-- Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns. +------------------------------------------------------------------------------- + +-- Advance cursor given item size for layout. +-- Register minimum needed size so it can extend the bounding box used for auto-fit calculation. +-- See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different. +-- THIS IS IN THE PERFORMANCE CRITICAL PATH. --- @param size_or_bb ImVec2|ImRect --- @param text_baseline_y? float @@ -5284,6 +6651,9 @@ function ImGui.ItemSize(size_or_bb, text_baseline_y) local dc = window.DC local mathMax = math.max + -- We increase the height in this function to accommodate for baseline offset. + -- In theory we should be offsetting the starting position (window.DC.CursorPos), that will be the topic of a larger refactor, + -- but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect. local offset_to_match_baseline_y if text_baseline_y >= 0 then offset_to_match_baseline_y = mathMax(0, dc.CurrLineTextBaseOffset - text_baseline_y) @@ -5302,12 +6672,15 @@ function ImGui.ItemSize(size_or_bb, text_baseline_y) local line_height = mathMax(dc.CurrLineSize.y, cursor.y - line_y1 + size_y + offset_to_match_baseline_y) local spacing_y = g.Style.ItemSpacing.y + -- Always align ourselves on pixel boundaries + -- if (g.IO.KeyAlt) window.DrawList:AddRect(window.DC.CursorPos, window.DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)) -- [DEBUG] prev_line.x = cursor.x + size_x prev_line.y = line_y1 - cursor.x = math.floor(window.Pos.x + dc.Indent.x + dc.ColumnsOffset.x) - cursor.y = math.floor(line_y1 + line_height + spacing_y) + cursor.x = math.floor(window.Pos.x + dc.Indent.x + dc.ColumnsOffset.x) -- Next line + cursor.y = math.floor(line_y1 + line_height + spacing_y) -- Next line max_pos.x = mathMax(max_pos.x, prev_line.x) max_pos.y = mathMax(max_pos.y, cursor.y - spacing_y) + -- if (g.IO.KeyAlt) window.DrawList:AddCircle(window.DC.CursorMaxPos, 3.0, IM_COL32(255,0,0,255), 4) -- [DEBUG] dc.PrevLineSize.y = line_height dc.CurrLineSize.y = 0 @@ -5316,12 +6689,17 @@ function ImGui.ItemSize(size_or_bb, text_baseline_y) dc.IsSetPos = false dc.IsSameLine = false - --- Horizontal layout mode + -- Horizontal layout mode if (dc.LayoutType == ImGuiLayoutType.Horizontal) then ImGui.SameLine() end end +-- Gets back to previous line and continue with horizontal layout +-- offset_from_start_x == 0 : follow right after previous item +-- offset_from_start_x != 0 : align to specified x position (relative to window/group left) +-- spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0 +-- spacing_w >= 0 : enforce spacing amount --- @param offset_from_start_x float? --- @param spacing_w float? @@ -5382,7 +6760,7 @@ function ImGui.Unindent(indent_w) window.DC.CursorPos.x = window.Pos.x + window.DC.Indent.x + window.DC.ColumnsOffset.x end --- Affect large frame+labels widgets only +-- Affect large frame+labels widgets only. --- @param item_width float function ImGui.SetNextItemWidth(item_width) local g = GImGui @@ -5390,11 +6768,12 @@ function ImGui.SetNextItemWidth(item_width) g.NextItemData.Width = item_width end +-- FIXME: Remove the == 0.0f behavior? --- @param item_width float function ImGui.PushItemWidth(item_width) local g = GImGui local window = g.CurrentWindow - window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) + window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) -- Backup current width window.DC.ItemWidth = (item_width == 0.0) and window.DC.ItemWidthDefault or item_width g.NextItemData.HasFlags = bit32.band(g.NextItemData.HasFlags, bit32.bnot(ImGuiNextItemDataFlags.HasWidth)) end @@ -5417,7 +6796,7 @@ function ImGui.PushMultiItemsWidths(components, w_full) local window = g.CurrentWindow IM_ASSERT(components > 0) local style = g.Style - window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) + window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) -- Backup current width local w_items = w_full - style.ItemInnerSpacing.x * (components - 1) local prev_split = w_items for i = components - 1, 1, -1 do @@ -5465,10 +6844,12 @@ end function ImGui.SetCursorScreenPos(pos) local window = ImGui.GetCurrentWindow() ImVec2_Copy(window.DC.CursorPos, pos) + -- window.DC.CursorMaxPos = ImMax(window.DC.CursorMaxPos, window.DC.CursorPos) window.DC.IsSetPos = true end --- [window-local] cursor position, in window coordinates (relative to window position, including scrolling) +-- User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. +-- Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. --- @return ImVec2 function ImGui.GetCursorPos() local window = ImGui.GetCurrentWindowRead() @@ -5489,6 +6870,7 @@ end function ImGui.SetCursorPos(local_pos) local window = ImGui.GetCurrentWindow() ImVec2_CopyV(window.DC.CursorPos, window.Pos.x - window.Scroll.x + local_pos.x, window.Pos.y - window.Scroll.y + local_pos.y) + -- window.DC.CursorMaxPos = ImMax(window.DC.CursorMaxPos, window.DC.CursorPos) window.DC.IsSetPos = true end @@ -5496,6 +6878,7 @@ end function ImGui.SetCursorPosX(x) local window = ImGui.GetCurrentWindow() window.DC.CursorPos.x = window.Pos.x - window.Scroll.x + x + -- window.DC.CursorMaxPos.x = ImMax(window.DC.CursorMaxPos.x, window.DC.CursorPos.x) window.DC.IsSetPos = true end @@ -5503,6 +6886,7 @@ end function ImGui.SetCursorPosY(y) local window = ImGui.GetCurrentWindow() window.DC.CursorPos.y = window.Pos.y - window.Scroll.y + y + -- window.DC.CursorMaxPos.y = ImMax(window.DC.CursorMaxPos.y, window.DC.CursorPos.y) window.DC.IsSetPos = true end @@ -5522,6 +6906,8 @@ function ImGui.GetTextLineHeightWithSpacing() return g.FontSize + g.Style.ItemSpacing.y end +-- You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()! +-- They are bizarre local-coordinates which don't play well with scrolling. --- @return ImVec2 function ImGui.GetContentRegionMax() local window = GImGui.CurrentWindow @@ -5580,7 +6966,7 @@ function ImGui.BeginGroup() ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorPos) ImVec2_CopyV(window.DC.CurrLineSize, 0.0, 0.0) if (g.LogEnabled) then - g.LogLinePosY = -FLT_MAX + g.LogLinePosY = -FLT_MAX -- To enforce a carriage return end end @@ -5597,6 +6983,7 @@ function ImGui.EndGroup() -- TODO: ImGui.ErrorCheckUsingSetCursorPosToExtendParentBoundaries() end + -- Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543) local group_bb = ImRect(group_data.BackupCursorPos, ImMax(ImMax(window.DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos)) ImVec2_Copy(window.DC.CursorPos, group_data.BackupCursorPos) ImVec2_Copy(window.DC.CursorPosPrevLine, group_data.BackupCursorPosPrevLine) @@ -5615,7 +7002,7 @@ function ImGui.EndGroup() return end - window.DC.CurrLineTextBaseOffset = ImMax(window.DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset) -- FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now + window.DC.CurrLineTextBaseOffset = ImMax(window.DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset) -- FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. ImGui.ItemSize(group_bb:GetSize()) ImGui.ItemAdd(group_bb, 0, nil, ImGuiItemFlags.NoTabStop) @@ -5655,6 +7042,8 @@ function ImGui.EndGroup() end end +-- Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(). +-- The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags() function ImGui.CalcItemWidth() local g = GImGui @@ -5676,6 +7065,10 @@ function ImGui.CalcItemWidth() return w end +-- [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth(). +-- Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. +-- Note that only CalcItemWidth() is publicly exposed. +-- The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) --- @param size ImVec2 --- @param default_w float --- @param default_h float @@ -5689,13 +7082,13 @@ function ImGui.CalcItemSize(size, default_w, default_h) if size.x == 0.0 then size.x = default_w elseif size.x < 0.0 then - size.x = ImMax(4.0, avail.x + size.x) -- size.x is negative here so we are subtracting + size.x = ImMax(4.0, avail.x + size.x) -- <-- size.x is negative here so we are subtracting end if size.y == 0.0 then size.y = default_h elseif size.y < 0.0 then - size.y = ImMax(4.0, avail.y + size.y) -- size.y is negative here so we are subtracting + size.y = ImMax(4.0, avail.y + size.y) -- <-- size.y is negative here so we are subtracting end return size @@ -5716,12 +7109,15 @@ function ImGui.IsItemActive() return false end +-- == (GetItemID() == GetFocusID() && GetFocusID() != 0) function ImGui.IsItemFocused() local g = GImGui if g.NavId ~= g.LastItemData.ID or g.NavId == 0 then return false end + -- Special handling for the dummy item after Begin() which represent the title bar or tab. + -- When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. local window = g.CurrentWindow if g.LastItemData.ID == window.ID and window.WriteAccessed then return false @@ -5738,6 +7134,7 @@ function ImGui.IsItemDeactivated() return g.DeactivatedItemData.ID == g.LastItemData.ID and g.LastItemData.ID ~= 0 and g.DeactivatedItemData.ElapseFrame >= g.FrameCount end +-- Since 1.92.9: consider using NoLiveEdit flags if all you need to that values are not written bo backing variable while typing. function ImGui.IsItemDeactivatedAfterEdit() local g = GImGui return ImGui.IsItemDeactivated() and g.DeactivatedItemData.HasBeenEditedBefore @@ -5754,6 +7151,7 @@ function ImGui.IsItemActivated() end -- Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()! +-- Most widgets have specific reactions based on mouse-up/down state, mouse position etc. --- @param mouse_button? ImGuiMouseButton function ImGui.IsItemClicked(mouse_button) if mouse_button == nil then mouse_button = 0 end @@ -5764,12 +7162,21 @@ function ImGui.IsItemToggledOpen() return bit32.band(GImGui.LastItemData.StatusFlags, ImGuiItemStatusFlags.ToggledOpen) ~= 0 end +-- Call after a Selectable() or TreeNode() items inside a BeginMultiSelect()/EndMultiSelect() scope. +-- - Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose. +-- Outside of a multi-select block: +-- - It would be misleading/ambiguous to report this signal, as widgets return e.g. a pressed event, +-- and user code is in charge of altering selection in ways we cannot predict. +-- Prefer using 'if (IsItemClicked() && !IsItemToggledOpen())' for a manual reimplementation of selection. function ImGui.IsItemToggledSelection() local g = GImGui IM_ASSERT(g.CurrentMultiSelect ~= nil) -- Can only be used inside a BeginMultiSelect()/EndMultiSelect() return bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.ToggledSelection) ~= 0 end +-- IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, +-- you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! +-- Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. function ImGui.IsAnyItemHovered() local g = GImGui return g.HoveredId ~= 0 or g.HoveredIdPreviousFrame ~= 0 @@ -5793,6 +7200,8 @@ function ImGui.IsItemEdited() end -- Allow next item to be overlapped by subsequent items. +-- This works by requiring HoveredId to match for two subsequent frames, +-- so if a following items overwrite it our interactions will naturally be disabled. function ImGui.SetNextItemAllowOverlap() local g = GImGui g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.AllowOverlap) @@ -5816,10 +7225,23 @@ function ImGui.GetHoveredID() return (g.HoveredId ~= 0) and g.HoveredId or g.HoveredIdPreviousFrame end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] WINDOW FOCUS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - SetWindowFocus() +-- - SetNextWindowFocus() +-- - IsWindowFocused() +-- - UpdateWindowInFocusOrderList() [Internal] +-- - BringWindowToFocusFront() [Internal] +-- - BringWindowToDisplayFront() [Internal] +-- - BringWindowToDisplayBack() [Internal] +-- - BringWindowToDisplayBehind() [Internal] +-- - FindWindowDisplayIndex() [Internal] +-- - FocusWindow() [Internal] +-- - FocusTopMostWindowUnderOne() [Internal] +------------------------------------------------------------------------------- +-- Moving window to front of display and set focus (which happens to be back of our sorted list) --- @param window? ImGuiWindow --- @param flags? ImGuiFocusRequestFlags function ImGui.FocusWindow(window, flags) @@ -5827,28 +7249,34 @@ function ImGui.FocusWindow(window, flags) local g = GImGui - if bit32.band(flags, ImGuiFocusRequestFlags.UnlessBelowModal) ~= 0 and g.NavWindow ~= window then + -- Modal check? + if bit32.band(flags, ImGuiFocusRequestFlags.UnlessBelowModal) ~= 0 and g.NavWindow ~= window then -- Early out in common case. local blocking_modal = ImGui.FindBlockingModal(window) if blocking_modal then + -- 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 == nil) -- IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".", window ? window->Name : "", blocking_modal->Name) if window and window == window.RootWindow and bit32.band(window.Flags, ImGuiWindowFlags.NoBringToFrontOnFocus) == 0 then - ImGui.BringWindowToDisplayBehind(window, blocking_modal) + ImGui.BringWindowToDisplayBehind(window, blocking_modal) -- Still bring right under modal. (FIXME: Could move in focus list too?) end - ImGui.ClosePopupsOverWindow(ImGui.GetTopMostPopupModal(), false) + ImGui.ClosePopupsOverWindow(ImGui.GetTopMostPopupModal(), false) -- Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals return end end + -- Find last focused child (if any) and focus it instead. if bit32.band(flags, ImGuiFocusRequestFlags.RestoreFocusedChild) ~= 0 and window ~= nil then window = ImGui.NavRestoreLastChildNavWindow(window) end + -- Apply focus if g.NavWindow ~= window then ImGui.SetNavWindow(window) if window and g.NavHighlightItemUnderNav then g.NavMousePosDirty = true end - g.NavId = window and window.NavLastIds[0] or 0 + g.NavId = window and window.NavLastIds[0] or 0 -- Restore NavId g.NavLayer = ImGuiNavLayer.Main ImGui.SetNavFocusScope(window and window.NavRootFocusScopeId or 0) g.NavIdIsAlive = false @@ -5858,23 +7286,35 @@ function ImGui.FocusWindow(window, flags) ImGui.ClosePopupsOverWindow(window, false) end + -- Move the root window to the top of the pile IM_ASSERT(window == nil or window.RootWindowDockTree ~= nil) local focus_front_window = window and window.RootWindow or nil local display_front_window = window and window.RootWindowDockTree or nil local dock_node = window and window.DockNode or nil local active_id_window_is_dock_node_host = g.ActiveIdWindow and dock_node and 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 and g.ActiveIdWindow and g.ActiveIdWindow.RootWindow ~= focus_front_window then if not g.ActiveIdNoClearOnFocusLoss and not active_id_window_is_dock_node_host then ImGui.ClearActiveID() end end + -- Passing nil allow to disable keyboard focus if not window then return end 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 ImGui.BringWindowToFocusFront(focus_front_window) if bit32.band(bit32.bor(window.Flags, focus_front_window.Flags, display_front_window.Flags), ImGuiWindowFlags.NoBringToFrontOnFocus) == 0 then ImGui.BringWindowToDisplayFront(display_front_window) @@ -5892,6 +7332,9 @@ function ImGui.FindWindowFocusIndex(window) return order end +-- 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. --- @param window ImGuiWindow --- @return bool function ImGui.IsWindowNavFocusable(window) @@ -5902,7 +7345,7 @@ end --- @param i_stop int --- @param dir int --- @return ImGuiWindow? -function ImGui.FindWindowNavFocusable(i_start, i_stop, dir) +function ImGui.FindWindowNavFocusable(i_start, i_stop, dir) -- FIXME-OPT O(N) local g = GImGui local i = i_start while i >= 1 and i <= g.WindowsFocusOrder.Size and i ~= i_stop do @@ -5963,13 +7406,15 @@ function ImGui.BringWindowToFocusFront(window) window.FocusOrder = new_order end +-- Note technically focus related but rather adjacent and close to BringWindowToFocusFront() +-- FIXME-FOCUS: Could opt-in/opt-out enable modal check like in FocusWindow(). --- @param window? ImGuiWindow function ImGui.BringWindowToDisplayFront(window) local g = GImGui local current_front_window = g.Windows:back() - if current_front_window == window or current_front_window.RootWindowDockTree == window then + if current_front_window == window or current_front_window.RootWindowDockTree == window then -- Cheap early out (could be better) return end @@ -6012,6 +7457,7 @@ function ImGui.FocusTopMostWindowUnderOne(under_this_window, ignore_window, filt end for i = start_idx, 1, -1 do repeat + -- 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. local window = g.WindowsFocusOrder.Data[i] if window == ignore_window or not window.WasActive then break @@ -6020,6 +7466,11 @@ function ImGui.FocusTopMostWindowUnderOne(under_this_window, ignore_window, filt break end if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs)) ~= bit32.bor(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs) then + -- 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? ImGui.FocusWindow(window, flags) return end @@ -6039,6 +7490,8 @@ function ImGui.SetFocusID(id, window) ImGui.SetNavWindow(window) end + -- Assume that SetFocusID() is called in the context where its window.DC.NavLayerCurrent and g.CurrentFocusScopeId are valid. + -- Note that window may be ~= g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text) local nav_layer = window.DC.NavLayerCurrent g.NavId = id g.NavLayer = nav_layer @@ -6058,23 +7511,33 @@ function ImGui.SetFocusID(id, window) g.NavCursorVisible = false end + -- Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y) end +-- This is not 100% symmetric 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). function ImGui.StopMouseMovingWindow() local g = GImGui local window = g.MovingWindow + -- Ref commits 6b7766817, 36055213c for some partial history on checking if viewport ~= nil. if window and window.Viewport then + -- 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 bit32.band(g.ConfigFlagsCurrFrame, ImGuiConfigFlags.ViewportsEnable) ~= 0 then ImGui.UpdateTryMergeWindowIntoHostViewport(window.RootWindowDockTree, g.MouseViewport) end + -- 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 (not ImGui.IsDragDropPayloadBeingAccepted()) then g.MouseViewport = window.Viewport end + -- Clear the NoInputs window flag set by the Viewport system in AddUpdateViewport() local window_can_use_inputs = bit32.band(window.Flags, ImGuiWindowFlags.NoMouseInputs) == 0 or bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) == 0 if window_can_use_inputs then window.Viewport.Flags = bit32.band(window.Viewport.Flags, bit32.bnot(ImGuiViewportFlags.NoInputs)) @@ -6089,23 +7552,32 @@ end function ImGui.SetActiveID(id, window) local g = GImGui + -- Clear previous active id if g.ActiveId ~= 0 then + -- Store deactivate data local deactivated_data = g.DeactivatedItemData deactivated_data.ID = g.ActiveId deactivated_data.ElapseFrame = (g.LastItemData.ID == g.ActiveId) and g.FrameCount or 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 then ImGui.InputTextDeactivateHook(g.ActiveId) end + -- 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 and (g.ActiveId == g.MovingWindow.MoveId) then print("SetActiveID() cancel MovingWindow") ImGui.StopMouseMovingWindow() end end + -- Set active id g.ActiveIdIsJustActivated = (g.ActiveId ~= id) if (g.ActiveIdIsJustActivated) then -- IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() 0x%08X in \"%s\"%*s(previously 0x%08X in \"%s\")\n", id, window ? window->Name : "", @@ -6137,14 +7609,20 @@ function ImGui.SetActiveID(id, window) IM_ASSERT(g.ActiveIdSource ~= ImGuiInputSource.None) end + -- Clear declaration of inputs claimed by the widget + -- (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet) g.ActiveIdUsingNavDirMask = 0x00 g.ActiveIdUsingAllKeyboardKeys = false end function ImGui.ClearActiveID() - ImGui.SetActiveID(0, nil) + ImGui.SetActiveID(0, nil) -- g.ActiveId = 0 end +------------------------------------------------------------------------------- +-- [SECTION] ID STACK +------------------------------------------------------------------------------- + --- @param str_id string|int function ImGui.PushID(str_id) @@ -6154,6 +7632,7 @@ function ImGui.PushID(str_id) window.IDStack:push_back(id) end +-- Push a given id value ignoring the ID stack as a seed. --- @param id ImGuiID function ImGui.PushOverrideID(id) local g = GImGui @@ -6171,6 +7650,8 @@ function ImGui.PopID() window.IDStack:pop_back() end +-- This is one of the very rare legacy case where we use ImGuiWindow methods, +-- it should ideally be flattened at some point but it's been used a lots by widgets. --- @param id string|int --- @return ImGuiID @@ -6190,7 +7671,7 @@ function MT.ImGuiWindow:GetID(id) return h end --- This is only used in rare/specific situations to manufacture an ID out of nowhere +-- This is only used in rare/specific situations to manufacture an ID out of nowhere. -- FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those? --- @param p_abs ImVec2 --- @return ImGuiID @@ -6221,6 +7702,9 @@ function ImGui.GetID(str_or_int, str_end) return window:GetID(str_or_int) end +-- Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call +-- (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level. +-- for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more) -- Overloads: GetIDWithSeed(str, str_end, seed) / GetIDWithSeed(n, seed) function ImGui.GetIDWithSeed(a, b, c) local id @@ -6263,6 +7747,7 @@ end --- @param user_flags ImGuiHoveredFlags --- @param shared_flags ImGuiHoveredFlags local function ApplyHoverFlagsForTooltip(user_flags, shared_flags) + -- Allow instance flags to override shared flags if bit32.band(user_flags, bit32.bor(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.DelayNormal)) ~= 0 then shared_flags = bit32.band(shared_flags, bit32.bnot(bit32.bor(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.DelayNormal))) end @@ -6275,6 +7760,7 @@ function ImGui.MarkItemEdited(id) -- ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data. local g = GImGui + -- IM_ASSERT(g.LastItemData.ID == id) -- Failing cases include: "widgets_inputtext_scrolling", "widgets_inputtext_multiline_status", "widgets_selectable_input" = case of e.g TempInputText() overlayed manually with different ID (#2718) g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal) if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited) ~= 0 then return @@ -6337,6 +7823,9 @@ function ImGui.IsWindowContentHoverable(window, flags) return true end +-- This is roughly matching the behavior of internal-facing ItemHoverable() +-- - we allow hovering to be true when ActiveId==window.MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() +-- - this should work even for non-interactive items that have no ID, so we cannot use LastItemId --- @param flags? ImGuiHoveredFlags function ImGui.IsItemHovered(flags) @@ -6358,6 +7847,7 @@ function ImGui.IsItemHovered(flags) flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav) end else + -- Test for bounding box overlap, as updated as ItemAdd() local status_flags = g.LastItemData.StatusFlags if bit32.band(status_flags, ImGuiItemStatusFlags.HoveredRect) == 0 then return false @@ -6367,19 +7857,31 @@ function ImGui.IsItemHovered(flags) flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse) end + -- Done with rectangle culling so we can perform heavier checks now + -- Test if we are hovering the right window (our window could be behind another window) + -- [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851) + -- [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable + -- to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was + -- the test that has been running for a long while. if g.HoveredWindow ~= window and bit32.band(status_flags, ImGuiItemStatusFlags.HoveredWindow) == 0 then if bit32.band(flags, ImGuiHoveredFlags.AllowWhenOverlappedByWindow) == 0 then return false end end + -- Test if another item is active (e.g. being dragged) local id = g.LastItemData.ID if bit32.band(flags, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) == 0 then if g.ActiveId ~= 0 and g.ActiveId ~= id and not g.ActiveIdAllowOverlap and not g.ActiveIdFromShortcut then + -- 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. local cancel_is_hovered = true if g.ActiveId == window.MoveId and (id == 0 or g.ActiveIdDisabledId == id) then cancel_is_hovered = false end + -- When ActiveId == TabId it means user clicked docking tab for the window. if g.ActiveId == window.TabId then cancel_is_hovered = false end @@ -6389,18 +7891,25 @@ function ImGui.IsItemHovered(flags) end end + -- Test if interactions on this window are blocked by an active popup or modal. + -- The ImGuiHoveredFlags.AllowWhenBlockedByPopup flag will be tested here. if not ImGui.IsWindowContentHoverable(window, flags) and bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoWindowHoverableCheck) == 0 then return false end + -- Test if the item is disabled if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.Disabled) ~= 0 and bit32.band(flags, ImGuiHoveredFlags.AllowWhenDisabled) == 0 then return false end + -- Special handling for calling after Begin() which represent the title bar or tab. + -- When the window is skipped/collapsed (SkipItems==true) that last item (always .MoveId submitted by Begin) + -- will never be overwritten so we need to detect the case. if id == window.MoveId and window.WriteAccessed then return false end + -- Test if using AllowOverlap and overlapped if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowOverlap) ~= 0 and id ~= 0 then if bit32.band(flags, ImGuiHoveredFlags.AllowWhenOverlappedByItem) == 0 then if g.HoveredIdPreviousFrame ~= g.LastItemData.ID then @@ -6410,6 +7919,8 @@ function ImGui.IsItemHovered(flags) end end + -- Handle hover delay + -- (some ideas: https://www.nngroup.com/articles/timing-exposing-content) local delay = CalcDelayFromHoveredFlags(flags) if delay > 0.0 or bit32.band(flags, ImGuiHoveredFlags.Stationary) ~= 0 then local hover_delay_id @@ -6423,6 +7934,9 @@ function ImGui.IsItemHovered(flags) end g.HoverItemDelayId = hover_delay_id + -- When changing hovered item we requires a bit of stationary delay before activating hover timer, + -- but once unlocked on a given item we also moving. + -- if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); } if bit32.band(flags, ImGuiHoveredFlags.Stationary) ~= 0 and g.HoverItemUnlockedStationaryId ~= hover_delay_id then return false end @@ -6435,6 +7949,13 @@ function ImGui.IsItemHovered(flags) return true end +-- 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: +-- - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'. +-- - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags.None) unless you want to benefit from special behavior handled by ItemHoverable. --- @param bb ImRect --- @param id ImGuiID --- @param item_flags ImGuiItemFlags @@ -6443,6 +7964,8 @@ function ImGui.ItemHoverable(bb, id, item_flags) local g = GImGui local 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) if not IMGUI_DISABLE_DEBUG_TOOLS then if id ~= 0 and g.HoveredIdPreviousFrame == id and bit32.band(item_flags, ImGuiItemFlags.AllowDuplicateId) == 0 then g.HoveredIdPreviousFrameItemCount = g.HoveredIdPreviousFrameItemCount + 1 @@ -6470,18 +7993,24 @@ end end end + -- We are done with rectangle culling so we can perform heavier checks now. if (bit32.band(item_flags, ImGuiItemFlags.NoWindowHoverableCheck) == 0) and not ImGui.IsWindowContentHoverable(window, ImGuiHoveredFlags.None) then g.HoveredIdIsDisabled = true return false end + -- We exceptionally allow this function to be called with id==0 to allow using it for easy high-level + -- hover test in widgets code. We could also decide to split this function is two. if id ~= 0 then + -- Drag source doesn't report as hovered if g.DragDropActive and g.DragDropPayload.SourceId == id and (bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceNoDisableHover) == 0) then return false end ImGui.SetHoveredID(id) + -- AllowOverlap mode (rarely used) requires previous frame HoveredId to be nil or to match. + -- This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test. if bit32.band(item_flags, ImGuiItemFlags.AllowOverlap) ~= 0 then g.HoveredIdAllowOverlap = true if g.HoveredIdPreviousFrame ~= id then @@ -6489,6 +8018,8 @@ end end end + -- Display shortcut (only works with mouse) + -- (ImGuiItemStatusFlags.HasShortcut in LastItemData denotes we want a tooltip) if id == g.LastItemData.ID and (bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasShortcut) ~= 0) and g.ActiveId ~= id then if ImGui.IsItemHovered(bit32.bor(ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.DelayNormal)) then ImGui.SetTooltip("%s", ImGui.GetKeyChordName(g.LastItemData.Shortcut)) @@ -6496,6 +8027,7 @@ end end end + -- When disabled we'll return false but still set HoveredId if bit32.band(item_flags, ImGuiItemFlags.Disabled) ~= 0 then -- Release active id if turning disabled if g.ActiveId == id and id ~= 0 then @@ -6512,6 +8044,8 @@ end return true end +-- FIXME: This is inlined/duplicated in ItemAdd() +-- FIXME: The id ~= 0 path is not used by our codebase, may get rid of it? --- @param bb ImRect --- @param id ImGuiID --- @return bool @@ -6528,6 +8062,8 @@ function ImGui.IsClippedEx(bb, id) return false end +-- This is also inlined in ItemAdd() +-- Note: if ImGuiItemStatusFlags.HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect. --- @param item_id ImGuiID --- @param item_flags ImGuiItemFlags --- @param status_flags ImGuiItemStatusFlags @@ -6552,6 +8088,10 @@ function ImGui.SetLastItemDataForWindow(window, rect) end end +-- Pass in translated ASCII characters for text input. +-- - with glfw you can get those from the callback set in glfwSetCharCallback() +-- - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message +-- FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API --- @param c unsigned_int function MT.ImGuiIO:AddInputCharacter(c) IM_ASSERT(self.Ctx ~= nil) @@ -6571,6 +8111,8 @@ function MT.ImGuiIO:AddInputCharacter(c) g.InputEventsQueue:push_back(e) end +-- UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so +-- we should save the high surrogate. --- @param c ImWchar16 function MT.ImGuiIO:AddInputCharacterUTF16(c) if (c == 0 and self.InputQueueSurrogate == 0) or not self.AppAcceptingEvents then @@ -6587,11 +8129,11 @@ function MT.ImGuiIO:AddInputCharacterUTF16(c) local cp = c if self.InputQueueSurrogate ~= 0 then - if bit32.band(c, 0xFC00) ~= 0xDC00 then -- Invalid low surrogate + if bit32.band(c, 0xFC00) ~= 0xDC00 then -- Invalid low surrogate self:AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID) else -- #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF - cp = IM_UNICODE_CODEPOINT_INVALID + cp = IM_UNICODE_CODEPOINT_INVALID -- Codepoint will not fit in ImWchar -- #endif end @@ -6600,12 +8142,14 @@ function MT.ImGuiIO:AddInputCharacterUTF16(c) self:AddInputCharacter(cp) end +-- Clear all incoming events. function MT.ImGuiIO:ClearEventsQueue() IM_ASSERT(self.Ctx ~= nil) local g = GImGui g.InputEventsQueue:clear() end +-- Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. function MT.ImGuiIO:ClearInputKeys() local g = self.Ctx for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do @@ -6621,7 +8165,7 @@ function MT.ImGuiIO:ClearInputKeys() self.KeyAlt = false self.KeySuper = false self.KeyMods = ImGuiMod_None - self.InputQueueCharacters:resize(0) + self.InputQueueCharacters:resize(0) -- Behavior of old ClearInputCharacters(). end function MT.ImGuiIO:ClearInputMouse() @@ -6668,18 +8212,25 @@ function MT.ImGuiIO:FindLatestInputEvent(ctx, type, arg) return nil end +-- Queue a new key down/up event. +-- - ImGuiKey key: Translated key (as in, generally ImGuiKey.A matches the key end-user would use to emit an 'A' character) +-- - bool down: Is the key down? use false to signify a key release. +-- - float analog_value: 0.0f..1.0f +-- IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE. +-- WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT. --- @param key ImGuiKey --- @param down bool --- @param analog_value float function MT.ImGuiIO:AddKeyAnalogEvent(key, down, analog_value) + -- if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); } IM_ASSERT(self.Ctx ~= nil) if key == ImGuiKey.None or not self.AppAcceptingEvents then return end local g = self.Ctx - IM_ASSERT(ImGui.IsNamedKeyOrMod(key)) - IM_ASSERT(ImGui.IsAliasKey(key) == false) + IM_ASSERT(ImGui.IsNamedKeyOrMod(key)) -- Backend needs to pass a valid ImGuiKey constant. 0..511 values are legacy native key codes which are not accepted by this API. + IM_ASSERT(ImGui.IsAliasKey(key) == false) -- Backend cannot submit ImGuiKey.MouseXXX values they are automatically inferred from AddMouseXXX() events. -- MacOS: swap Cmd(Super) and Ctrl if (g.IO.ConfigMacOSXBehaviors) then @@ -6692,6 +8243,7 @@ function MT.ImGuiIO:AddKeyAnalogEvent(key, down, analog_value) end end + -- Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed) local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.Key, key) local key_data = ImGui.GetKeyData(g, key) local latest_key_down = latest_event and latest_event.Key.Down or key_data.Down @@ -6700,6 +8252,7 @@ function MT.ImGuiIO:AddKeyAnalogEvent(key, down, analog_value) return end + -- Add event local e = ImGuiInputEvent() e.Type = ImGuiInputEventType.Key e.Source = ImGui.IsGamepadKey(key) and ImGuiInputSource.Gamepad or ImGuiInputSource.Keyboard @@ -6721,11 +8274,14 @@ function MT.ImGuiIO:AddKeyEvent(key, down) self:AddKeyAnalogEvent(key, down, (down and 1.0 or 0.0)) end +-- 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. --- @param accepting_events bool function MT.ImGuiIO:SetAppAcceptingEvents(accepting_events) self.AppAcceptingEvents = accepting_events end +-- This is not a real event, the data is latched in order to be stored in actual Mouse events. +-- This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes. --- @param source ImGuiMouseSource function MT.ImGuiIO:AddMouseSourceEvent(source) IM_ASSERT(self.Ctx ~= nil) @@ -6737,7 +8293,7 @@ end function MT.ImGuiIO:AddMouseViewportEvent(viewport_id) IM_ASSERT(self.Ctx ~= nil) local g = self.Ctx - -- IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags.HasMouseHoveredViewport); + -- IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags.HasMouseHoveredViewport) if (not self.AppAcceptingEvents) then return end @@ -6767,6 +8323,7 @@ function MT.ImGuiIO:AddFocusEvent(focused) IM_ASSERT(self.Ctx ~= nil) local g = self.Ctx + -- Filter duplicate local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.Focus) local latest_focused = latest_event and latest_event.AppFocused.Focused or (not g.IO.AppFocusLost) if latest_focused == focused or (self.ConfigDebugIgnoreFocusLoss and not focused) then @@ -6782,6 +8339,7 @@ function MT.ImGuiIO:AddFocusEvent(focused) g.InputEventsQueue:push_back(e) end +-- Queue a mouse move event --- @param x float --- @param y float function MT.ImGuiIO:AddMousePosEvent(x, y) @@ -6792,6 +8350,7 @@ function MT.ImGuiIO:AddMousePosEvent(x, y) local g = self.Ctx + -- Apply same flooring as UpdateMouseInputs() local x_val = x if x > -FLT_MAX then x_val = ImFloor(x) @@ -6801,6 +8360,7 @@ function MT.ImGuiIO:AddMousePosEvent(x, y) y_val = ImFloor(y) end + -- Filter duplicate local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.MousePos) local latest_pos = latest_event and ImVec2(latest_event.MousePos.PosX, latest_event.MousePos.PosY) or self.MousePos if latest_pos.x == x_val and latest_pos.y == y_val then @@ -6838,6 +8398,7 @@ function MT.ImGuiIO:AddMouseButtonEvent(mouse_button, down) end end + -- Filter duplicate local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.MouseButton, mouse_button) local latest_button_down = latest_event and latest_event.MouseButton.Down or self.MouseDown[mouse_button] if latest_button_down == down then @@ -6869,11 +8430,13 @@ function MT.ImGuiIO:AddMouseButtonEvent(mouse_button, down) g.InputEventsQueue:push_back(e) end +-- Queue a mouse wheel event (some mouse/API may only have a Y component) --- @param wheel_x float --- @param wheel_y float function MT.ImGuiIO:AddMouseWheelEvent(wheel_x, wheel_y) IM_ASSERT(self.Ctx ~= nil) local g = self.Ctx + -- Filter duplicate (unlike most events, wheel values are relative and easy to filter) if not self.AppAcceptingEvents or (wheel_x == 0 and wheel_y == 0) then return end @@ -6890,6 +8453,73 @@ function MT.ImGuiIO:AddMouseWheelEvent(wheel_x, wheel_y) g.InputEventsQueue:push_back(e) end +------------------------------------------------------------------------------- +-- [SECTION] INPUTS +------------------------------------------------------------------------------- +-- - GetModForLRModKey() [Internal] +-- - FixupKeyChord() [Internal] +-- - GetKeyData() [Internal] +-- - GetKeyIndex() [Internal] +-- - GetKeyName() +-- - GetKeyChordName() [Internal] +-- - CalcTypematicRepeatAmount() [Internal] +-- - GetTypematicRepeatRate() [Internal] +-- - GetKeyPressedAmount() [Internal] +-- - GetKeyMagnitude2d() [Internal] +------------------------------------------------------------------------------- +-- - UpdateKeyRoutingTable() [Internal] +-- - GetRoutingIdFromOwnerId() [Internal] +-- - GetShortcutRoutingData() [Internal] +-- - CalcRoutingScore() [Internal] +-- - SetShortcutRouting() [Internal] +-- - TestShortcutRouting() [Internal] +------------------------------------------------------------------------------- +-- - IsKeyDown() +-- - IsKeyPressed() +-- - IsKeyReleased() +------------------------------------------------------------------------------- +-- - IsMouseDown() +-- - IsMouseClicked() +-- - IsMouseReleased() +-- - IsMouseDoubleClicked() +-- - GetMouseClickedCount() +-- - GetItemClickedCountWithSingleClickDelay() +-- - IsMouseHoveringRect() [Internal] +-- - IsMouseDragPastThreshold() [Internal] +-- - IsMouseDragging() +-- - GetMousePos() +-- - SetMousePos() [Internal] +-- - GetMousePosOnOpeningCurrentPopup() +-- - IsMousePosValid() +-- - IsAnyMouseDown() +-- - GetMouseDragDelta() +-- - ResetMouseDragDelta() +-- - GetMouseCursor() +-- - SetMouseCursor() +------------------------------------------------------------------------------- +-- - UpdateAliasKey() +-- - GetMergedModsFromKeys() +-- - UpdateKeyboardInputs() +-- - UpdateMouseInputs() +------------------------------------------------------------------------------- +-- - LockWheelingWindow [Internal] +-- - FindBestWheelingWindow [Internal] +-- - UpdateMouseWheel() [Internal] +------------------------------------------------------------------------------- +-- - SetNextFrameWantCaptureKeyboard() +-- - SetNextFrameWantCaptureMouse() +------------------------------------------------------------------------------- +-- - GetInputSourceName() [Internal] +-- - DebugPrintInputEvent() [Internal] +-- - UpdateInputEvents() [Internal] +------------------------------------------------------------------------------- +-- - GetKeyOwner() [Internal] +-- - TestKeyOwner() [Internal] +-- - SetKeyOwner() [Internal] +-- - SetItemKeyOwner() [Internal] +-- - Shortcut() [Internal] +------------------------------------------------------------------------------- + --- @param key ImGuiKey local function GetModForLRModKey(key) if key == ImGuiKey.LeftCtrl or key == ImGuiKey.RightCtrl then @@ -6909,6 +8539,7 @@ end --- @param key_chord ImGuiKeyChord function ImGui.FixupKeyChord(key_chord) + -- Add ImGuiMod_XXXX when a corresponding ImGuiKey.LeftXXX/ImGuiKey.RightXXX is specified. local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if ImGui.IsLRModKey(key) then key_chord = bit32.bor(key_chord, GetModForLRModKey(key)) @@ -6922,6 +8553,7 @@ end function ImGui.GetKeyData(ctx, key) if ctx == nil then ctx = GImGui end + -- Special storage location for mods if bit32.band(key, ImGuiMod_Mask_) ~= 0 then key = ImGui.ConvertSingleModFlagToKey(key) end @@ -6931,6 +8563,7 @@ function ImGui.GetKeyData(ctx, key) return ctx.IO.KeysData[idx], idx end +-- Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey.GamepadLStick* values). --- @param key_left ImGuiKey --- @param key_right ImGuiKey --- @param key_up ImGuiKey @@ -6942,6 +8575,10 @@ function ImGui.GetKeyMagnitude2d(key_left, key_right, key_up, key_down) ) end +-- TestKeyOwner(..., ID) : (owner == None || owner == ID) +-- TestKeyOwner(..., None) : (owner == None) +-- TestKeyOwner(..., Any) : no owner test +-- All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags.LockXXX flags. --- @param key ImGuiKey --- @param owner_id ImGuiID function ImGui.TestKeyOwner(key, owner_id) @@ -6961,6 +8598,9 @@ function ImGui.TestKeyOwner(key, owner_id) return not owner_data.LockThisFrame end + -- Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId + -- are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things. + -- Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions. if owner_data.OwnerCurr ~= owner_id then if owner_data.LockThisFrame then return false @@ -6973,6 +8613,8 @@ function ImGui.TestKeyOwner(key, owner_id) return true end +-- Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes. +-- Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey.A) (>= 1.87) --- @param key ImGuiKey --- @param owner_id? ImGuiID function ImGui.IsKeyDown(key, owner_id) @@ -7012,6 +8654,7 @@ function ImGui.IsKeyReleased(key, owner_id) return true end +-- Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat. --- @param key ImGuiKey --- @param flags ImGuiInputFlags --- @param owner_id? ImGuiID @@ -7021,8 +8664,7 @@ function ImGui.IsKeyPressedEx(key, flags, owner_id) local g = GImGui local key_data = ImGui.GetKeyData(g, key) - -- In theory this should already be encoded as (DownDuration < 0.0), but testing this facilitates eating mechanism (until we finish work on key ownership) - if not key_data.Down then + if not key_data.Down then -- In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership) return false end local t = key_data.DownDuration @@ -7065,6 +8707,7 @@ function ImGui.IsKeyPressedEx(key, flags, owner_id) end -- TODO: +-- Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super. function ImGui.GetKeyChordName(key_chord) local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if ImGui.IsLRModKey(key) then @@ -7081,6 +8724,7 @@ function ImGui.GetKeyChordName(key_chord) return s end +-- Those names are provided for debugging purpose and are not meant to be saved persistently nor compared. local GKeyNames = { "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown", "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape", @@ -7141,6 +8785,10 @@ function ImGui.GetKeyOwner(key) return owner_id end +-- t0 = previous time (e.g.: g.Time - g.IO.DeltaTime) +-- t1 = current time (e.g.: g.Time) +-- An event is triggered at: +-- t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N --- @param t0 float --- @param t1 float --- @param repeat_delay float @@ -7184,6 +8832,8 @@ function ImGui.GetTypematicRepeatRate(flags) else repeat_delay = g.IO.KeyRepeatDelay * 1.00; repeat_rate = g.IO.KeyRepeatRate * 1.00; return repeat_delay, repeat_rate end end +-- Return value representing the number of presses in the last time period, for the given repeat rate +-- (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate) --- @param key ImGuiKey --- @param repeat_delay float --- @param repeat_rate float @@ -7197,6 +8847,10 @@ function ImGui.GetKeyPressedAmount(key, repeat_delay, repeat_rate) return ImGui.CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate) end +-- Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data. +-- Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D +-- Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6 +-- See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation. --- @param rt ImGuiKeyRoutingTable function ImGui.UpdateKeyRoutingTable(rt) local g = GImGui --[[@as ImGuiContext]] @@ -7209,19 +8863,22 @@ function ImGui.UpdateKeyRoutingTable(rt) repeat routing_entry = rt.Entries[old_routing_idx] routing_entry.RoutingCurrScore = routing_entry.RoutingNextScore - routing_entry.RoutingCurr = routing_entry.RoutingNext + routing_entry.RoutingCurr = routing_entry.RoutingNext -- Update entry routing_entry.RoutingNext = ImGuiKeyOwner_NoOwner routing_entry.RoutingNextScore = 0 if routing_entry.RoutingCurr == ImGuiKeyOwner_NoOwner then break end - rt.EntriesNext:push_back(routing_entry) + rt.EntriesNext:push_back(routing_entry) -- Write alive ones into new buffer + -- Apply routing to owner if there's no owner already (RoutingCurr == None at this point) + -- This is the result of previous frame's SetShortcutRouting() call. if routing_entry.Mods == g.IO.KeyMods then local owner_data = ImGui.GetKeyOwnerData(g, key) if owner_data.OwnerCurr == ImGuiKeyOwner_NoOwner then owner_data.OwnerCurr = routing_entry.RoutingCurr + -- IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr); end end @@ -7230,15 +8887,16 @@ function ImGui.UpdateKeyRoutingTable(rt) old_routing_idx = routing_entry.NextEntryIndex end + -- Rewrite linked-list rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] = (new_routing_start_idx <= rt.EntriesNext.Size and new_routing_start_idx or -1) for n = new_routing_start_idx, rt.EntriesNext.Size do rt.EntriesNext[n].NextEntryIndex = (n + 1 <= rt.EntriesNext.Size) and (n + 1) or -1 end end - rt.Entries:swap(rt.EntriesNext) + rt.Entries:swap(rt.EntriesNext) -- Swap new and old indexes end --- owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope() +-- owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope(). --- @param owner_id ImGuiID local function GetRoutingIdFromOwnerId(owner_id) local g = GImGui @@ -7248,6 +8906,12 @@ end --- @param key_chord ImGuiKeyChord --- @return ImGuiKeyRoutingData function ImGui.GetShortcutRoutingData(key_chord) + -- Majority of shortcuts will be Key + any number of Mods + -- We accept _Single_ mod with ImGuiKey.None. + -- - Shortcut(ImGuiKey.S | ImGuiMod_Ctrl) -- Legal + -- - Shortcut(ImGuiKey.S | ImGuiMod_Ctrl | ImGuiMod_Shift) -- Legal + -- - Shortcut(ImGuiMod_Ctrl) -- Legal + -- - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift) -- Not legal local g = GImGui local rt = g.KeysRoutingTable local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) @@ -7257,6 +8921,8 @@ function ImGui.GetShortcutRoutingData(key_chord) end IM_ASSERT(ImGui.IsNamedKey(key)) + -- Get (in the majority of case, the linked list will have one element so this should be 2 reads. + -- Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame). local routing_data local idx = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] while idx ~= -1 do @@ -7268,32 +8934,51 @@ function ImGui.GetShortcutRoutingData(key_chord) idx = routing_data.NextEntryIndex end + -- Add to linked-list local routing_data_idx = rt.Entries.Size + 1 rt.Entries:push_back(ImGuiKeyRoutingData()) routing_data = rt.Entries[routing_data_idx] routing_data.Mods = mods - routing_data.NextEntryIndex = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] + routing_data.NextEntryIndex = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] -- Setup linked list rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] = routing_data_idx return routing_data end +-- Current score encoding +-- - 0: Never route +-- - 1: ImGuiInputFlags.RouteGlobal (lower priority) +-- - 100..199: ImGuiInputFlags.RouteFocused (if window in focus-stack) +-- 200: ImGuiInputFlags.RouteGlobal | ImGuiInputFlags.RouteOverFocused +-- 300: ImGuiInputFlags.RouteActive or ImGuiInputFlags.RouteFocused (if item active) +-- 400: ImGuiInputFlags.RouteGlobal | ImGuiInputFlags.RouteOverActive +-- - 500..599: ImGuiInputFlags.RouteFocused | ImGuiInputFlags.RouteOverActive (if window in focus-stack) (higher priority) +-- 'flags' should include an explicit routing policy --- @param focus_scope_id ImGuiID --- @param owner_id ImGuiID --- @param flags ImGuiInputFlags local function CalcRoutingScore(focus_scope_id, owner_id, flags) local g = GImGui if bit32.band(flags, ImGuiInputFlags.RouteFocused) ~= 0 then + -- ActiveID gets high priority + -- (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it) if owner_id ~= 0 and g.ActiveId == owner_id then return 300 end + -- Score based on distance to focused window (lower is better) + -- Assuming both windows are submitting a routing request, + -- - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match) + -- - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best) + -- Assuming only WindowA is submitting a routing request, + -- - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score. + -- This essentially follow the window.ParentWindowForFocusRoute chain. if focus_scope_id == 0 then return 0 end for index_in_focus_path = 1, g.NavFocusRoute.Size do if g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id then - if bit32.band(flags, ImGuiInputFlags.RouteOverActive) ~= 0 then + if bit32.band(flags, ImGuiInputFlags.RouteOverActive) ~= 0 then -- && g.ActiveId != 0 && g.ActiveId != owner_id) return 599 - (index_in_focus_path - 1) else return 199 - (index_in_focus_path - 1) @@ -7322,16 +9007,22 @@ local function CalcRoutingScore(focus_scope_id, owner_id, flags) return 0 end +-- - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active +-- e.g. ImGuiKey.G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey.G can be. +-- - This is also used by UpdateInputEvents() to avoid trickling in the most common case of e.g. pressing ImGuiKey.G also emitting a G character. --- @param key_chord ImGuiKeyChord local function IsKeyChordPotentiallyCharInput(key_chord) + -- Mimic 'ignore_char_inputs' logic in InputText() local g = GImGui + -- When the right mods are pressed it cannot be a char input so we won't filter the shortcut out. local mods = bit32.band(key_chord, ImGuiMod_Mask_) local ignore_char_inputs = ((bit32.band(mods, ImGuiMod_Ctrl) ~= 0) and (bit32.band(mods, ImGuiMod_Alt) == 0)) or (g.IO.ConfigMacOSXBehaviors and (bit32.band(mods, ImGuiMod_Ctrl) ~= 0)) if ignore_char_inputs then return false end + -- Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered. local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if key == ImGuiKey.None then return false @@ -7339,6 +9030,11 @@ local function IsKeyChordPotentiallyCharInput(key_chord) return g.KeysMayBeCharInput:TestBit(key + 1) -- TestBit requires 1-based index end +-- Request a desired route for an input chord (key + mods). +-- Return true if the route is available this frame. +-- - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state. +-- (Conceptually this does a "Submit for next frame" + "Test for current frame". +-- As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.) --- @param key_chord ImGuiKeyChord --- @param flags ImGuiInputFlags --- @param owner_id ImGuiID @@ -7358,8 +9054,10 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiInputFlags.RouteGlobal, ImGuiInputFlags.RouteFocused)) ~= 0) end + -- Add ImGuiMod_XXXX when a corresponding ImGuiKey.LeftXXX/ImGuiKey.RightXXX is specified. key_chord = ImGui.FixupKeyChord(key_chord) + -- [DEBUG] Debug break requested by user if g.DebugBreakInShortcutRouting == key_chord then -- IM_DEBUG_BREAK() end @@ -7370,21 +9068,29 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) end end + -- Note how ImGuiInputFlags.RouteAlways won't set routing and thus won't set owner. May want to rework this? if bit32.band(flags, ImGuiInputFlags.RouteAlways) ~= 0 then -- IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register", ImGui.GetKeyChordName(key_chord), flags, owner_id) return true end + -- Specific culling when there's an active item. if g.ActiveId ~= 0 and g.ActiveId ~= owner_id then if bit32.band(flags, ImGuiInputFlags.RouteActive) ~= 0 then return false end + -- Cull shortcuts with no modifiers when it could generate a character. + -- e.g. Shortcut(ImGuiKey.G) also generates 'g' character, should not trigger when InputText() is active. + -- but Shortcut(Ctrl+G) should generally trigger when InputText() is active. + -- TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active. + -- (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined) if g.IO.WantTextInput and IsKeyChordPotentiallyCharInput(key_chord) then -- IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input", ImGui.GetKeyChordName(key_chord), flags, owner_id) return false end + -- ActiveIdUsingAllKeyboardKeys trumps all for ActiveId if bit32.band(flags, ImGuiInputFlags.RouteOverActive) == 0 and g.ActiveIdUsingAllKeyboardKeys then local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if key == ImGuiKey.None then @@ -7396,9 +9102,10 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) end end + -- Where do we evaluate route for? local focus_scope_id = g.CurrentFocusScopeId if bit32.band(flags, ImGuiInputFlags.RouteFromRootWindow) ~= 0 then - focus_scope_id = g.CurrentWindow.RootWindow.ID + focus_scope_id = g.CurrentWindow.RootWindow.ID -- See PushFocusScope() call in Begin() end local score = CalcRoutingScore(focus_scope_id, owner_id, flags) @@ -7407,18 +9114,23 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) return false end + -- Submit routing for NEXT frame (assuming score is sufficient) + -- FIXME: Could expose a way to use a "serve last" policy for same score resolution (using >= instead of >). local routing_data = ImGui.GetShortcutRoutingData(key_chord) + -- const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score >= routing_data->RoutingNextScore) : (score > routing_data->RoutingNextScore); if score > routing_data.RoutingNextScore then routing_data.RoutingNext = owner_id routing_data.RoutingNextScore = score end + -- Return routing state for CURRENT frame if routing_data.RoutingCurr == owner_id then -- IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route") end return routing_data.RoutingCurr == owner_id end +-- We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position. --- @param mouse_pos? ImVec2 function ImGui.IsMousePosValid(mouse_pos) local MOUSE_INVALID = -256000.0 @@ -7427,6 +9139,7 @@ function ImGui.IsMousePosValid(mouse_pos) return p.x >= MOUSE_INVALID and p.y >= MOUSE_INVALID end +-- [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. --- @return bool function ImGui.IsAnyMouseDown() local g = GImGui @@ -7445,7 +9158,7 @@ function ImGui.IsMouseDown(button, owner_id) local g = GImGui IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown) - return g.IO.MouseDown[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) + return g.IO.MouseDown[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) -- Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array. end --- @param button ImGuiMouseButton @@ -7466,14 +9179,14 @@ function ImGui.IsMouseClickedEx(button, flags, owner_id) local g = GImGui IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown) - if not g.IO.MouseDown[button] then + if not g.IO.MouseDown[button] then -- In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership) return false end local t = g.IO.MouseDownDuration[button] if t < 0.0 then return false end - IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedByIsMouseClicked)) == 0) + IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedByIsMouseClicked)) == 0) -- Passing flags not supported by this function! -- FIXME: Could support RepeatRate and RepeatUntil flags here. local is_repeat = (bit32.band(flags, ImGuiInputFlags.Repeat) ~= 0) local pressed = (t == 0.0) or (is_repeat and t > g.IO.KeyRepeatDelay and ImGui.CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0) @@ -7496,10 +9209,13 @@ function ImGui.IsMouseReleased(button, owner_id) local g = GImGui IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown) - return g.IO.MouseReleased[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) + return g.IO.MouseReleased[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) -- Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id) end +-- Prefer higher-level helper GetItemClickedCountWithSingleClickDelay() -- 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. --- @param button ImGuiMouseButton --- @param delay? float function ImGui.IsMouseReleasedWithDelay(button, delay) @@ -7551,6 +9267,22 @@ local function LastItemOverlayButtonForNullId(mouse_button) return id end +-- [BETA] Building block for disambiguation between single-click and double-click. +-- - Returns 1 on single-click but delayed by io.MouseSingleClickDelay (which is always > io.MouseDoubleClickTime) after mouse release. +-- - Returns 2+ on double-click and subsequent repeated clicks. +-- In order use that to replicate Windows Explorer's "click on label to rename after a delay", +-- When the function returns 1 for a delayed single click, you can add with further tests: +-- - If you want to test that the mouse position AT THE TIME of the click (before the delay): you can use the 'io.MouseClickedPos[mouse_button]' position. +-- - If you want to test that the mouse position is still over the item at the end of delay: you can use '&& IsItemHovered()'. +-- - If you want to test that the item was selected or the sole selection AT THE TIME of the click (before the delay): you can test for 'g.LastActiveIdWasSelected' or 'g.LastActiveIdWasSoleSelected'. +-- e.g. +-- local click_count = ImGui.GetItemClickedCountWithSingleClickDelay(mouse_button) +-- if click_count == 1 and ImGui.GetCurrentContext().LastActiveIdWasSoleSelected then +-- StartRename() +-- end +-- if click_count == 2 then +-- Launch() +-- end --- @param mouse_button? ImGuiMouseButton --- @param delay? float --- @return int @@ -7594,6 +9326,8 @@ function ImGui.GetMousePosOnOpeningCurrentPopup() end -- Return the delta from the initial clicking position while the mouse button is clicked or was just released. +-- This is locked and return 0.0f until the mouse moves past a distance threshold at least once. +-- NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window. --- @param button? ImGuiMouseButton --- @param lock_threshold? float --- @return ImVec2 @@ -7628,11 +9362,18 @@ do local key_changed_mask = ImBitArray(ImGuiKey.NamedKey_COUNT) +-- Process input queue +-- We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'. +-- - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost) +-- - trickle_fast_inputs = true : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87) --- @param trickle_fast_inputs bool function ImGui.UpdateInputEvents(trickle_fast_inputs) local g = GImGui local io = g.IO + -- Only trickle chars<>key when working with InputText() + -- FIXME: InputText() could parse event trail? + -- FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters) local trickle_interleaved_nonchar_keys_and_text = trickle_fast_inputs and g.WantTextInputNextFrame == 1 local mouse_moved = false @@ -7653,7 +9394,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) if g.IO.WantSetMousePos then break end - + -- Trickling Rule: Stop processing queued events if we already handled a mouse button change if trickle_fast_inputs and (mouse_button_changed ~= 0 or mouse_wheeled or key_changed or text_inputted) then stop_3231 = true; break end @@ -7662,12 +9403,13 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) io.MouseSource = e.MousePos.MouseSource mouse_moved = true elseif e.Type == ImGuiInputEventType.MouseButton then + -- Trickling Rule: Stop processing queued events if we got multiple action on the same button local button = e.MouseButton.Button IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT) if trickle_fast_inputs and ((bit32.band(mouse_button_changed, bit32.lshift(1, button)) ~= 0) or mouse_wheeled) then stop_3231 = true; break end - if trickle_fast_inputs and e.MouseButton.MouseSource == ImGuiMouseSource.TouchScreen and mouse_moved then + if trickle_fast_inputs and e.MouseButton.MouseSource == ImGuiMouseSource.TouchScreen and mouse_moved then -- #2702: TouchScreen have no initial hover. stop_3231 = true; break end @@ -7675,6 +9417,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) io.MouseSource = e.MouseButton.MouseSource mouse_button_changed = bit32.bor(mouse_button_changed, bit32.lshift(1, button)) elseif e.Type == ImGuiInputEventType.MouseWheel then + -- Trickling Rule: Stop processing queued events if we got multiple action on the event if trickle_fast_inputs and (mouse_moved or mouse_button_changed ~= 0) then stop_3231 = true; break end @@ -7706,7 +9449,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) stop_3231 = true; break end - if key_data.Down ~= e.Key.Down then + if key_data.Down ~= e.Key.Down then -- 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 + 1) if trickle_interleaved_nonchar_keys_and_text and not key_is_potentially_for_char_input then @@ -7720,7 +9463,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoKeyboard) ~= 0 then break end - + -- Trickling Rule: Stop processing queued events if keys/mouse have been interacted with if trickle_fast_inputs and (mouse_button_changed ~= 0 or mouse_moved or mouse_wheeled) then stop_3231 = true; break end @@ -7733,6 +9476,8 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) text_inputted = true end elseif e.Type == ImGuiInputEventType.Focus then + -- We intentionally overwrite this and process in NewFrame(), in order to give a chance + -- to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame. local focus_lost = not e.AppFocused.Focused io.AppFocusLost = focus_lost else @@ -7745,6 +9490,9 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) event_n = event_n + 1 end + -- Remaining events will be processed on the next frame + -- FIXME-MULTITHREADING: io.AddKeyEvent() etc. calls are mostly thread-safe apart from the fact they push to this + -- queue which may be resized here. Could potentially rework this to narrow down the section needing a mutex? (#5772) if event_n == g.InputEventsQueue.Size + 1 then g.InputEventsQueue:resize(0) else @@ -7753,6 +9501,10 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) end end + -- Clear buttons state when focus is lost + -- - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle. + -- - we clear in EndFrame() and not now in order allow application/user code polling this flag + -- (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event). if g.IO.AppFocusLost then g.IO:ClearInputKeys() g.IO:ClearInputMouse() @@ -7761,6 +9513,12 @@ end end +-- _LockXXX flags are useful to lock keys away from code which is not input-owner aware. +-- When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone. +-- - SetKeyOwner(..., None) : clears owner +-- - SetKeyOwner(..., Any, !Lock) : illegal (assert) +-- - SetKeyOwner(..., Any or None, Lock) : set lock +-- Ownership is automatically released on the frame after a release, see code in UpdateKeyboardInputs(). --- @param key ImGuiKey --- @param owner_id ImGuiID --- @param flags? ImGuiInputFlags @@ -7770,11 +9528,14 @@ function ImGui.SetKeyOwner(key, owner_id, flags) local g = GImGui --- @cast g ImGuiContext IM_ASSERT(ImGui.IsNamedKeyOrMod(key) and (owner_id ~= ImGuiKeyOwner_Any or (bit32.band(flags, bit32.bor(ImGuiInputFlags.LockThisFrame, ImGuiInputFlags.LockUntilRelease)) ~= 0)), "Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)") IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetKeyOwner)) == 0, "Passing flags not supported by this function!") + -- IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags) local owner_data = ImGui.GetKeyOwnerData(g, key) owner_data.OwnerCurr = owner_id owner_data.OwnerNext = owner_id + -- We cannot lock by default as it would likely break lots of legacy code. + -- In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data.Down test) owner_data.LockUntilRelease = (bit32.band(flags, ImGuiInputFlags.LockUntilRelease) ~= 0) owner_data.LockThisFrame = (bit32.band(flags, ImGuiInputFlags.LockThisFrame) ~= 0) or owner_data.LockUntilRelease end @@ -7803,6 +9564,12 @@ function ImGui.SetKeyOwnersForKeyChord(key_chord, owner_id, flags) end end +-- This is more or less equivalent to a fancier version of: +-- if (IsItemHovered() || IsItemActive()) +-- SetKeyOwner(key, GetItemID()); +-- Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times. +-- More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition. +-- Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority. --- @param key ImGuiKey --- @param flags? ImGuiInputFlags function ImGui.SetItemKeyOwner(key, flags) @@ -7817,7 +9584,7 @@ function ImGui.SetItemKeyOwner(key, flags) flags = bit32.bor(flags, ImGuiInputFlags.CondDefault_) end if (g.HoveredId == id and bit32.band(flags, ImGuiInputFlags.CondHovered) ~= 0) or (g.ActiveId == id and bit32.band(flags, ImGuiInputFlags.CondActive) ~= 0) then - IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetItemKeyOwner)) == 0) + IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetItemKeyOwner)) == 0) -- Passing flags not supported by this function! if not ImGui.TestKeyOwner(key, id) then return false end @@ -7827,6 +9594,7 @@ function ImGui.SetItemKeyOwner(key, flags) return false end +-- This is equivalent to comparing KeyMods + doing a IsKeyPressed() --- @param key_chord ImGuiKeyChord --- @param flags ImGuiInputFlags --- @param owner_id ImGuiID @@ -7865,7 +9633,7 @@ end --- @param owner_id ImGuiID function ImGui.Shortcut(key_chord, flags, owner_id) local g = GImGui - -- IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)", ImGui.GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id) + -- IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", ImGui.GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id) -- When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any. if bit32.band(flags, ImGuiInputFlags.RouteTypeMask_) == 0 then @@ -7913,6 +9681,9 @@ end --- @param window ImGuiWindow --- @nodiscard local function CalcWindowMinSize(window) + -- We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) + -- FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller. + -- Perhaps should tend further a neater test for this. local g = GImGui local size_min = ImVec2() @@ -7943,6 +9714,7 @@ local function CalcWindowMinSize(window) end end + -- Reduce artifacts with very small windows local window_for_height = window size_min.y = ImMax(size_min.y, window_for_height.TitleBarHeight + window_for_height.MenuBarHeight + ImMax(0, g.Style.WindowRounding - 1)) @@ -7960,6 +9732,7 @@ local function CalcWindowSizeAfterConstraint(window, size_desired) ImVec2_Copy(new_size, size_desired) if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) ~= 0 then + -- See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max. local cr = ImRect() ImRect_Copy(cr, g.NextWindowData.SizeConstraintRect) @@ -7979,6 +9752,7 @@ local function CalcWindowSizeAfterConstraint(window, size_desired) new_size.y = IM_TRUNC(new_size.y) end + -- Minimum size local size_min = CalcWindowMinSize(window) return ImMax(new_size, size_min) end @@ -8021,6 +9795,8 @@ local function CalcWindowAutoFitSize(window, size_contents, axis_mask) size_desired.x = (bit32.band(axis_mask, 1) ~= 0) and (size_contents.x + size_pad.x + decoration_w_without_scrollbars) or window.Size.x size_desired.y = (bit32.band(axis_mask, 2) ~= 0) and (size_contents.y + size_pad.y + decoration_h_without_scrollbars) or window.Size.y + -- Determine maximum window size + -- Child windows are laid within their parent (unless they are also popups/menus) and thus have no restriction local size_max = ImVec2(FLT_MAX, FLT_MAX) if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0 or bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then if not window.ViewportOwned then @@ -8033,13 +9809,16 @@ local function CalcWindowAutoFitSize(window, size_contents, axis_mask) end if bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0 then + -- Tooltip always resize (up to maximum size) return ImMin(size_desired, size_max) else local size_min = CalcWindowMinSize(window) local size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max) + -- When the window cannot fit all contents (either because of constraints, either because screen is too small), + -- we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. local size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit) - local size_contents_for_scrollbar_x = (bit32.band(axis_mask, 1) ~= 0) and size_contents.x or window.ContentSize.x + local size_contents_for_scrollbar_x = (bit32.band(axis_mask, 1) ~= 0) and size_contents.x or window.ContentSize.x -- See #9352. In theory this should use same logic as `window.ScrollbarY = ...` codepath in Begin(). Needs some plumbling. local size_contents_for_scrollbar_y = (bit32.band(axis_mask, 2) ~= 0) and size_contents.y or window.ContentSize.y local will_have_scrollbar_x = (size_auto_fit_after_constraint.x < size_contents_for_scrollbar_x + size_pad.x + decoration_w_without_scrollbars and bit32.band(window.Flags, ImGuiWindowFlags.NoScrollbar) == 0 and bit32.band(window.Flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0) or bit32.band(window.Flags, ImGuiWindowFlags.AlwaysHorizontalScrollbar) ~= 0 local will_have_scrollbar_y = (size_auto_fit_after_constraint.y < size_contents_for_scrollbar_y + size_pad.y + decoration_h_without_scrollbars and bit32.band(window.Flags, ImGuiWindowFlags.NoScrollbar) == 0) or bit32.band(window.Flags, ImGuiWindowFlags.AlwaysVerticalScrollbar) ~= 0 @@ -8085,7 +9864,7 @@ local function CalcResizePosSizeFromAnyCorner(window, corner_target_arg, corner_ local corner_target = ImVec2() ImVec2_Copy(corner_target, corner_target_arg) - if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then + if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then -- Clamp resizing of childs within parent local parent_window = window.ParentWindow local parent_flags = parent_window.Flags @@ -8100,8 +9879,8 @@ local function CalcResizePosSizeFromAnyCorner(window, corner_target_arg, corner_ corner_target.y = ImClamp(corner_target.y, limit_rect.Min.y, limit_rect.Max.y) end end - local pos_min = ImLerp(corner_target, window.Pos, corner_norm) - local pos_max = ImLerp(window.Pos + window.Size, corner_target, corner_norm) + local pos_min = ImLerp(corner_target, window.Pos, corner_norm) -- Expected window upper-left + local pos_max = ImLerp(window.Pos + window.Size, corner_target, corner_norm) -- Expected window lower-right local size_expected = pos_max - pos_min local size_constrained = CalcWindowSizeAfterConstraint(window, size_expected) @@ -8116,6 +9895,9 @@ local function CalcResizePosSizeFromAnyCorner(window, corner_target_arg, corner_ return out_pos, size_constrained end +-- Handle resize for: Resize Grips, Borders, Gamepad +-- Return true when using auto-fit (double-click on resize grip) +-- Returns (ret_auto_fit_mask, border_hovered, border_held) --- @param window ImGuiWindow --- @param resize_grip_count int --- @param resize_grip_col table @@ -8131,7 +9913,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c if (bit32.band(flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0 and bit32.band(window.ChildFlags, bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY)) == 0) then return 0, -1, -1 end - if window.WasActive == false then + if window.WasActive == false then -- Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window. return 0, -1, -1 end @@ -8153,7 +9935,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c -- This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it. -- - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow. -- - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold). - -- We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. + -- We only clip interaction so we overwrite window.ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. local clip_with_viewport_rect = bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasMouseHoveredViewport) == 0 or g.IO.MouseHoveredViewport ~= window.ViewportId or bit32.band(window.Viewport.Flags, ImGuiViewportFlags.NoDecoration) == 0 if (clip_with_viewport_rect) then ImRect_Copy(window.ClipRect, window.Viewport:GetMainRect()) @@ -8174,35 +9956,41 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c local corner = ImVec2(window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y) + -- Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window local resize_rect = ImRect(corner - inner_dir * grip_hover_outer_size, corner + inner_dir * grip_hover_inner_size) if resize_rect.Min.x > resize_rect.Max.x then resize_rect.Min.x, resize_rect.Max.x = resize_rect.Max.x, resize_rect.Min.x end if resize_rect.Min.y > resize_rect.Max.y then resize_rect.Min.y, resize_rect.Max.y = resize_rect.Max.y, resize_rect.Min.y end - local resize_grip_id = window:GetID(resize_grip_n) + local resize_grip_id = window:GetID(resize_grip_n) -- == GetWindowResizeCornerID() ImGui.ItemAdd(resize_rect, resize_grip_id, nil, ImGuiItemFlags.NoNav) local _, hovered, held = ImGui.ButtonBehavior(resize_rect, resize_grip_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus)) + -- GetForegroundDrawList(window):AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)) if hovered or held then ImGui.SetMouseCursor((bit32.band(resize_grip_n, 1) ~= 0) and ImGuiMouseCursor.ResizeNESW or ImGuiMouseCursor.ResizeNWSE) end if held and g.IO.MouseDoubleClicked[0] then + -- Auto-fit when double-clicking local size_auto_fit = CalcWindowAutoFitSize(window, window.ContentSizeIdeal, -1) size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit) - ret_auto_fit_mask = 0x03 + ret_auto_fit_mask = 0x03 -- Both axes ImGui.ClearActiveID() elseif held then + -- Resize from any of the four corners + -- We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position local clamp_min = ImVec2((corner_pos.x == 1.0) and clamp_rect.Min.x or -FLT_MAX, (corner_pos.y == 1.0) and clamp_rect.Min.y or -FLT_MAX) local clamp_max = ImVec2((corner_pos.x == 0.0) and clamp_rect.Max.x or FLT_MAX, (corner_pos.y == 0.0) and clamp_rect.Max.y or FLT_MAX) - local corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN) + local corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN) -- Corner of the window corresponding to our corner grip corner_target = ImClamp(corner_target, clamp_min, clamp_max) pos_target, size_target = CalcResizePosSizeFromAnyCorner(window, corner_target, corner_pos) end + -- Only lower-left grip is visible before hovering/activating local resize_grip_visible = held or hovered or (resize_grip_n == 0 and bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0) if resize_grip_visible then local color @@ -8243,9 +10031,10 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c end local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding) - local border_id = window:GetID(border_n + 4) + local border_id = window:GetID(border_n + 4) -- == GetWindowResizeBorderID() ImGui.ItemAdd(border_rect, border_id, nil, ImGuiItemFlags.NoNav) local _, hovered, held = ImGui.ButtonBehavior(border_rect, border_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus)) + -- GetForegroundDrawList(window):AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)) if hovered and g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER then hovered = false @@ -8265,6 +10054,9 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c end ImGui.ClearActiveID() elseif held then + -- Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop. + -- Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually. + -- FIXME: May want to generalize this idiom at lower-level, so more widgets can use it! local just_scrolled_manually_while_resizing = (g.WheelingWindow ~= nil and g.WheelingWindowScrolledFrame == g.FrameCount and ImGui.IsWindowChildOf(window, g.WheelingWindow, false, true)) if g.ActiveIdIsJustActivated or just_scrolled_manually_while_resizing then g.WindowResizeBorderExpectedRect = border_rect @@ -8279,7 +10071,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c local border_target_rel_mode_for_axis local border_target_abs_mode_for_axis border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis] - border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding -- Match ButtonBehavior() padding above + border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding -- Match ButtonBehavior() padding above. -- Use absolute mode position local border_target = ImVec2() @@ -8289,12 +10081,14 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c -- Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position. local ignore_resize = false if g.WindowResizeRelativeMode then + -- GetForegroundDrawList():AddText(GetMainViewport().WorkPos, IM_COL32_WHITE, "Relative Mode") border_target[axis] = border_target_rel_mode_for_axis if g.IO.MouseDelta[axis] == 0.0 or ((g.IO.MouseDelta[axis] > 0.0) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis)) then ignore_resize = true end end + -- Clamp, apply local clamp_min = ImVec2((border_n == ImGuiDir.Right) and clamp_rect.Min.x or -FLT_MAX, (border_n == ImGuiDir.Down or (border_n == ImGuiDir.Up and window_move_from_title_bar)) and clamp_rect.Min.y or -FLT_MAX) local clamp_max = ImVec2((border_n == ImGuiDir.Left) and clamp_rect.Max.x or FLT_MAX, (border_n == ImGuiDir.Up) and clamp_rect.Max.y or FLT_MAX) border_target = ImClamp(border_target, clamp_min, clamp_max) @@ -8314,8 +10108,10 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c end ImGui.PopID() + -- Restore nav layer window.DC.NavLayerCurrent = ImGuiNavLayer.Main + -- Apply back modified position/size to window if size_target.x ~= FLT_MAX and (window.Size.x ~= size_target.x or window.SizeFull.x ~= size_target.x) then window.Size.x = size_target.x window.SizeFull.x = size_target.x @@ -8334,6 +10130,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c window.Pos.y = ImFloor(pos_target.y) end + -- Recalculate next expected border expected coordinates if border_held ~= -1 then g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, border_held, grip_hover_inner_size, g.WindowsBorderHoverPadding) end @@ -8352,14 +10149,26 @@ function ImGui.CalcWrapWidthForPos(pos, wrap_pos_x) local g = GImGui local window = g.CurrentWindow if wrap_pos_x == 0.0 then + -- We could decide to setup a default wrapping max point for auto-resizing windows, + -- or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function? + -- if (window.Hidden and (window.Flags & ImGuiWindowFlags.AlwaysAutoResize)) + -- wrap_pos_x = ImMax(window.WorkRect.Min.x + g.FontSize * 10.0, window.WorkRect.Max.x) + -- else wrap_pos_x = window.WorkRect.Max.x elseif wrap_pos_x > 0.0 then - wrap_pos_x = wrap_pos_x + window.Pos.x - window.Scroll.x + wrap_pos_x = wrap_pos_x + window.Pos.x - window.Scroll.x -- wrap_pos_x is provided is window local space end return ImMax(wrap_pos_x - pos.x, 1.0) end +------------------------------------------------------------------------------- +-- [SECTION] RENDER HELPERS +-- Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change, +-- we need a nicer separation between low-level functions and high-level functions relying on the ImGui context. +-- Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context. +------------------------------------------------------------------------------- + --- @param text ImString --- @param text_end int? --- @return int # Exclusive upper bound @@ -8377,6 +10186,8 @@ function ImGui.FindRenderedTextEnd(text, text_end) return text_display_end end +-- Internal ImGui functions to render text +-- RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() --- @param pos ImVec2 --- @param text string --- @param text_begin int? @@ -8396,7 +10207,7 @@ function ImGui.RenderText(pos, text, text_begin, text_end, hide_text_after_hash) text_display_end = ImGui.FindRenderedTextEnd(text, text_end) else if text_end == nil then - text_end = #text + 1 + text_end = #text + 1 -- FIXME-OPT (not reached by our internal calls) end text_display_end = text_end end @@ -8418,7 +10229,7 @@ function ImGui.RenderTextWrapped(pos, text, text_end, wrap_width) local window = g.CurrentWindow if text_end == nil then - text_end = #text + 1 + text_end = #text + 1 -- FIXME-OPT (not reached by our internal calls) end if text ~= "" then @@ -8426,6 +10237,12 @@ function ImGui.RenderTextWrapped(pos, text, text_end, wrap_width) end 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, 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. +-- DOES NOT CALL LogRenderedText(), unlike RenderTextClipped!!! --- @param draw_list ImDrawList --- @param pos_min ImVec2 --- @param pos_max ImVec2 @@ -8439,6 +10256,7 @@ end function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin, text_display_end, text_size_if_known, align, clip_rect) if not align then align = ImVec2(0, 0) end + -- Perform CPU side clipping for single clipped element to avoid using scissor state local pos = ImVec2() ImVec2_Copy(pos, pos_min) @@ -8447,13 +10265,15 @@ function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin local clip_min = clip_rect and clip_rect.Min or pos_min local clip_max = clip_rect and clip_rect.Max or pos_max local need_clipping = (pos.x + text_size.x >= clip_max.x) or (pos.y + text_size.y >= clip_max.y) - if (clip_rect) then + if (clip_rect) then -- If we had no explicit clipping rectangle then pos==clip_min need_clipping = need_clipping or ((pos.x < clip_min.x) or (pos.y < clip_min.y)) end + -- Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. if (align.x > 0.0) then pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x) end if (align.y > 0.0) then pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y) end + -- Render local g = GImGui if (need_clipping) then local fine_clip_rect = ImVec4(clip_min.x, clip_min.y, clip_max.x, clip_max.y) @@ -8473,6 +10293,7 @@ end function ImGui.RenderTextClipped(pos_min, pos_max, text, text_end, text_size_if_known, align, clip_rect) if not align then align = ImVec2(0, 0) end + -- Hide anything after a '##' string local text_display_end = ImGui.FindRenderedTextEnd(text, text_end) local text_len = text_display_end - 1 @@ -8507,6 +10328,8 @@ function ImGui.RenderNavCursor(bb, id, flags, rounding) return end + -- We don't early out on 'window.Flags & ImGuiWindowFlags.NoNavInputs' because it would be inconsistent with + -- other code directly checking NavCursorVisible. Instead we aim for NavCursorVisible to always be false. local window = g.CurrentWindow if window.DC.NavHideHighlightOneFrame then return @@ -8519,7 +10342,7 @@ function ImGui.RenderNavCursor(bb, id, flags, rounding) local display_rect = ImRect() ImRect_Copy(display_rect, bb) display_rect:ClipWith(window.ClipRect) - local scale_factor = ImGui.GetScale() + local scale_factor = ImGui.GetScale() -- FIXME-DPI local thickness = ImTrunc(ImMax(2.0, 1.5 * scale_factor)) if bit32.band(flags, ImGuiNavRenderCursorFlags.Compact) ~= 0 then window.DrawList:AddRect(display_rect.Min, display_rect.Max, ImGui.GetColorU32(ImGuiCol.NavCursor), rounding, thickness) @@ -8552,13 +10375,14 @@ local uv_fill = {ImVec2(), ImVec2()} --- @param col_shadow ImU32 function ImGui.RenderMouseCursor(base_pos, base_scale, mouse_cursor, col_fill, col_border, col_shadow) local g = GImGui - if mouse_cursor <= ImGuiMouseCursor.None or mouse_cursor >= ImGuiMouseCursor.COUNT then -- We intentionally accept out of bound values + if mouse_cursor <= ImGuiMouseCursor.None or mouse_cursor >= ImGuiMouseCursor.COUNT then -- We intentionally accept out of bound values. mouse_cursor = ImGuiMouseCursor.Arrow end local font_atlas = g.DrawListSharedData.FontAtlas for _, viewport in g.Viewports:iter() do repeat + -- We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor. if not ImFontAtlasGetMouseCursorTexData(font_atlas, mouse_cursor, offset, size, uv_border, uv_fill) then break end @@ -8590,9 +10414,10 @@ end end ---- Another overly complex function until we reorganize everything into a nice all-in-one helper. ---- This is made more complex because we have dissociated the layout rectangle (pos_min .. pos_max) 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. +-- 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) 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. +-- (BREAKING) On 2025/04/16 we removed the 'float clip_max_x' parameters which was preceding 'float ellipsis_max' and was the same value for 99% of users. --- @param draw_list ImDrawList --- @param pos_min ImVec2 --- @param pos_max ImVec2 @@ -8615,8 +10440,8 @@ function ImGui.RenderTextEllipsis(draw_list, pos_min, pos_max, ellipsis_max_x, t text_size = ImGui.CalcTextSize(text, text_end_full, false, 0.0) end - -- 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)) + -- draw_list:AddLineV(pos_max.x, pos_min.y - 4, pos_max.y + 6, IM_COL32(0, 0, 255, 255)) + -- draw_list:AddLineV(ellipsis_max_x, pos_min.y - 2, 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 then @@ -8652,6 +10477,7 @@ function ImGui.RenderTextEllipsis(draw_list, pos_min, pos_max, ellipsis_max_x, t end end +-- Render a rectangle shaped with optional rounding and borders --- @param p_min ImVec2 --- @param p_max ImVec2 --- @param fill_col ImU32 @@ -8720,7 +10546,7 @@ local function RenderWindowOuterBorders(window) if border_size > 0.0 and (bit32.band(window.Flags, ImGuiWindowFlags.NoBackground) == 0) then window.DrawList:AddRect(window.Pos, window.Pos + window.Size, border_col, window.WindowRounding, window.WindowBorderSize, 0) elseif border_size > 0.0 then - if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 then + if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 then -- Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border. RenderWindowOuterSingleBorder(window, 1, border_col, border_size) end if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0 then @@ -8731,7 +10557,7 @@ local function RenderWindowOuterBorders(window) if window.ResizeBorderHovered ~= -1 or window.ResizeBorderHeld ~= -1 then local border_n = (window.ResizeBorderHeld ~= -1) and window.ResizeBorderHeld or window.ResizeBorderHovered local border_col_resizing = ImGui.GetColorU32((window.ResizeBorderHeld ~= -1) and ImGuiCol.SeparatorActive or ImGuiCol.SeparatorHovered) - RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0, window.WindowBorderSize)) + RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0, window.WindowBorderSize)) -- Thicker than usual end if g.Style.FrameBorderSize > 0 and (bit32.band(window.Flags, ImGuiWindowFlags.NoTitleBar) == 0) and not window.DockIsActive then @@ -8740,6 +10566,8 @@ local function RenderWindowOuterBorders(window) end end +-- Draw background and borders +-- Draw and handle scrollbars --- @param window ImGuiWindow --- @param title_bar_rect ImRect --- @param title_bar_is_highlight bool @@ -8751,10 +10579,13 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high local style = g.Style local flags = window.Flags + -- 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. local window_rounding = window.WindowRounding local window_border_size = window.WindowBorderSize if window.Collapsed then + -- Title bar only local backup_border_size = style.FrameBorderSize g.Style.FrameBorderSize = window.WindowBorderSize @@ -8765,6 +10596,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high -- Window background if bit32.band(flags, ImGuiWindowFlags.NoBackground) == 0 then local bg_col = ImGui.GetColorU32(GetWindowBgColorIdx(window)) + -- Adjust alpha. For docking local override_alpha = false local alpha = 1.0 @@ -8774,9 +10606,13 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end if override_alpha then - bg_col = bit32.band(bg_col, bit32.bnot(IM_COL32_A_MASK)) or bit32.lshift(IM_F32_TO_INT8_SAT(alpha), IM_COL32_A_SHIFT) + bg_col = bit32.bor(bit32.band(bg_col, bit32.bnot(IM_COL32_A_MASK)), bit32.lshift(IM_F32_TO_INT8_SAT(alpha), IM_COL32_A_SHIFT)) end + -- Render, for docked windows and host windows we ensure BG goes before decorations + if window.DockIsActive then window.DockNode.LastBgColor = bg_col end + if bit32.band(flags, ImGuiWindowFlags.DockNodeHost) ~= 0 then bg_col = 0 end + if bit32.band(bg_col, IM_COL32_A_MASK) ~= 0 then local bg_rect = ImRect(window.Pos + ImVec2(0, window.TitleBarHeight), window.Pos + window.Size) local bg_rounding_flags @@ -8794,6 +10630,8 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high if window.DockIsActive then window.DockNode.IsBgDrawnThisFrame = true end -- Title bar + -- (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag, + -- in order for their pos/size to be matching their undocking state.) if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and not window.DockIsActive then local title_bar_col = ImGui.GetColorU32(title_bar_is_highlight and ImGuiCol.TitleBgActive or ImGuiCol.TitleBg) window.DrawList:AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags.RoundCornersTop) @@ -8802,7 +10640,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high -- Menu bar if bit32.band(flags, ImGuiWindowFlags.MenuBar) ~= 0 then local menu_bar_rect = window:MenuBarRect() - menu_bar_rect:ClipWith(window:Rect()) + menu_bar_rect:ClipWith(window:Rect()) -- Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. window.DrawList:AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, ImGui.GetColorU32(ImGuiCol.MenuBarBg), (bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0) and window_rounding or 0.0, ImDrawFlags.RoundCornersTop) if style.FrameBorderSize > 0.0 and menu_bar_rect.Max.y < window.Pos.y + window.Size.y then window.DrawList:AddLineH(menu_bar_rect.Min.x + window_border_size * 0.5, menu_bar_rect.Max.x - window_border_size * 0.5, menu_bar_rect.Max.y, ImGui.GetColorU32(ImGuiCol.Border), style.FrameBorderSize) @@ -8822,12 +10660,15 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high if pressed then node.WantHiddenTabBarToggle = true elseif held and ImGui.IsMouseDragging(0) then - ImGui.StartMouseMovingWindowOrNode(window, node, true) + ImGui.StartMouseMovingWindowOrNode(window, node, true) -- Undock from tab-bar triangle = same as window/collapse menu button end + + -- FIXME-DOCK: Ideally we'd use ImGuiCol.TitleBgActive/ImGuiCol.TitleBg here, but neither is guaranteed to be visible enough at this sort of size.. local col = ImGui.GetColorU32(((held and hovered) or (node.IsFocused and not hovered)) and ImGuiCol.ButtonActive or (hovered and ImGuiCol.ButtonHovered or ImGuiCol.Button)) window.DrawList:AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0), p + ImVec2(0.0, unhide_sz_draw), col) end + -- Scrollbars if window.ScrollbarX then ImGui.Scrollbar(ImGuiAxis.X) end @@ -8835,7 +10676,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high ImGui.Scrollbar(ImGuiAxis.Y) end - -- Resize grip(s) + -- Render resize grips (after their input handling so we don't have a frame of latency) if handle_borders_and_resize_grips and (bit32.band(flags, ImGuiWindowFlags.NoResize) == 0) then for resize_grip_n = 1, #ImGuiResizeGripDef do repeat @@ -8856,6 +10697,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end end + -- Borders (for dock node host they will be rendered over after the tab bar) if handle_borders_and_resize_grips and not window.DockNodeAsHost then RenderWindowOuterBorders(window) end @@ -8865,6 +10707,9 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders +-- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. +-- Render title text, collapse button, close button +-- Returns the updated 'open' value (nil when there is no close button) --- @param window ImGuiWindow --- @param title_bar_rect ImRect --- @param name string @@ -8878,10 +10723,14 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) local has_close_button = (open ~= nil) local has_collapse_button = bit32.band(flags, ImGuiWindowFlags.NoCollapse) == 0 and (style.WindowMenuButtonPosition ~= ImGuiDir.None) + -- Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) + -- FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags.NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref? local item_flags_backup = g.CurrentItemFlags g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.NoNavDefaultFocus) window.DC.NavLayerCurrent = ImGuiNavLayer.Menu + -- Layout buttons + -- FIXME: Would be nice to generalize the subtleties expressed here into reusable code. local pad_l = g.Style.FramePadding.x local pad_r = g.Style.FramePadding.x local button_sz = g.FontSize @@ -8900,12 +10749,14 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) pad_l = pad_l + button_sz + style.ItemInnerSpacing.x end + -- Collapse button (submitting first so it gets priority when choosing a navigation init fallback) if has_collapse_button then if ImGui.CollapseButton(window:GetID("#COLLAPSE"), collapse_button_pos) then window.WantCollapseToggle = true -- Defer actual collapsing to next frame as we are too far in the Begin() function end end + -- Close button if has_close_button then local backup_item_flags = g.CurrentItemFlags g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.NoFocus) @@ -8918,9 +10769,13 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) window.DC.NavLayerCurrent = ImGuiNavLayer.Main g.CurrentItemFlags = item_flags_backup + -- Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) + -- FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. local marker_size_x = (bit32.band(flags, ImGuiWindowFlags.UnsavedDocument) ~= 0) and (button_sz * 0.80) or 0.0 local text_size = ImGui.CalcTextSize(name, nil, true) + ImVec2(marker_size_x, 0.0) + -- As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, + -- while uncentered title text will still reach edges correctly. if (pad_l > style.FramePadding.x) then pad_l = pad_l + g.Style.ItemInnerSpacing.x end @@ -8928,7 +10783,7 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) pad_r = pad_r + g.Style.ItemInnerSpacing.x end if (style.WindowTitleAlign.x > 0.0 and style.WindowTitleAlign.x < 1.0) then - local centerness = ImSaturate(1.0 - ImFabs(style.WindowTitleAlign.x - 0.5) * 2.0) + local centerness = ImSaturate(1.0 - ImFabs(style.WindowTitleAlign.x - 0.5) * 2.0) -- 0.0 on either edges, 1.0 on center local pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect:GetWidth() - pad_l - pad_r - text_size.x) pad_l = ImMax(pad_l, pad_extend * centerness) pad_r = ImMax(pad_r, pad_extend * centerness) @@ -8946,7 +10801,8 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - math.floor(marker_size_x * 0.5)) end end - + -- if (g.IO.KeyShift) window.DrawList:AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)) -- [DEBUG] + -- if (g.IO.KeyCtrl) window.DrawList:AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)) -- [DEBUG] ImGui.RenderTextClipped(layout_r.Min, layout_r.Max, name, nil, text_size, style.WindowTitleAlign, clip_r) return open @@ -8972,7 +10828,7 @@ function ImGui.UpdateWindowParentAndRootLinks(window, flags, parent_window) if parent_window and (bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0) then window.RootWindowPopupTree = parent_window.RootWindowPopupTree end - if parent_window and (bit32.band(flags, ImGuiWindowFlags.Modal) == 0) and (bit32.band(flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0) then + if parent_window and (bit32.band(flags, ImGuiWindowFlags.Modal) == 0) and (bit32.band(flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0) then -- FIXME: simply use _NoTitleBar ? window.RootWindowForTitleBarHighlight = parent_window.RootWindowForTitleBarHighlight end @@ -9015,10 +10871,10 @@ function ImGui.UpdateWindowSkipRefresh(window) window.SkipItems = true end -- FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused. - if window.Appearing then -- If currently appearing + if window.Appearing then -- If currently appearing return end - if window.Hidden then -- If was hidden (previous frame) + if window.Hidden then -- If was hidden (previous frame) return end if bit32.band(g.NextWindowData.RefreshFlagsVal, ImGuiWindowRefreshFlags.RefreshOnHover) ~= 0 and g.HoveredWindow then @@ -9081,6 +10937,11 @@ function ImGui.GcCompactTransientMiscBuffers() end end +-- Free up/compact internal window buffers, we can use this when a window becomes unused. +-- Not freed: +-- - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data) +-- This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost. +-- FIXME: Consider exposing of elaborating GC policy, e.g. being able to trim excessive ImDrawList gaps. (#9303) --- @param window ImGuiWindow function ImGui.GcCompactTransientWindowBuffers(window) window.MemoryCompacted = true @@ -9095,6 +10956,8 @@ end --- @param window ImGuiWindow function ImGui.GcAwakeTransientWindowBuffers(window) + -- We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening. + -- The other buffers tends to amortize much faster. window.MemoryCompacted = false window.DrawList.IdxBuffer:reserve(window.MemoryDrawListIdxCapacity) window.DrawList.VtxBuffer:reserve(window.MemoryDrawListVtxCapacity) @@ -9120,14 +10983,16 @@ function ImGui.SetWindowPos(window, pos, cond) end if cond == nil then cond = 0 end + -- Test condition (NB: bit 0 is always true) and clear flags for next time if (cond ~= 0) and (bit32.band(window.SetWindowPosAllowFlags, cond) == 0) then return end - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. window.SetWindowPosAllowFlags = bit32.band(window.SetWindowPosAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing))) ImVec2_Copy(window.SetWindowPosVal, ImVec2(FLT_MAX, FLT_MAX)) + -- Set local old_pos = ImVec2() ImVec2_Copy(old_pos, window.Pos) @@ -9140,9 +11005,9 @@ function ImGui.SetWindowPos(window, pos, cond) return end ImGui.MarkIniSettingsDirty(window) - - ImVec2_Copy(window.DC.CursorPos, window.DC.CursorPos + offset) - ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorMaxPos + offset) + -- FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here. + ImVec2_Copy(window.DC.CursorPos, window.DC.CursorPos + offset) -- As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorMaxPos + offset) -- And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected. ImVec2_Copy(window.DC.IdealMaxPos, window.DC.IdealMaxPos + offset) ImVec2_Copy(window.DC.CursorStartPos, window.DC.CursorStartPos + offset) end @@ -9160,13 +11025,15 @@ function ImGui.SetWindowSize(window, size, cond) end if cond == nil then cond = 0 end + -- Test condition (NB: bit 0 is always true) and clear flags for next time if ((cond ~= 0) and bit32.band(window.SetWindowSizeAllowFlags, cond) == 0) then return end - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. window.SetWindowSizeAllowFlags = bit32.band(window.SetWindowSizeAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing))) + -- Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags.AlwaysAutoResize) if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0 or window.Appearing or bit32.band(window.ChildFlags, ImGuiChildFlags.AlwaysAutoResize) ~= 0 then window.AutoFitFramesX = (size.x <= 0.0) and 2 or 0 end @@ -9174,6 +11041,7 @@ function ImGui.SetWindowSize(window, size, cond) window.AutoFitFramesY = (size.y <= 0.0) and 2 or 0 end + -- Set local old_size_x, old_size_y = window.SizeFull.x, window.SizeFull.y if size.x <= 0.0 then @@ -9200,6 +11068,7 @@ function ImGui.SetWindowCollapsed(window, collapsed, cond) window, collapsed, cond = GImGui.CurrentWindow, window, collapsed end if cond == nil then cond = 0 end + -- Test condition (NB: bit 0 is always true) and clear flags for next time if cond ~= 0 and bit32.band(window.SetWindowCollapsedAllowFlags, cond) == 0 then return end @@ -9276,7 +11145,7 @@ function ImGui.SetNextWindowPos(pos, cond, pivot) if pivot == nil then pivot = ImVec2(0, 0) end local g = GImGui - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) ImVec2_Copy(g.NextWindowData.PosVal, pos) @@ -9291,7 +11160,7 @@ function ImGui.SetNextWindowSize(size, cond) if cond == nil then cond = 0 end local g = GImGui - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ImVec2_Copy(g.NextWindowData.SizeVal, size) @@ -9330,6 +11199,9 @@ function ImGui.GetFont() return GImGui.Font end +-- 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) function ImGui.GetFontSize() return GImGui.FontSize end @@ -9378,7 +11250,7 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) child_flags = bit32.band(bit32.bor(child_flags, g.NextWindowData.ChildFlagsSet), bit32.bnot(g.NextWindowData.ChildFlagsClear)) end - -- Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument + -- Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument. local ImGuiChildFlags_SupportedMask_ = bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY, ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AutoResizeY, ImGuiChildFlags.AlwaysAutoResize, ImGuiChildFlags.FrameStyle, ImGuiChildFlags.NavFlattened) -- IM_UNUSED(ImGuiChildFlags_SupportedMask_) IM_ASSERT(bit32.band(child_flags, bit32.bnot(ImGuiChildFlags_SupportedMask_)) == 0, "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?") @@ -9398,7 +11270,7 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoDocking) window_flags = bit32.bor(window_flags, bit32.band(parent_window.Flags, ImGuiWindowFlags.NoMove)) -- Inherit the NoMove flag if bit32.band(child_flags, bit32.bor(ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AutoResizeY, ImGuiChildFlags.AlwaysAutoResize)) ~= 0 then - window_flags = bit32.bor(window_flags, ImGuiWindowFlags.AlwaysAutoResize) + window_flags = bit32.bor(window_flags, ImGuiWindowFlags.AlwaysAutoResize) -- FIXME: Would be sane to not make single-axis flag set this. (#9355) end if bit32.band(child_flags, bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY)) == 0 then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoSavedSettings) @@ -9415,15 +11287,15 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) end -- Forward size - -- Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags.ResizeXXX is set. + -- Important: Begin() has special processing to switch condition to ImGuiCond.FirstUseEver for a given axis when ImGuiChildFlags.ResizeXXX is set. -- (the alternative would to store conditional flags per axis, which is possible but more code) local size_avail = ImGui.GetContentRegionAvail() local size_default = ImVec2((bit32.band(child_flags, ImGuiChildFlags.AutoResizeX) ~= 0) and 0.0 or size_avail.x, (bit32.band(child_flags, ImGuiChildFlags.AutoResizeY) ~= 0) and 0.0 or size_avail.y) local size = ImGui.CalcItemSize(size_arg, size_default.x, size_default.y) -- 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. + -- (since the code in Begin() never supported SizeVal==0.0 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 bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ~= 0 and bit32.band(g.NextWindowData.SizeCond, ImGuiCond.Always) ~= 0 then if g.NextWindowData.SizeVal.x > 0.0 then size.x = g.NextWindowData.SizeVal.x @@ -9441,6 +11313,9 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) -- 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. -- e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it. local temp_window_name + -- if (name and parent_window.IDStack:back() == parent_window.ID) + -- temp_window_name = ImFormatString("%s/%s", parent_window.Name, name) -- May omit ID if in root of ID stack + -- else if name then temp_window_name = ImFormatString("%s/%s_%08X", parent_window.Name, name, id) else @@ -9490,6 +11365,7 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) end -- Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'. +-- ImGuiChildFlags.Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details! -- `true` is accepted as ImGuiChildFlags.Borders for legacy code. --- @param str_id_or_id string|ImGuiID --- @param size_arg? ImVec2 @@ -9537,6 +11413,8 @@ function ImGui.EndChild() end else -- Not navigable into + -- - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs. + -- - We could later decide to not apply this path if ImGuiChildFlags.FrameStyle or ImGuiChildFlags.Borders is set. ImGui.ItemAdd(bb, child_window.ChildId, nil, ImGuiItemFlags.NoNav) -- But when flattened we directly reach items, adjust active layer mask accordingly @@ -9548,6 +11426,7 @@ function ImGui.EndChild() g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end child_window.DC.ChildItemStatusFlags = g.LastItemData.StatusFlags + -- SetLastItemDataForChildWindowItem(child_window, child_window:Rect()) -- Not needed, effectively done by ItemAdd() else ImGui.SetLastItemDataForChildWindowItem(child_window, child_window:Rect()) end @@ -9593,6 +11472,7 @@ function ImGui.SetNextWindowFlags(flags, enabled) end -- Content size = inner scrollable rectangle, padded with WindowPadding. +-- SetNextWindowContentSize(ImVec2(100,100)) + ImGuiWindowFlags.AlwaysAutoResize will always allow submitting a 100x100 item. --- @param size ImVec2 function ImGui.SetNextWindowContentSize(size) local g = GImGui @@ -9612,7 +11492,7 @@ end function ImGui.SetNextWindowCollapsed(collapsed, cond) if cond == nil then cond = 0 end local g = GImGui - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasCollapsed) g.NextWindowData.CollapsedVal = collapsed g.NextWindowData.CollapsedCond = (cond ~= 0) and cond or ImGuiCond.Always @@ -9681,6 +11561,9 @@ end --- @param window ImGuiWindow function ImGui.StartMouseMovingWindow(window) + -- Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows. + -- We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward. + -- This is because we want ActiveId to be set even when the window is not permitted to move. local g = GImGui ImGui.FocusWindow(window) ImGui.SetActiveID(window.MoveId, window) @@ -9704,15 +11587,23 @@ function ImGui.StartMouseMovingWindow(window) end end +-- 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 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. function ImGui.UpdateMouseMovingWindowNewFrame() local g = GImGui if g.MovingWindow then + -- We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window). + -- We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow.MoveId for consistency. ImGui.KeepAliveID(g.ActiveId) IM_ASSERT(g.MovingWindow and g.MovingWindow.RootWindowDockTree) local moving_window = g.MovingWindow.RootWindowDockTree + -- When a window stop being submitted while being dragged, it may will its viewport until next Begin() local window_disappeared = (not moving_window.WasActive and not moving_window.Active) if g.IO.MouseDown[0] and ImGui.IsMousePosValid(g.IO.MousePos) and not window_disappeared then local pos = g.IO.MousePos - g.ActiveIdClickOffset @@ -9729,6 +11620,7 @@ function ImGui.UpdateMouseMovingWindowNewFrame() ImGui.ClearActiveID() end else + -- When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others. if (g.ActiveIdWindow and g.ActiveIdWindow.MoveId == g.ActiveId) then ImGui.KeepAliveID(g.ActiveId) @@ -9743,6 +11635,7 @@ function ImGui.GetDrawListSharedData() return GImGui.DrawListSharedData end +-- Supported flags: ImGuiPopupFlags.AnyPopupId, ImGuiPopupFlags.AnyPopupLevel --- @param id ImGuiID --- @param popup_flags ImGuiPopupFlags function ImGui.IsPopupOpen(id, popup_flags) @@ -9778,6 +11671,7 @@ function ImGui.IsPopupOpen(id, popup_flags) end end +-- Also see FindBlockingModal(nil) --- @return ImGuiWindow? function ImGui.GetTopMostPopupModal() local g = GImGui @@ -9792,6 +11686,9 @@ function ImGui.GetTopMostPopupModal() return nil end +-- Initiate focusing and moving window when clicking on empty space or title bar. +-- Initiate focusing window when clicking on a disabled item. +-- Handle left-click and right-click focus. function ImGui.UpdateMouseMovingWindowEndFrame() local g = GImGui @@ -9799,13 +11696,18 @@ function ImGui.UpdateMouseMovingWindowEndFrame() return end + -- Unless we just made a window/popup appear if g.NavWindow and g.NavWindow.Appearing then return end local hovered_window = g.HoveredWindow + -- Click on empty space to focus window and start moving + -- (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!) if ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) then + -- Handle the edge case of a popup being closed while clicking in its empty space. + -- If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. local hovered_root if hovered_window then hovered_root = hovered_window.RootWindow @@ -9818,8 +11720,11 @@ function ImGui.UpdateMouseMovingWindowEndFrame() if hovered_window ~= nil and not is_closed_popup and not is_queued_focus_request then ImGui.StartMouseMovingWindow(hovered_window) + -- FIXME: In principle we might be able to call StopMouseMovingWindow() below. + -- Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symmetrical, at the later doesn't clear ActiveId. + -- Cancel moving if clicked outside of title bar - if bit32.band(hovered_window.BgClickFlags, ImGuiWindowBgClickFlags.Move) == 0 then -- set by io.ConfigWindowsMoveFromTitleBarOnly + if bit32.band(hovered_window.BgClickFlags, ImGuiWindowBgClickFlags.Move) == 0 then -- set by io.ConfigWindowsMoveFromTitleBarOnly if bit32.band(hovered_root.Flags, ImGuiWindowFlags.NoTitleBar) == 0 then if not hovered_root:TitleBarRect():Contains(g.IO.MouseClickedPos[0]) then g.MovingWindow = nil @@ -9834,6 +11739,7 @@ function ImGui.UpdateMouseMovingWindowEndFrame() g.ActiveIdDisabledId = g.HoveredId end elseif hovered_window == nil and g.NavWindow ~= nil then + -- Clicking on void disable focus ImGui.FocusWindow(nil, ImGuiFocusRequestFlags.UnlessBelowModal) end end @@ -9850,6 +11756,8 @@ function ImGui.UpdateMouseMovingWindowEndFrame() end end +-- This is called during NewFrame()->UpdateViewportsNewFrame() only. +-- Need to keep in sync with SetWindowPos() --- @param window ImGuiWindow --- @param delta ImVec2 function ImGui.TranslateWindow(window, delta) @@ -9880,8 +11788,13 @@ function ImGui.FindWindowByName(name) return ImGui.FindWindowByID(id) end ---- Push a new Dear ImGui window to add widgets to. ---- - Passing a non-nil `open` displays a close button on the upper-right corner of the window +-- Push a new Dear ImGui window to add widgets to. +-- - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. +-- - Begin/End can be called multiple times during the frame with the same window name to append content. +-- - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). +-- You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. +-- - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui.End() even if false is returned. +-- - Passing a non-nil 'open' displays a Close button on the upper-right corner of the window, the returned 'is_open' value will be false when the button is pressed. --- @param name string --- @param open? bool --- @param flags? ImGuiWindowFlags @@ -9893,10 +11806,11 @@ function ImGui.Begin(name, open, flags) local g = GImGui local style = g.Style - IM_ASSERT(name ~= nil and name ~= "") - IM_ASSERT(g.WithinFrameScope) - IM_ASSERT(g.FrameCountEnded ~= g.FrameCount) + IM_ASSERT(name ~= nil and name ~= "") -- Window name required + IM_ASSERT(g.WithinFrameScope) -- Forgot to call ImGui.NewFrame() + IM_ASSERT(g.FrameCountEnded ~= g.FrameCount) -- Called ImGui.Render() or ImGui.EndFrame() and haven't called ImGui.NewFrame() again yet + -- Find or create local window = ImGui.FindWindowByName(name) local window_just_created = (window == nil) if window_just_created then @@ -9916,7 +11830,8 @@ function ImGui.Begin(name, open, flags) local first_begin_of_the_frame = (window.LastFrameActive ~= current_frame) window.IsFallbackWindow = (g.CurrentWindowStack.Size == 0 and g.WithinFrameScopeWithImplicitWindow) - local window_just_activated_by_user = (window.LastFrameActive < (current_frame - 1)) + -- Update the Appearing flag (note: the BeginDocked() path may also set this to true later) + local window_just_activated_by_user = (window.LastFrameActive < (current_frame - 1)) -- Not using !WasActive because the implicit "Debug" window would always toggle off->on if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then local popup_ref = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1] window_just_activated_by_user = window_just_activated_by_user or (window.PopupId ~= popup_ref.PopupId) -- We recycle popups so treat window as activated if popup id changed @@ -9963,7 +11878,7 @@ function ImGui.Begin(name, open, flags) flags = window.Flags if window.DockIsActive then IM_ASSERT(window.DockNode ~= nil) - g.NextWindowData.HasFlags = bit32.band(g.NextWindowData.HasFlags, bit32.bnot(ImGuiNextWindowDataFlags.HasSizeConstraint)) + g.NextWindowData.HasFlags = bit32.band(g.NextWindowData.HasFlags, bit32.bnot(ImGuiNextWindowDataFlags.HasSizeConstraint)) -- Docking currently override constraints end -- Amend the Appearing flag @@ -9974,6 +11889,7 @@ function ImGui.Begin(name, open, flags) end end + -- Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack local parent_window_in_stack if window.DockIsActive and window.DockNode.HostWindow then parent_window_in_stack = window.DockNode.HostWindow @@ -9993,6 +11909,7 @@ function ImGui.Begin(name, open, flags) parent_window = window.ParentWindow end + -- We allow window memory to be compacted so recreate the base stack when needed. if window.IDStack.Size == 0 then window.IDStack:push_back(window.ID) end @@ -10013,10 +11930,14 @@ function ImGui.Begin(name, open, flags) g.BeginMenuDepth = g.BeginMenuDepth + 1 end + -- Update .RootWindow and others pointers (before any possible call to FocusWindow) if first_begin_of_the_frame then ImGui.UpdateWindowParentAndRootLinks(window, flags, parent_window) window.ParentWindowInBeginStack = parent_window_in_stack + -- Focus route + -- There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack, + -- Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798) if window.RootWindow ~= window then window.ParentWindowForFocusRoute = parent_window_in_stack else @@ -10027,10 +11948,12 @@ function ImGui.Begin(name, open, flags) window.ParentWindowForFocusRoute = window.DockNode.HostWindow end end + -- Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute() if window.WindowClass and window.WindowClass.FocusRouteParentWindowId ~= nil and window.WindowClass.FocusRouteParentWindowId ~= 0 then window.ParentWindowForFocusRoute = ImGui.FindWindowByID(window.WindowClass.FocusRouteParentWindowId) end + -- Inherit SetWindowFontScale() from parent until we fix this system... if parent_window then window.FontWindowScaleParents = parent_window.FontWindowScaleParents * parent_window.FontWindowScale else @@ -10038,10 +11961,11 @@ function ImGui.Begin(name, open, flags) end end + -- Add to focus scope stack ImGui.PushFocusScope((bit32.band(window.ChildFlags, ImGuiChildFlags.NavFlattened) ~= 0) and g.CurrentFocusScopeId or window.ID) window.NavRootFocusScopeId = g.CurrentFocusScopeId - -- Add to popup stacks: update OpenPopupStack data, push to BeginPopupStack + -- Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[] if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then local popup_ref = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1] popup_ref.Window = window @@ -10050,12 +11974,15 @@ function ImGui.Begin(name, open, flags) window.PopupId = popup_ref.PopupId end + -- Process SetNextWindow***() calls + -- (FIXME: Consider splitting the HasXXX flags into X/Y components) local window_pos_set_by_api = false local window_size_x_set_by_api = false local window_size_y_set_by_api = false if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) ~= 0 then window_pos_set_by_api = (bit32.band(window.SetWindowPosAllowFlags, g.NextWindowData.PosCond) ~= 0) if window_pos_set_by_api and ImLengthSqr(g.NextWindowData.PosPivotVal) > 1e-5 then + -- May be processed on the next frame if this is our first frame and we are measuring size -- FIXME: Look into removing the branch so everything can go through this same code path for consistency. ImVec2_Copy(window.SetWindowPosVal, g.NextWindowData.PosVal) ImVec2_Copy(window.SetWindowPosPivot, g.NextWindowData.PosPivotVal) @@ -10067,7 +11994,7 @@ function ImGui.Begin(name, open, flags) if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ~= 0 then window_size_x_set_by_api = (bit32.band(window.SetWindowSizeAllowFlags, g.NextWindowData.SizeCond) ~= 0) and (g.NextWindowData.SizeVal.x > 0.0) window_size_y_set_by_api = (bit32.band(window.SetWindowSizeAllowFlags, g.NextWindowData.SizeCond) ~= 0) and (g.NextWindowData.SizeVal.y > 0.0) - if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then + if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then -- Axis-specific conditions for BeginChild() g.NextWindowData.SizeVal.x = window.SizeFull.x end if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then @@ -10106,14 +12033,18 @@ function ImGui.Begin(name, open, flags) -- [EXPERIMENTAL] Skip Refresh mode ImGui.UpdateWindowSkipRefresh(window) + -- Nested root windows (typically tooltips) override disabled state if window_stack_data.DisabledOverrideReenable and window.RootWindow == window then ImGui.BeginDisabledOverrideReenable() end + -- We intentionally set g.CurrentWindow to nil to prevent usage until when the viewport is set, then will call SetCurrentWindow() g.CurrentWindow = nil + -- When reusing window again multiple times a frame, just append content (don't need to setup again) if first_begin_of_the_frame and not window.SkipRefresh then - local window_is_child_tooltip = (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0) + -- Initialize + local window_is_child_tooltip = (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0) -- FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) local window_just_appearing_after_hidden_for_resize = (window.HiddenFramesCannotSkipItems > 0) window.Active = true @@ -10126,16 +12057,22 @@ function ImGui.Begin(name, open, flags) window.DC.CurrentTableIdx = -1 if bit32.band(flags, ImGuiWindowFlags.DockNodeHost) ~= 0 then window.DrawList:ChannelsSplit(2) - window.DrawList:ChannelsSetCurrent(1) -- DOCKING_HOST_DRAW_CHANNEL_FG: render decorations on channel 1, backgrounds rendered manually later + window.DrawList:ChannelsSetCurrent(1) -- DOCKING_HOST_DRAW_CHANNEL_FG: Render decorations on channel 1 as we will render the backgrounds manually later end + -- Restore buffer capacity when woken from a compacted state, to avoid if window.MemoryCompacted then ImGui.GcAwakeTransientWindowBuffers(window) end -- UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS + -- Update contents size from last frame for auto-fitting (or use explicit size) CalcWindowContentSizes(window, window.ContentSize, window.ContentSizeIdeal) + + -- FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors + -- for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because + -- it has a single usage before this code block and may be set below before it is finally checked. if window.HiddenFramesCanSkipItems > 0 then window.HiddenFramesCanSkipItems = window.HiddenFramesCanSkipItems - 1 end @@ -10170,11 +12107,16 @@ function ImGui.Begin(name, open, flags) end -- SELECT VIEWPORT + -- We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes. + ImGui.WindowSelectViewport(window) ImGui.SetCurrentViewport(window, window.Viewport) SetCurrentWindow(window) flags = window.Flags + -- LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies) + -- We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style. + if not window.DockIsActive and bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then window.WindowBorderSize = style.ChildBorderSize else @@ -10207,25 +12149,29 @@ function ImGui.Begin(name, open, flags) window.TitleBarHeight = (bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0) and 0 or g.FontSize + g.Style.FramePadding.y * 2 - window.FontRefSize = g.FontSize -- Lock this to discourage calling window:CalcFontSize() outside of current window. + 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. local use_current_size_for_scrollbar_x = window_just_created local use_current_size_for_scrollbar_y = window_just_created if window_size_x_set_by_api and window.ContentSizeExplicit.x ~= 0.0 then use_current_size_for_scrollbar_x = true end - if window_size_y_set_by_api and window.ContentSizeExplicit.y ~= 0.0 then + if window_size_y_set_by_api and window.ContentSizeExplicit.y ~= 0.0 then -- #7252 use_current_size_for_scrollbar_y = true end -- Collapse window by double-clicking on title bar -- At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and bit32.band(flags, ImGuiWindowFlags.NoCollapse) == 0 and not window.DockIsActive then + -- We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), + -- so verify that we don't have items over the title bar. local title_bar_rect = window:TitleBarRect() if g.HoveredWindow == window and g.HoveredId == 0 and g.HoveredIdPreviousFrame == 0 and g.ActiveId == 0 and ImGui.IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) then if g.IO.MouseClickedCount[0] == 2 and ImGui.GetKeyOwner(ImGuiKey.MouseLeft) == ImGuiKeyOwner_NoOwner then window.WantCollapseToggle = true - ImGui.SetKeyOwner(ImGuiKey.MouseLeft, window.MoveId) + ImGui.SetKeyOwner(ImGuiKey.MouseLeft, window.MoveId) -- Claim input the same way ButtonBehavior() does. Prevent a same-frame move from triggering other items. (#9439) end end if window.WantCollapseToggle then @@ -10240,6 +12186,10 @@ function ImGui.Begin(name, open, flags) end window.WantCollapseToggle = false + -- SIZE + + -- Outer Decoration Sizes + -- (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations). local scrollbar_sizes_from_last_frame = ImVec2() ImVec2_Copy(scrollbar_sizes_from_last_frame, window.ScrollbarSizes) @@ -10300,6 +12250,7 @@ function ImGui.Begin(name, open, flags) end end + -- Apply minimum/maximum window size constraints and final size ImVec2_Copy(window.SizeFull, CalcWindowSizeAfterConstraint(window, window.SizeFull)) ImVec2_Copy(window.Size, (window.Collapsed and bit32.band(flags, ImGuiWindowFlags.ChildWindow) == 0) and window:TitleBarRect():GetSize() or window.SizeFull) @@ -10313,6 +12264,7 @@ function ImGui.Begin(name, open, flags) end end + -- Position child window if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then IM_ASSERT(parent_window and parent_window.Active) window.BeginOrderWithinParent = parent_window.DC.ChildWindows.Size @@ -10351,12 +12303,16 @@ function ImGui.Begin(name, open, flags) ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) end + -- Calculate the range of allowed position for that window (to be movable and visible past safe area padding) + -- When clamping to stay visible, we will enforce that window.Pos stays inside of visibility_rect. local viewport_rect = window.Viewport:GetMainRect() local viewport_work_rect = window.Viewport:GetWorkRect() local visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding) local visibility_rect = ImRect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding) -- Clamp position/size so window stays visible within its viewport or monitor + -- Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + -- FIXME: Similar to code in GetWindowAllowedExtentRect() if not window_pos_set_by_api and bit32.band(flags, ImGuiWindowFlags.ChildWindow) == 0 then if not window.ViewportOwned and viewport_rect:GetWidth() > 0 and viewport_rect:GetHeight() > 0.0 then local size_for_clamping_y = window.Size.y @@ -10369,6 +12325,7 @@ function ImGui.Begin(name, open, flags) end window.Pos.x = ImTrunc(window.Pos.x) window.Pos.y = ImTrunc(window.Pos.y) + -- Apply window focus (new and reactivated windows are moved to front) local want_focus = false if (window_just_activated_by_user and bit32.band(flags, ImGuiWindowFlags.NoFocusOnAppearing) == 0) then if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then @@ -10378,6 +12335,8 @@ function ImGui.Begin(name, open, flags) end end + -- Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) + -- Large values tend to lead to variety of artifacts and are not recommended. if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and not window.DockIsActive then window.WindowRounding = style.ChildRounding elseif window.RootWindowDockTree.ViewportOwned then @@ -10390,11 +12349,16 @@ function ImGui.Begin(name, open, flags) end end + -- Decide if we are going to handle borders and resize grips + -- '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. local handle_borders_and_resize_grips = (window.DockNodeAsHost ~= nil or not window.DockIsActive) if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and window.ParentWindow.SkipItems then handle_borders_and_resize_grips = false end + -- Handle manual resize: Resize Grips, Borders, Gamepad + -- Child windows can only be resized when they have the flags set. The resize grip allows resizing in both directions, so it should appear only if both flags are set. local border_hovered, border_held = -1, -1 local resize_grip_col = {0, 0, 0, 0} @@ -10406,7 +12370,7 @@ function ImGui.Begin(name, open, flags) resize_grip_count = 0 end else - resize_grip_count = g.IO.ConfigWindowsResizeFromEdges and 2 or 1 -- Allow resize from lower-left if we have the mouse cursor feedback for it. + resize_grip_count = g.IO.ConfigWindowsResizeFromEdges and 2 or 1 -- Allow resize from lower-left if we have the mouse cursor feedback for it. end local resize_grip_draw_size = ImTrunc(ImMax(g.FontSize * 1.10, g.Style.WindowRounding + 1.0 + g.FontSize * 0.2)) @@ -10440,12 +12404,13 @@ function ImGui.Begin(name, open, flags) -- Save last known viewport position within the window itself (so it can be saved in .ini file and restored) ImVec2_Copy(window.ViewportPos, window.Viewport.Pos) - --- SCROLLBAR VISIBILITY - -- Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size) + -- SCROLLBAR VISIBILITY + + -- Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). if not window.Collapsed then -- When reading the current size we need to read it after size constraints have been applied. -- Intentionally use previous frame values for InnerRect and ScrollbarSizes. - -- And when we use window.DecoOuterSizeY1 here it doesn't have ScrollbarSizes.y applied yet. + -- And when we use window.DecorationUp here it doesn't have ScrollbarSizes.y applied yet. local avail_size_from_current_frame = ImVec2(window.SizeFull.x, window.SizeFull.y - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2)) local avail_size_from_last_frame = window.InnerRect:GetSize() + scrollbar_sizes_from_last_frame local needed_size_from_last_frame = window_just_created and ImVec2(0, 0) or window.ContentSize + window.WindowPadding * 2.0 @@ -10483,11 +12448,20 @@ function ImGui.Begin(name, open, flags) window.ScrollbarSizes = ImVec2(window.ScrollbarY and style.ScrollbarSize or 0.0, window.ScrollbarX and style.ScrollbarSize or 0.0) - -- Amend the partially filled window.DecoOuterSizeX2 values. + -- Amend the partially filled window.DecorationXXX values. window.DecoOuterSizeX2 = window.DecoOuterSizeX2 + window.ScrollbarSizes.x window.DecoOuterSizeY2 = window.DecoOuterSizeY2 + window.ScrollbarSizes.y end + -- UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING) + -- Update various regions. Variables they depend on should be set above in this function. + -- We set this up after processing the resize grip so that our rectangles doesn't lag by a frame. + + -- Outer rectangle + -- Not affected by window border size. Used by: + -- - FindHoveredWindow() (w/ extra padding when border resize is enabled) + -- - Begin() initial clipping rect for drawing window background and borders. + -- - Begin() clipping whole child local host_rect if (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Popup) == 0 and not window_is_child_tooltip) then host_rect = parent_window.ClipRect @@ -10502,20 +12476,39 @@ function ImGui.Begin(name, open, flags) end window.OuterRectClipped:ClipWith(host_rect) + -- Inner rectangle + -- Not affected by window border size. Used by: + -- - InnerClipRect + -- - ScrollToRectEx() + -- - NavUpdatePageUpPageDown() + -- - Scrollbar() window.InnerRect.Min.x = window.Pos.x + window.DecoOuterSizeX1 window.InnerRect.Min.y = window.Pos.y + window.DecoOuterSizeY1 window.InnerRect.Max.x = window.Pos.x + window.Size.x - window.DecoOuterSizeX2 window.InnerRect.Max.y = window.Pos.y + window.Size.y - window.DecoOuterSizeY2 + -- Inner clipping rectangle. + -- - Extend a outside of normal work region up to borders. + -- - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. + -- - It also makes clipped items be more noticeable. + -- - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5 on left and right edge), see #3312 + -- - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + -- Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. + -- Affected by window/frame border size. Used by: + -- - Begin() initial clip rect local top_border_size = ((bit32.band(flags, ImGuiWindowFlags.MenuBar) ~= 0 or bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0) and style.FrameBorderSize or window.WindowBorderSize) + -- Try to match the fact that our border is drawn centered over the window rectangle, rather than inner. + -- This is why we do a *0.5 here. We don't currently even technically support large values for WindowBorderSize, + -- see e.g #7887 #7888, but may do after we move the window border to become an inner border (and then we can remove the 0.5 here). window.InnerClipRect.Min.x = ImFloor(0.5 + window.InnerRect.Min.x + window.WindowBorderSize * 0.5) window.InnerClipRect.Min.y = ImFloor(0.5 + window.InnerRect.Min.y + top_border_size * 0.5) window.InnerClipRect.Max.x = ImFloor(window.InnerRect.Max.x - window.WindowBorderSize * 0.5) window.InnerClipRect.Max.y = ImFloor(window.InnerRect.Max.y - window.WindowBorderSize * 0.5) window.InnerClipRect:ClipWithFull(host_rect) - --- Scrolling + -- SCROLLING + -- Lock down maximum scrolling -- The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate -- for right/bottom aligned items without creating a scrollbar. @@ -10527,10 +12520,16 @@ function ImGui.Begin(name, open, flags) ImVec2_CopyV(window.ScrollTarget, FLT_MAX, FLT_MAX) window.DecoInnerSizeX1 = 0.0; window.DecoInnerSizeY1 = 0.0 + -- DRAWING + + -- Setup draw list and outer clipping rectangle IM_ASSERT(window.DrawList.CmdBuffer.Size == 1 and window.DrawList.CmdBuffer.Data[1].ElemCount == 0) window.DrawList:PushTexture(g.Font.OwnerAtlas.TexRef) ImGui.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) + -- When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order. + -- FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493) local is_undocked_or_docked_visible = not window.DockIsActive or window.DockTabIsVisible if is_undocked_or_docked_visible then local render_decorations_in_parent = false @@ -10559,6 +12558,7 @@ function ImGui.Begin(name, open, flags) window.DrawList = parent_window.DrawList end + -- Handle title bar, scrollbar, resize grips and resize borders local window_to_highlight = g.NavWindowingTarget or g.NavWindow local title_bar_is_highlight = want_focus or (window_to_highlight ~= nil and (window.RootWindowForTitleBarHighlight == window_to_highlight.RootWindowForTitleBarHighlight or (window.DockNode ~= nil and window.DockNode == window_to_highlight.DockNode))) @@ -10569,6 +12569,13 @@ function ImGui.Begin(name, open, flags) end end + -- UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING) + + -- Work rectangle. + -- Affected by window padding and border size. Used by: + -- - Columns() for right-most edge + -- - TreeNode(), CollapsingHeader() for right-most edge + -- - BeginTabBar() for right-most edge local allow_scrollbar_x = (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) == 0) and (bit32.band(flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0) local allow_scrollbar_y = (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) == 0) @@ -10597,7 +12604,7 @@ function ImGui.Begin(name, open, flags) window.ParentWorkRect = window.WorkRect -- [LEGACY] Content Region - -- FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. + -- FIXME-OBSOLETE: window.ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. -- Unless explicit content size is specified by user, this currently represent the region leading to no scrolling. -- Used by: -- - Mouse wheel scrolling + many other things @@ -10607,7 +12614,7 @@ function ImGui.Begin(name, open, flags) window.ContentRegionRect.Max.y = window.ContentRegionRect.Min.y + (window.ContentSizeExplicit.y ~= 0.0 and window.ContentSizeExplicit.y or (window.Size.y - window.WindowPadding.y * 2.0 - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2))) -- Setup drawing context - -- (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) + -- (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window. and window.DC. is dubious.) window.DC.Indent.x = window.DecoOuterSizeX1 + window.WindowPadding.x - window.Scroll.x window.DC.GroupOffset.x = 0.0 window.DC.ColumnsOffset.x = 0.0 @@ -10663,7 +12670,7 @@ function ImGui.Begin(name, open, flags) end window.DC.ItemWidth = window.DC.ItemWidthDefault window.DC.ItemWidthStack:resize(0) - window.DC.TextWrapPos = -1.0 + window.DC.TextWrapPos = -1.0 -- Disabled window.DC.TextWrapPosStack:resize(0) if bit32.band(flags, ImGuiWindowFlags.Modal) ~= 0 then window.DC.ModalDimBgColor = ImGui.ColorConvertFloat4ToU32(ImGui.GetStyleColorVec4(ImGuiCol.ModalWindowDimBg)) @@ -10676,22 +12683,30 @@ function ImGui.Begin(name, open, flags) window.AutoFitFramesY = window.AutoFitFramesY - 1 end + -- Clear SetNextWindowXXX data (can aim to move this higher in the function) g.NextWindowData:ClearFlags() + -- Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) + -- We ImGuiFocusRequestFlags.UnlessBelowModal to: + -- - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed. + -- - Position window behind the modal that is not a begin-parent of this window. if want_focus then ImGui.FocusWindow(window, ImGuiFocusRequestFlags.UnlessBelowModal) end if want_focus and window == g.NavWindow then - ImGui.NavInitWindow(window, false) + ImGui.NavInitWindow(window, false) -- <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls end -- 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 then if g.NavWindow and g.NavWindow.RootWindow == window and g.ActiveId == 0 and ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.C)) then ImGui.LogToClipboard(0) end end + -- Title bar if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and not window.DockIsActive then open = 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, open) elseif bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and window.DockIsActive then @@ -10707,7 +12722,7 @@ function ImGui.Begin(name, open, flags) if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) ~= 0 then -- Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source. - -- We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it. + -- We need to do this _before_ we overwrite window.DC.LastItemId below because BeginDockableDragDropSource() also overwrites it. if g.MovingWindow == window and bit32.band(window.RootWindowDockTree.Flags, ImGuiWindowFlags.NoDocking) == 0 then ImGui.BeginDockableDragDropSource(window) end @@ -10722,12 +12737,17 @@ function ImGui.Begin(name, open, flags) end end + -- Set default BgClickFlags + -- This is set at the end of this function, so UpdateWindowManualResize()/ClampWindowPos() may use last-frame value if overridden by user code. + -- FIXME: The general intent is that we will later expose config options to default to enable scrolling + select scrolling mouse button. if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then window.BgClickFlags = parent_window.BgClickFlags else window.BgClickFlags = g.IO.ConfigWindowsMoveFromTitleBarOnly and ImGuiWindowBgClickFlags.None or ImGuiWindowBgClickFlags.Move end + -- 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 if ImGui.IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) then @@ -10735,10 +12755,12 @@ function ImGui.Begin(name, open, flags) end ImGui.SetLastItemDataForWindow(window, title_bar_rect) else + -- Skip refresh always mark active if (window.SkipRefresh) then SetWindowActiveForSkipRefresh(window) end + -- Append ImGui.SetCurrentViewport(window, window.Viewport) SetCurrentWindow(window) g.NextWindowData:ClearFlags() @@ -10753,12 +12775,17 @@ function ImGui.Begin(name, open, flags) dl._ScrollOriginX, dl._ScrollOriginY = window.Pos.x - window.Scroll.x, window.Pos.y - window.Scroll.y end + -- Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) window.WriteAccessed = false window.BeginCount = window.BeginCount + 1 g.NextWindowData:ClearFlags() + -- Update visibility if first_begin_of_the_frame and not window.SkipRefresh then -- When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. + -- This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. + -- This is analogous to regular windows being hidden from one frame. + -- It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed. if window.DockIsActive and not window.DockTabIsVisible then if window.LastFrameJustFocused == g.FrameCount then window.HiddenFramesCannotSkipItems = 1 @@ -10793,10 +12820,12 @@ function ImGui.Begin(name, open, flags) end end + -- Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) if style.Alpha <= 0.0 then window.HiddenFramesCanSkipItems = 1 end + -- Update the Hidden flag local hidden_regular = (window.HiddenFramesCanSkipItems > 0) or (window.HiddenFramesCannotSkipItems > 0) window.Hidden = hidden_regular or (window.HiddenFramesForRenderOnly > 0) @@ -10820,6 +12849,7 @@ function ImGui.Begin(name, open, flags) window.DC.NavLayersActiveMaskNext = window.DC.NavLayersActiveMask end elseif first_begin_of_the_frame then + -- Skip refresh mode window.SkipItems = true end @@ -10831,6 +12861,7 @@ function ImGui.End() local g = GImGui local window = g.CurrentWindow + -- Error checking: verify that user hasn't called End() too many times! if (g.CurrentWindowStack.Size <= 1 and g.WithinFrameScopeWithImplicitWindow) then IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!") @@ -10838,6 +12869,7 @@ function ImGui.End() end local window_stack_data = g.CurrentWindowStack:back() + -- Error checking: verify that user doesn't directly call End() on a child window. if bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then IM_ASSERT_USER_ERROR(g.WithinEndPopupID == window.ID, "Must call EndPopup() and not End()!") end @@ -10845,10 +12877,11 @@ function ImGui.End() IM_ASSERT_USER_ERROR(g.WithinEndChildID == window.ID, "Must call EndChild() and not End()!") end + -- Close anything that is open if window.DC.CurrentColumns then ImGui.EndColumns() end - if bit32.band(window.Flags, ImGuiWindowFlags.DockNodeHost) == 0 and not window.SkipRefresh then + if bit32.band(window.Flags, ImGuiWindowFlags.DockNodeHost) == 0 and not window.SkipRefresh then -- Pop inner window clip rectangle ImGui.PopClipRect() end ImGui.PopFocusScope() @@ -10877,7 +12910,7 @@ function ImGui.End() -- Docking: report contents sizes to parent to allow for auto-resize if window.DockNode and window.DockTabIsVisible then - local host_window = window.DockNode.HostWindow + local host_window = window.DockNode.HostWindow -- FIXME-DOCK if host_window then ImVec2_Copy(host_window.DC.CursorMaxPos, window.DC.CursorMaxPos + window.WindowPadding - host_window.WindowPadding) end @@ -10935,6 +12968,13 @@ function ImGui.PopItemFlag() g.CurrentItemFlags = g.ItemFlagsStack:back() end +-- BeginDisabled()/EndDisabled() +-- - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) +-- - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently. +-- - Feedback welcome at https://github.com/ocornut/imgui/issues/211 +-- - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions. +-- (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls) +-- - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags.Disabled) is currently NOT SUPPORTED. --- @param disabled? bool function ImGui.BeginDisabled(disabled) if disabled == nil then disabled = true end @@ -10943,12 +12983,12 @@ function ImGui.BeginDisabled(disabled) local was_disabled = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0 if not was_disabled and disabled then g.DisabledAlphaBackup = g.Style.Alpha - g.Style.Alpha = g.Style.Alpha * g.Style.DisabledAlpha + g.Style.Alpha = g.Style.Alpha * g.Style.DisabledAlpha -- PushStyleVar(ImGuiStyleVar.Alpha, g.Style.Alpha * g.Style.DisabledAlpha) end if was_disabled or disabled then g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.Disabled) end - g.ItemFlagsStack:push_back(g.CurrentItemFlags) + g.ItemFlagsStack:push_back(g.CurrentItemFlags) -- FIXME-OPT: can we simply skip this and use DisabledStackSize? g.DisabledStackSize = g.DisabledStackSize + 1 end @@ -10957,13 +12997,17 @@ function ImGui.EndDisabled() IM_ASSERT_USER_ERROR_RET(g.DisabledStackSize > 0, "Calling EndDisabled() too many times!") g.DisabledStackSize = g.DisabledStackSize - 1 local was_disabled = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0 + -- PopItemFlag() g.ItemFlagsStack:pop_back() g.CurrentItemFlags = g.ItemFlagsStack:back() if was_disabled and bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) == 0 then - g.Style.Alpha = g.DisabledAlphaBackup + g.Style.Alpha = g.DisabledAlphaBackup -- PopStyleVar() end end +-- Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name. +-- Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal. +-- The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled(). function ImGui.BeginDisabledOverrideReenable() local g = GImGui IM_ASSERT(bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0) @@ -10984,6 +13028,12 @@ function ImGui.EndDisabledOverrideReenable() g.Style.Alpha = g.CurrentWindowStack:back().DisabledOverrideReenableAlphaBackup end +-- Find window given position, search front-to-back +-- - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow. +-- - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically +-- with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is +-- called, aka before the next Begin(). Moving window isn't affected. +-- - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here. --- @param pos ImVec2 --- @param find_first_and_in_any_viewport bool --- @return ImGuiWindow, ImGuiWindow? @@ -11022,6 +13072,8 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) if (window.Viewport ~= g.MouseViewport) then break end + + -- Using the clipped AABB, a child window will typically be clipped by its parent (not always) local hit_padding if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.NoResize, ImGuiWindowFlags.AlwaysAutoResize)) ~= 0 then hit_padding = padding_regular @@ -11032,6 +13084,8 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) break end + -- Support for one rectangular hole in any given window + -- FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512) if window.HitTestHoleSize.x ~= 0 then local hx, hy = window.Pos.x + window.HitTestHoleOffset.x, window.Pos.y + window.HitTestHoleOffset.y if pos.x >= hx and pos.y >= hy and pos.x < hx + window.HitTestHoleSize.x and pos.y < hy + window.HitTestHoleSize.y then @@ -11068,26 +13122,37 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) end -- TODO: +-- 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) function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) local g = GImGui local 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.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. local clear_hovered_windows = false g.HoveredWindow, g.HoveredWindowUnderMovingWindow = FindHoveredWindowEx(mouse_pos, false) IM_ASSERT(g.HoveredWindow == nil or g.HoveredWindow == g.MovingWindow or g.HoveredWindow.Viewport == g.MouseViewport) g.HoveredWindowBeforeClear = g.HoveredWindow + -- Modal windows prevents mouse from hovering behind them. local modal_window = ImGui.GetTopMostPopupModal() - if modal_window and g.HoveredWindow and not ImGui.IsWindowWithinBeginStackOf(g.HoveredWindow.RootWindow, modal_window) then + if modal_window and g.HoveredWindow and not ImGui.IsWindowWithinBeginStackOf(g.HoveredWindow.RootWindow, modal_window) then -- FIXME-MERGE: RootWindowDockTree ? clear_hovered_windows = true end + -- Disabled mouse hovering (we don't currently clear MousePos, we could) if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoMouse) ~= 0 then clear_hovered_windows = true end + -- We track click ownership. When clicked outside of a window the click is owned by the application and + -- won't report hovering nor request capture even while dragging over our windows afterward. local has_open_popup = (g.OpenPopupStack.Size > 0) local has_open_modal = (modal_window ~= nil) local mouse_earliest_down = -1 @@ -11100,7 +13165,7 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) end mouse_any_down = mouse_any_down or io.MouseDown[i] - if (io.MouseDown[i] or io.MouseReleased[i]) then + if (io.MouseDown[i] or io.MouseReleased[i]) then -- Increase release frame for our evaluation of earliest button (#1392) if (mouse_earliest_down == -1 or (io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])) then mouse_earliest_down = i end @@ -11110,6 +13175,8 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) local mouse_avail = (mouse_earliest_down == -1) or io.MouseDownOwned[mouse_earliest_down] local mouse_avail_unless_popup_close = (mouse_earliest_down == -1) or io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down] + -- If mouse was first clicked outside of ImGui bounds we also cancel out hovering. + -- FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) local mouse_dragging_extern_payload = g.DragDropActive and bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceExtern) ~= 0 if not mouse_avail and not mouse_dragging_extern_payload then clear_hovered_windows = true @@ -11120,6 +13187,8 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) g.HoveredWindowUnderMovingWindow = nil end + -- Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app) + -- Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag if (g.WantCaptureMouseNextFrame ~= -1) then io.WantCaptureMouse = (g.WantCaptureMouseNextFrame ~= 0) io.WantCaptureMouseUnlessPopupClose = io.WantCaptureMouse @@ -11128,6 +13197,7 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close and (g.HoveredWindow ~= nil or mouse_any_down)) or has_open_modal end + -- Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app) io.WantCaptureKeyboard = false if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoKeyboard) == 0 then if (g.ActiveId ~= 0) or (modal_window ~= nil) then @@ -11136,10 +13206,11 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) io.WantCaptureKeyboard = true end end - if g.WantCaptureKeyboardNextFrame ~= -1 then + if g.WantCaptureKeyboardNextFrame ~= -1 then -- Manual override io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame ~= 0) end + -- Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible io.WantTextInput = (g.WantTextInputNextFrame ~= -1) and (g.WantTextInputNextFrame ~= 0) or false end @@ -11153,8 +13224,10 @@ function ImGui.UpdateAliasKey(key, v, analog_value) key_data.AnalogValue = analog_value end +-- [Internal] Do not use directly function ImGui.GetMergedModsFromKeys() local g = GImGui + -- Bypass IsKeyDown() for the unlikely case where user used a ImGuiInputFlags.LockXXXX on those. local mods = 0 if ImGui.GetKeyData(g, ImGuiMod_Ctrl).Down then mods = bit32.bor(mods, ImGuiMod_Ctrl) end @@ -11173,13 +13246,17 @@ function ImGui.UpdateKeyboardInputs() io:ClearInputKeys() end + -- Update aliases for n = 0, 2 do -- TODO: ImGuiMouseButton.COUNT - 1 ImGui.UpdateAliasKey(ImGui.MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] and 1.0 or 0.0) end ImGui.UpdateAliasKey(ImGuiKey.MouseWheelX, io.MouseWheelH ~= 0.0, io.MouseWheelH) ImGui.UpdateAliasKey(ImGuiKey.MouseWheelY, io.MouseWheel ~= 0.0, io.MouseWheel) - -- Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values + -- Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values. + -- - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array. + -- - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array. + -- So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing. local prev_key_mods = io.KeyMods io.KeyMods = ImGui.GetMergedModsFromKeys() io.KeyCtrl = bit32.band(io.KeyMods, ImGuiMod_Ctrl) ~= 0 @@ -11235,6 +13312,7 @@ function ImGui.UpdateKeyboardInputs() owner_data.LockUntilRelease = owner_data.LockUntilRelease and key_data.Down -- Clear LockUntilRelease when key is not Down anymore end + -- Update key routing (for e.g. shortcuts) ImGui.UpdateKeyRoutingTable(g.KeysRoutingTable) end @@ -11244,7 +13322,9 @@ function ImGui.UpdateMouseInputs() -- Mouse Wheel swapping flag -- As a standard behavior holding Shift while using Vertical Mouse Wheel triggers Horizontal scroll instead - -- - We avoid doing it on OSX as it the OS input layer handles this already + -- - We avoid doing it on OSX as it the OS input layer handles this already. + -- - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature. + -- - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source. io.MouseWheelRequestAxisSwap = io.KeyShift and not io.ConfigMacOSXBehaviors -- Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well) @@ -11263,13 +13343,14 @@ function ImGui.UpdateMouseInputs() io.MouseDelta = ImVec2(0.0, 0.0) end - -- Update stationary timer - -- FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates - local mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource.Mouse) and 2.0 or 3.0 + -- Update stationary timer. + -- FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates. + local mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource.Mouse) and 2.0 or 3.0 -- Slightly higher threshold for ImGuiMouseSource.TouchScreen/ImGuiMouseSource.Pen, may need rework. local mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold) g.MouseStationaryTimer = mouse_stationary and (g.MouseStationaryTimer + io.DeltaTime) or 0.0 + -- IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer) - -- If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0 threshold but would need to reset in everywhere we set this to true. + -- If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true. if io.MouseDelta.x ~= 0.0 or io.MouseDelta.y ~= 0.0 then g.NavHighlightItemUnderNav = false end @@ -11331,8 +13412,10 @@ function ImGui.UpdateMouseInputs() io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, (delta_from_click_pos.y < 0.0) and -delta_from_click_pos.y or delta_from_click_pos.y) end + -- We provide io.MouseDoubleClicked[] as a legacy service io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2) + -- Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation if (io.MouseClicked[i]) then g.NavHighlightItemUnderNav = false end @@ -11363,6 +13446,7 @@ end --- @param wheel ImVec2 --- @return ImGuiWindow? local function FindBestWheelingWindow(wheel) + -- For each axis, find window in the hierarchy that may want to use scrolling local g = GImGui local windows = {nil, nil} for axis = ImGuiAxis.X, ImGuiAxis.Y do @@ -11370,10 +13454,15 @@ local function FindBestWheelingWindow(wheel) windows[axis] = g.HoveredWindow local window = g.HoveredWindow while bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 do + -- Bubble up into parent window if: + -- - a child window doesn't allow any scrolling. + -- - a child window has the ImGuiWindowFlags.NoScrollWithMouse flag. + -- -- - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP) local has_scrolling = (window.ScrollMax[axis] ~= 0.0) local inputs_disabled = (bit32.band(window.Flags, ImGuiWindowFlags.NoScrollWithMouse) ~= 0) and not (bit32.band(window.Flags, ImGuiWindowFlags.NoMouseInputs) ~= 0) + -- local scrolling_past_limits = (wheel_v < 0.0) and (window.Scroll[axis] <= 0.0) or (window.Scroll[axis] >= window.ScrollMax[axis]) - if has_scrolling and not inputs_disabled then + if has_scrolling and not inputs_disabled then -- and not scrolling_past_limits break -- select this window end @@ -11386,10 +13475,14 @@ local function FindBestWheelingWindow(wheel) return nil end + -- If there's only one window or only one axis then there's no ambiguity if (windows[1] == windows[2] or windows[1] == nil or windows[2] == nil) then return windows[2] and windows[2] or windows[1] end + -- If candidate are different windows we need to decide which one to prioritize + -- - First frame: only find a winner if one axis is zero. + -- - Subsequent frames: only find a winner when one is more than the other. if (g.WheelingWindowStartFrame == -1) then g.WheelingWindowStartFrame = g.FrameCount end @@ -11401,7 +13494,10 @@ local function FindBestWheelingWindow(wheel) return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) and windows[1] or windows[2] end +-- Called by NewFrame() function ImGui.UpdateMouseWheel() + -- Reset the locked window if we move the mouse or after the timer elapses. + -- FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795) local g = GImGui if g.WheelingWindow ~= nil then g.WheelingWindowReleaseTimer = g.WheelingWindowReleaseTimer - g.IO.DeltaTime @@ -11423,13 +13519,14 @@ function ImGui.UpdateMouseWheel() local wheel = ImVec2() wheel.x = ImGui.TestKeyOwner(ImGuiKey.MouseWheelX, owner_id) and g.IO.MouseWheelH or 0.0 wheel.y = ImGui.TestKeyOwner(ImGuiKey.MouseWheelY, owner_id) and g.IO.MouseWheel or 0.0 + -- IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y) if g.WheelingWindow ~= nil then ImGui.SetKeyOwner(ImGuiKey.MouseWheelX, owner_id) ImGui.SetKeyOwner(ImGuiKey.MouseWheelY, owner_id) end -- Zoom / Scale window - -- FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned + -- FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. if wheel.y ~= 0.0 and g.IO.KeyCtrl and g.IO.FontAllowUserScaling then LockWheelingWindow(mouse_window, wheel.y) local window = mouse_window @@ -11448,6 +13545,7 @@ function ImGui.UpdateMouseWheel() end -- Mouse wheel scrolling + -- Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs() if (g.IO.MouseWheelRequestAxisSwap) then wheel = ImVec2(wheel.y, 0.0) end @@ -11457,7 +13555,7 @@ function ImGui.UpdateMouseWheel() g.WheelingAxisAvg.x = ImStd.ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30) g.WheelingAxisAvg.y = ImStd.ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30) - -- In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now + -- In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now. wheel = wheel + g.WheelingWindowWheelRemainder g.WheelingWindowWheelRemainder = ImVec2(0.0, 0.0) if (wheel.x == 0.0 and wheel.y == 0.0) then @@ -11500,6 +13598,8 @@ function ImGui.UpdateMouseWheel() end end +-- Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. +-- FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! local function SetupDrawListSharedData() local g = GImGui local virtual_space = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX) @@ -11530,7 +13630,7 @@ local function InitViewportDrawData(viewport) local g = GImGui local draw_data = viewport.DrawDataP - viewport.DrawData = draw_data + viewport.DrawData = draw_data -- Make publicly accessible viewport.DrawDataBuilder.Layers[1] = draw_data.CmdLists viewport.DrawDataBuilder.Layers[2] = viewport.DrawDataBuilder.LayerData1 viewport.DrawDataBuilder.Layers[1]:resize(0) @@ -11563,7 +13663,7 @@ local function InitViewportDrawData(viewport) draw_data.Textures = g.PlatformIO.Textures end --- FIXME-DPI: +-- FIXME-DPI: PLEASE DO NOT USE. I don't want to formalize this just yet. Because reasons. function ImGui.GetScale() local g = GImGui return g.Style._MainScale @@ -11583,6 +13683,14 @@ function ImGui.GetCurrentWindow() return g.CurrentWindow end +-- Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. +-- - When using this function it is sane to ensure that float are perfectly rounded to integer values, +-- so that e.g. (int)(max.x-min.x) in user's render produce correct result. +-- - 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 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. --- @param clip_rect_min ImVec2 --- @param clip_rect_max ImVec2 --- @param intersect_with_current_clip_rect? bool @@ -11604,6 +13712,7 @@ end --- @param drawlist_name string --- @return ImDrawList local function GetViewportBgFgDrawList(viewport, drawlist_no, drawlist_name) + -- Create the draw list on demand, because they are not frequently used for all viewports local g = GImGui IM_ASSERT(drawlist_no <= 2) -- IM_COUNTOF(viewport->BgFgDrawLists) local draw_list = viewport.BgFgDrawLists[drawlist_no] @@ -11613,6 +13722,7 @@ local function GetViewportBgFgDrawList(viewport, drawlist_no, drawlist_name) viewport.BgFgDrawLists[drawlist_no] = draw_list end + -- Our ImDrawList system requires that there is always a command if viewport.BgFgDrawListsLastTimeActive[drawlist_no] ~= g.Time then draw_list:_ResetForNewFrame() draw_list:PushTexture(g.IO.Fonts.TexRef) @@ -11647,7 +13757,7 @@ function ImGui.GetForegroundDrawList(viewport) return GetViewportBgFgDrawList(viewport, 2, "##Foreground") end --- FIXME: Add a more explicit sort order in the window structure +-- FIXME: Add a more explicit sort order in the window structure. --- @param lhs ImGuiWindow --- @param rhs ImGuiWindow local function ChildWindowComparer(lhs, rhs) @@ -11684,7 +13794,7 @@ local function AddWindowToDrawData(window, layer) local viewport = window.Viewport g.IO.MetricsRenderWindows = g.IO.MetricsRenderWindows + 1 if window.DrawList._Splitter._Count > 1 then - window.DrawList:ChannelsMerge() -- Merge if user forgot to merge back. Also required for DockNodeHost windows. + window.DrawList:ChannelsMerge() -- Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags.DockNodeHost windows. end ImGui.AddDrawListToDrawDataEx(viewport.DrawDataP, viewport.DrawDataBuilder.Layers[layer], window.DrawList) for _, child in window.DC.ChildWindows:iter() do @@ -11699,6 +13809,7 @@ local function GetWindowDisplayLayer(window) return (bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0) and 2 or 1 end +-- Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu) --- @param window ImGuiWindow local function AddRootWindowToDrawData(window) AddWindowToDrawData(window, GetWindowDisplayLayer(window)) @@ -11746,6 +13857,7 @@ function ImGui.NewFrame() g.WindowsActiveCount = 0 g.MenusIdSubmittedThisFrame:resize(0) + -- Calculate frame-rate for the user, as a purely luxurious feature -- FIXME: are lines below correct and necessary g.FramerateSecPerFrameAccum = g.FramerateSecPerFrameAccum + (g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]) g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime @@ -11757,12 +13869,16 @@ function ImGui.NewFrame() g.IO.Framerate = FLT_MAX end + -- Process input queue (trickle as many events as possible), turn events into writes to IO structure ImGui.UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue) + -- Update viewports (after processing input queue, so io.MouseHoveredViewport is set) ImGui.UpdateViewportsNewFrame() + -- Update texture list (collect destroyed textures, etc.) ImGui.UpdateTexturesNewFrame() + -- Setup current font and draw list shared data SetupDrawListSharedData() ImGui.UpdateFontsNewFrame() @@ -11774,11 +13890,13 @@ function ImGui.NewFrame() viewport.DrawDataP.Valid = false end + -- Drag and drop keep the source ID alive so even if the source disappear our state is consistent if g.DragDropActive and g.DragDropPayload.SourceId == g.ActiveId then ImGui.KeepAliveID(g.DragDropPayload.SourceId) end - if not g.IO.ConfigDebugHighlightIdConflicts or not g.IO.KeyCtrl then + -- [DEBUG] + if not g.IO.ConfigDebugHighlightIdConflicts or not g.IO.KeyCtrl then -- Count is locked while holding Ctrl g.DebugDrawIdConflictsId = 0 end if g.IO.ConfigDebugHighlightIdConflicts and g.HoveredIdPreviousFrameItemCount > 1 then @@ -11804,6 +13922,9 @@ function ImGui.NewFrame() g.HoveredIdAllowOverlap = false g.HoveredIdIsDisabled = false + -- Clear ActiveID if the item is not alive anymore. + -- In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd(). + -- As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves. if (g.ActiveId ~= 0 and g.ActiveIdIsAlive ~= g.ActiveId and g.ActiveIdPreviousFrame == g.ActiveId) then IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() 0x%08X because it isn't marked alive anymore!", g.ActiveId) @@ -11873,8 +13994,18 @@ function ImGui.NewFrame() end end + -- Close popups on focus lost (currently wip/opt-in) + -- if (g.IO.AppFocusLost) + -- ClosePopupsExceptModals(); + + -- Update keyboard input state ImGui.UpdateKeyboardInputs() + -- IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl)); + -- IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift)); + -- IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt)); + -- IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper)); + -- Drag and drop g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr g.DragDropAcceptIdCurr = 0 @@ -11885,6 +14016,10 @@ function ImGui.NewFrame() g.DragDropWithinTarget = false g.DragDropHoldJustPressedId = 0 if g.DragDropActive then + -- Also works when g.ActiveId==0 (aka leftover payload in progress, no active id) + -- You may disable this externally by hijacking the input route: + -- 'if (GetDragDropPayload() ~= nil) then Shortcut(ImGuiKey.Escape, ImGuiInputFlags.RouteGlobal | ImGuiInputFlags.RouteOverActive) end + -- but you will not get a return value from Shortcut() due to ActiveIdUsingAllKeyboardKeys logic. You can however poll IsKeyPressed(ImGuiKey.Escape) afterwards. local owner_id = (g.ActiveId ~= 0) and g.ActiveId or ImHashStr("##DragDropCancelHandler") if ImGui.Shortcut(ImGuiKey.Escape, ImGuiInputFlags.RouteGlobal, owner_id) then ImGui.ClearActiveID() @@ -11893,14 +14028,17 @@ function ImGui.NewFrame() end g.TooltipPreviousWindow = nil + -- Update keyboard/gamepad navigation ImGui.NavUpdate() + -- Update mouse input state ImGui.UpdateMouseInputs() -- Undocking -- (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame) ImGui.DockContextNewFrameUpdateUndocking(g) + -- Mark all windows as not visible and compact unused memory. IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size) local gc_all = g.GcCompactAll or g.IO.ConfigMemoryCompactTimer < 0.0 local memory_compact_start_time = gc_all and FLT_MAX or (g.Time - g.IO.ConfigMemoryCompactTimer) @@ -11912,13 +14050,18 @@ function ImGui.NewFrame() window.BeginCountPreviousFrame = window.BeginCount window.BeginCount = 0 + -- Garbage collect transient buffers of recently unused windows if (not window.WasActive or gc_all) and not window.MemoryCompacted and window.LastTimeActive < memory_compact_start_time then ImGui.GcCompactTransientWindowBuffers(window) end end + -- 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) ImGui.UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos) + -- Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) ImGui.UpdateMouseMovingWindowNewFrame() -- Background darkening/whitening @@ -11938,6 +14081,7 @@ function ImGui.NewFrame() g.PlatformImeData.WantVisible = false g.PlatformImeData.WantTextInput = false + -- Mouse wheel scrolling, scale ImGui.UpdateMouseWheel() -- Garbage collect transient buffers of recently unused tables @@ -11957,14 +14101,17 @@ function ImGui.NewFrame() end g.GcCompactAll = false + -- Closing the focused window restore focus to the first active root window in descending z-order if (g.NavWindow and not g.NavWindow.WasActive) then ImGui.FocusTopMostWindowUnderOne(nil, nil, nil, ImGuiFocusRequestFlags.RestoreFocusedChild) end + -- No window should be open at the beginning of the frame. + -- But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack:resize(0) g.BeginPopupStack:resize(0) g.ItemFlagsStack:resize(0) - g.ItemFlagsStack:push_back(ImGuiItemFlags.Default_) + g.ItemFlagsStack:push_back(ImGuiItemFlags.Default_) -- Default flags g.CurrentItemFlags = g.ItemFlagsStack:back() g.GroupStack:resize(0) @@ -11974,6 +14121,9 @@ function ImGui.NewFrame() -- Docking ImGui.DockContextNewFrameUpdateDocking(g) + -- Create implicit/fallback window - which we will only render it if the user has added something to it. + -- We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. + -- This fallback is particularly important as it prevents ImGui:: calls from crashing. g.WithinFrameScopeWithImplicitWindow = true ImGui.SetNextWindowSize(ImVec2(400, 400), ImGuiCond.FirstUseEver) ImGui.Begin("Debug##Default") @@ -11985,10 +14135,12 @@ function ImGui.NewFrame() ImGui.ErrorRecoveryStoreState(g.StackSizesInNewFrame) end +-- This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. function ImGui.EndFrame() local g = GImGui IM_ASSERT(g.Initialized) + -- Don't process EndFrame() multiple times. if g.FrameCountEnded == g.FrameCount then return end @@ -12000,7 +14152,7 @@ function ImGui.EndFrame() end ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() - -- Notify Platform when our Input Method Editor cursor has moved + -- Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) local ime_data = g.PlatformImeData if g.PlatformIO.Platform_SetImeDataFn ~= nil and not ImGuiPlatformImeData_Compare(ime_data, g.PlatformImeDataPrev) then local viewport = ImGui.FindViewportByID(ime_data.ViewportId) @@ -12012,6 +14164,7 @@ function ImGui.EndFrame() end g.WantTextInputNextFrame = ime_data.WantTextInput + -- Hide implicit/fallback "Debug" window if it hasn't been used g.WithinFrameScopeWithImplicitWindow = false if (g.CurrentWindow and g.CurrentWindow.IsFallbackWindow and g.CurrentWindow.WriteAccessed == false) then g.CurrentWindow.Active = false @@ -12044,14 +14197,19 @@ function ImGui.EndFrame() g.DragDropWithinSource = false end + -- End frame g.WithinFrameScope = false g.FrameCountEnded = g.FrameCount ImGui.UpdateFontsEndFrame() + -- Initiate moving window + handle left-click and right-click focus ImGui.UpdateMouseMovingWindowEndFrame() + -- Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) ImGui.UpdateViewportsEndFrame() + -- Sort the window list so that all child windows are after their parent + -- We cannot do that on FocusWindow() because children may not exist yet g.WindowsTempSortBuffer:resize(0) g.WindowsTempSortBuffer:reserve(g.Windows.Size) for _, window in g.Windows:iter() do @@ -12065,16 +14223,19 @@ function ImGui.EndFrame() until true end + -- This usually assert if there is a mismatch between the ImGuiWindowFlags.ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong. IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size) g.Windows:swap(g.WindowsTempSortBuffer) g.IO.MetricsActiveWindows = g.WindowsActiveCount ImGui.UpdateTexturesEndFrame() + -- Unlock font atlas for _, atlas in g.FontAtlases:iter() do atlas.Locked = false end + -- Clear Input data for next frame ImVec2_Copy(g.IO.MousePosPrev, g.IO.MousePos) g.IO.AppFocusLost = false g.IO.MouseWheel = 0.0 @@ -12083,6 +14244,9 @@ function ImGui.EndFrame() end -- TODO: +-- Prepare the data for rendering so you can call GetDrawData() +-- (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) function ImGui.Render() local g = GImGui IM_ASSERT(g.Initialized) @@ -12095,6 +14259,7 @@ function ImGui.Render() g.IO.MetricsRenderWindows = 0 + -- Add background ImDrawList (for each active viewport) for _, viewport in g.Viewports:iter() do InitViewportDrawData(viewport) if viewport.BgFgDrawLists[1] ~= nil and viewport.BgFgDrawListsLastTimeActive[1] == g.Time then @@ -12102,8 +14267,10 @@ function ImGui.Render() end end + -- Draw modal/window whitening backgrounds ImGui.RenderDimmedBackgrounds() + -- Add ImDrawList to render local windows_to_render_top_most = {nil, nil} windows_to_render_top_most[1] = (g.NavWindowingTarget and (bit32.band(g.NavWindowingTarget.Flags, ImGuiWindowFlags.NoBringToFrontOnFocus) == 0)) and g.NavWindowingTarget.RootWindowDockTree or nil windows_to_render_top_most[2] = g.NavWindowingTarget and g.NavWindowingListWindow or nil @@ -12123,15 +14290,18 @@ function ImGui.Render() ImGui.RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48)) end + -- Setup ImDrawData structures for end-user g.IO.MetricsRenderVertices = 0 g.IO.MetricsRenderIndices = 0 for _, viewport in g.Viewports:iter() do FlattenDrawDataIntoSingleLayer(viewport.DrawDataBuilder) + -- Add foreground ImDrawList (for each active viewport) if viewport.BgFgDrawLists[2] ~= nil and viewport.BgFgDrawListsLastTimeActive[2] == g.Time then ImGui.AddDrawListToDrawDataEx(viewport.DrawDataP, viewport.DrawDataBuilder.Layers[1], ImGui.GetForegroundDrawList(viewport)) end + -- We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch). local draw_data = viewport.DrawDataP for _, draw_list in draw_data.CmdLists:iter() do draw_list:_PopUnusedDrawCmd() @@ -12142,6 +14312,8 @@ function ImGui.Render() end end +-- Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. +-- CalcTextSize("") should return ImVec2(0.0, g.FontSize) --- @param text ImString --- @param text_end? int # Exclusive upper bound --- @param hide_text_after_double_hash? bool @@ -12167,7 +14339,7 @@ function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double local text_display_end if hide_text_after_double_hash then - text_display_end = ImGui.FindRenderedTextEnd(text, text_end) + text_display_end = ImGui.FindRenderedTextEnd(text, text_end) -- Hide anything after a '##' string else text_display_end = text_end end @@ -12179,11 +14351,15 @@ function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double end local text_size = font:CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_begin, text_display_end, nil) + -- Round + -- (see 7b0bf230, 4622fa4b6, #791 for details about this.) + -- FIXME: Add a way to disable this. text_size.x = ImCeilFast(text_size.x) return text_size end +-- Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() function ImGui.GetDrawData() local g = GImGui local viewport = g.Viewports[1] @@ -12194,6 +14370,7 @@ function ImGui.GetTime() return GImGui.Time end +-- This function is merely here to free heap allocations. function ImGui.Shutdown() local g = GImGui IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == nil, "Forgot to shutdown Platform backend?") @@ -12203,6 +14380,7 @@ function ImGui.Shutdown() IM_ASSERT_USER_ERROR(viewport.RendererUserData == nil and viewport.PlatformUserData == nil and viewport.PlatformHandle == nil, "Backend or app forgot to call DestroyPlatformWindows()?") end + -- 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) for _, atlas in g.FontAtlases:iter() do ImGui.UnregisterFontAtlas(atlas) if atlas.OwnerContext == g then @@ -12214,16 +14392,20 @@ function ImGui.Shutdown() end g.DrawListSharedData.TempBuffer:clear() + -- Shutdown extensions ImGui.DockContextShutdown(g) + -- Cleanup of other data are conditional on actually having initialized Dear ImGui. if not g.Initialized then return end -- TODO: + -- Clear everything else g.MenusIdSubmittedThisFrame:clear() end +-- A conformant backend should return nil on failure (e.g. clipboard data is not text). --- @return string? function ImGui.GetClipboardText() local g = GImGui @@ -12246,17 +14428,29 @@ function ImGui.GetPlatformIO() return GImGui.PlatformIO end +-- Get desired mouse cursor shape. +-- Important: this is meant to be used by a platform backend, it is reset in ImGui.NewFrame(), +-- updated during the frame, and locked in EndFrame()/Render(). +-- If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you function ImGui.GetMouseCursor() local g = GImGui return g.MouseCursor end +-- We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value. +-- Custom cursors may be handled by custom backends. If you are using a standard backend and want to hack in a custom cursor, you may +-- handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags.NoMouseCursorChange during the backend _NewFrame() call. --- @param cursor_type ImGuiMouseCursor function ImGui.SetMouseCursor(cursor_type) local g = GImGui g.MouseCursor = cursor_type end +------------------------------------------------------------------------------- +-- [SECTION] MISC HELPERS/UTILITIES (Color functions) +-- Note: The Convert functions are early design which are not consistent with other API. +------------------------------------------------------------------------------- + --- @param col_a ImU32 --- @param col_b ImU32 --- @return ImU32 @@ -12294,6 +14488,8 @@ function ImGui.ColorConvertFloat4ToU32(in_col) return bit32.bor(F32ToU8Sat(in_col.x), bit32.lshift(F32ToU8Sat(in_col.y), 8), bit32.lshift(F32ToU8Sat(in_col.z), 16), bit32.lshift(F32ToU8Sat(in_col.w), 24)) end +-- Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 +-- Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv --- @param r float --- @param g float --- @param b float @@ -12317,6 +14513,8 @@ function ImGui.ColorConvertRGBtoHSV(r, g, b) return out_h, out_s, out_v end +-- Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 +-- also http://en.wikipedia.org/wiki/HSL_and_HSV --- @param h float --- @param s float --- @param v float @@ -12350,6 +14548,7 @@ function ImGui.ColorConvertHSVtoRGB(h, s, v) end end +-- Generic helper, equivalent to old ImGui.CalcListClipping() but stateless --- @param clip_rect ImRect --- @param pos ImVec2 --- @param items_height float @@ -12359,9 +14558,9 @@ function ImGui.CalcClipRectVisibleItemsY(clip_rect, pos, items_height) return visible_start + 1, visible_end + 1 end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] STYLING ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.GetStyle() IM_ASSERT(GImGui ~= nil, "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?") @@ -12406,6 +14605,7 @@ end end +-- FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32 --- @param idx ImGuiCol --- @param col ImU32|ImVec4 function ImGui.PushStyleColor(idx, col) @@ -12440,57 +14640,57 @@ function ImGui.PopStyleColor(count) end local GStyleVarsInfo = { - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "Alpha"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DisabledAlpha"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowPadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowMinSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowTitleAlign"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "FramePadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemSpacing"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemInnerSpacing"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "IndentSpacing"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "CellPadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarPadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabMinSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthBase"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthShrink"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarOverlineSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TableAngledHeadersAngle"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "TableAngledHeadersTextAlign"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "MenuItemRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SelectableRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DragDropTargetRounding"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ButtonTextAlign"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SelectableTextAlign"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorTextBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextAlign"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextPadding") + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "Alpha"), -- ImGuiStyleVar.Alpha + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DisabledAlpha"), -- ImGuiStyleVar.DisabledAlpha + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowPadding"), -- ImGuiStyleVar.WindowPadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowRounding"), -- ImGuiStyleVar.WindowRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowBorderSize"), -- ImGuiStyleVar.WindowBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowMinSize"), -- ImGuiStyleVar.WindowMinSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowTitleAlign"), -- ImGuiStyleVar.WindowTitleAlign + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildRounding"), -- ImGuiStyleVar.ChildRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildBorderSize"), -- ImGuiStyleVar.ChildBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupRounding"), -- ImGuiStyleVar.PopupRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupBorderSize"), -- ImGuiStyleVar.PopupBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "FramePadding"), -- ImGuiStyleVar.FramePadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameRounding"), -- ImGuiStyleVar.FrameRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameBorderSize"), -- ImGuiStyleVar.FrameBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemSpacing"), -- ImGuiStyleVar.ItemSpacing + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemInnerSpacing"), -- ImGuiStyleVar.ItemInnerSpacing + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "IndentSpacing"), -- ImGuiStyleVar.IndentSpacing + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "CellPadding"), -- ImGuiStyleVar.CellPadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarSize"), -- ImGuiStyleVar.ScrollbarSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarRounding"), -- ImGuiStyleVar.ScrollbarRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarPadding"), -- ImGuiStyleVar.ScrollbarPadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabMinSize"), -- ImGuiStyleVar.GrabMinSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabRounding"), -- ImGuiStyleVar.GrabRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageRounding"), -- ImGuiStyleVar.ImageRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageBorderSize"), -- ImGuiStyleVar.ImageBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabRounding"), -- ImGuiStyleVar.TabRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBorderSize"), -- ImGuiStyleVar.TabBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthBase"), -- ImGuiStyleVar.TabMinWidthBase + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthShrink"), -- ImGuiStyleVar.TabMinWidthShrink + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarBorderSize"), -- ImGuiStyleVar.TabBarBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarOverlineSize"), -- ImGuiStyleVar.TabBarOverlineSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TableAngledHeadersAngle"), -- ImGuiStyleVar.TableAngledHeadersAngle + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "TableAngledHeadersTextAlign"), -- ImGuiStyleVar.TableAngledHeadersTextAlign + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesSize"), -- ImGuiStyleVar.TreeLinesSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesRounding"), -- ImGuiStyleVar.TreeLinesRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "MenuItemRounding"), -- ImGuiStyleVar.MenuItemRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SelectableRounding"), -- ImGuiStyleVar.SelectableRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DragDropTargetRounding"), -- ImGuiStyleVar.DragDropTargetRounding + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ButtonTextAlign"), -- ImGuiStyleVar.ButtonTextAlign + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SelectableTextAlign"), -- ImGuiStyleVar.SelectableTextAlign + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorSize"), -- ImGuiStyleVar.SeparatorSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorTextBorderSize"), -- ImGuiStyleVar.SeparatorTextBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextAlign"), -- ImGuiStyleVar.SeparatorTextAlign + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextPadding") -- ImGuiStyleVar.SeparatorTextPadding } --- @param idx ImGuiStyleVar --- @return ImGuiStyleVarInfo function ImGui.GetStyleVarInfo(idx) IM_ASSERT(idx >= 0 and idx < ImGuiStyleVar.COUNT) - -- IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT) + -- IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar.COUNT) return GStyleVarsInfo[idx + 1] end @@ -12558,8 +14758,9 @@ function ImGui.PopStyleVar(count) end end +-- ATTENTION THIS IS IN LEGACY LOCAL SPACE. --- @param wrap_local_pos_x float -function ImGui.PushTextWrapPos(wrap_local_pos_x) -- ATTENTION: THIS IS IN LEGACY LOCAL SPACE. +function ImGui.PushTextWrapPos(wrap_local_pos_x) local g = GImGui local window = g.CurrentWindow window.DC.TextWrapPosStack:push_back(window.DC.TextWrapPos) @@ -12649,7 +14850,7 @@ end function ImGui.IsWindowAbove(potential_above, potential_below) local g = GImGui - -- It would be saner to ensure that display layer is always reflected in the g.Windows order, which would likely requires altering all manipulations of that array + -- It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array local display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below) if display_layer_delta ~= 0 then return display_layer_delta > 0 @@ -12668,6 +14869,9 @@ function ImGui.IsWindowAbove(potential_above, potential_below) end -- Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags for options. +-- IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, +-- you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! +-- Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. --- @param flags? ImGuiHoveredFlags function ImGui.IsWindowHovered(flags) if flags == nil then flags = 0 end @@ -12708,6 +14912,11 @@ function ImGui.IsWindowHovered(flags) end end + -- When changing hovered window we requires a bit of stationary delay before activating hover timer. + -- FIXME: We don't support delay other than stationary one for now, other delay would need a way + -- to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true + -- for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache. + -- We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow. if bit32.band(flags, ImGuiHoveredFlags.ForTooltip) ~= 0 then flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse) end @@ -12757,11 +14966,12 @@ local function ScaleWindow(window, scale) ImVec2_Copy(window.ContentSize, ImTrunc(window.ContentSize * scale)) end +-- Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) --- @param viewport ImGuiViewportP --- @param scale float function ImGui.ScaleWindowsInViewport(viewport, scale) local g = GImGui - -- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X", viewport.ID) + -- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X\n", viewport.ID) if viewport.Window then ScaleWindow(viewport.Window, scale) @@ -12774,10 +14984,14 @@ function ImGui.ScaleWindowsInViewport(viewport, scale) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] SCROLLING ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Helper to snap on edges when aiming at an item very close to the edge, +-- So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling. +-- When we refactor the scrolling API this may be configurable with a flag? +-- Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default. --- @param target float --- @param snap_min float --- @param snap_max float @@ -12821,6 +15035,7 @@ function CalcNextScrollFromScrollTargetAndClamp(window) return scroll end +-- Scroll to keep newly navigated item fully into view --- @param window ImGuiWindow --- @param item_rect ImRect --- @param flags? ImGuiScrollFlags @@ -12831,10 +15046,14 @@ function ImGui.ScrollToRectEx(window, item_rect, flags) local scroll_rect = ImRect(window.InnerRect.Min - ImVec2(1, 1), window.InnerRect.Max + ImVec2(1, 1)) scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window.DecoInnerSizeX1, scroll_rect.Max.x) scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window.DecoInnerSizeY1, scroll_rect.Max.y) + -- GetForegroundDrawList(window):AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0, 0, 5.0) -- [DEBUG] + -- GetForegroundDrawList(window):AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE) -- [DEBUG] + -- Check that only one behavior is selected per axis IM_ASSERT(bit32.band(flags, ImGuiScrollFlags.MaskX_) == 0 or ImIsPowerOfTwo(bit32.band(flags, ImGuiScrollFlags.MaskX_))) IM_ASSERT(bit32.band(flags, ImGuiScrollFlags.MaskY_) == 0 or ImIsPowerOfTwo(bit32.band(flags, ImGuiScrollFlags.MaskY_))) + -- Defaults local in_flags = flags if bit32.band(flags, ImGuiScrollFlags.MaskX_) == 0 and window.ScrollbarX then flags = bit32.bor(flags, ImGuiScrollFlags.KeepVisibleEdgeX) @@ -12879,7 +15098,9 @@ function ImGui.ScrollToRectEx(window, item_rect, flags) local next_scroll = CalcNextScrollFromScrollTargetAndClamp(window) local delta_scroll = next_scroll - window.Scroll + -- Also scroll parent window to keep us into view if necessary if bit32.band(flags, ImGuiScrollFlags.NoScrollParent) == 0 and bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then + -- FIXME-SCROLL: May be an option? if bit32.band(in_flags, bit32.bor(ImGuiScrollFlags.AlwaysCenterX, ImGuiScrollFlags.KeepVisibleCenterX)) ~= 0 then in_flags = bit32.bor(bit32.band(in_flags, bit32.bnot(ImGuiScrollFlags.MaskX_)), ImGuiScrollFlags.KeepVisibleEdgeX) end @@ -12924,6 +15145,7 @@ function ImGui.ScrollToRect(window, item_rect, flags) ImGui.ScrollToRectEx(window, item_rect, flags or 0) end +-- center_x_ratio: 0.0 left of last item, 0.5 horizontal center of last item, 1.0 right of last item. --- @param center_x_ratio? float function ImGui.SetScrollHereX(center_x_ratio) if center_x_ratio == nil then center_x_ratio = 0.5 end @@ -12931,10 +15153,13 @@ function ImGui.SetScrollHereX(center_x_ratio) local window = g.CurrentWindow local spacing_x = ImMax(window.WindowPadding.x, g.Style.ItemSpacing.x) local target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio) - ImGui.SetScrollFromPosX(window, target_pos_x - window.Pos.x, center_x_ratio) + ImGui.SetScrollFromPosX(window, target_pos_x - window.Pos.x, center_x_ratio) -- Convert from absolute to local pos + + -- Tweak: snap on edges when aiming at an item very close to the edge window.ScrollTargetEdgeSnapDist.x = ImMax(0.0, window.WindowPadding.x - spacing_x) end +-- center_y_ratio: 0.0 top of last item, 0.5 vertical center of last item, 1.0 bottom of last item. --- @param center_y_ratio? float function ImGui.SetScrollHereY(center_y_ratio) if center_y_ratio == nil then center_y_ratio = 0.5 end @@ -12942,7 +15167,9 @@ function ImGui.SetScrollHereY(center_y_ratio) local window = g.CurrentWindow local spacing_y = ImMax(window.WindowPadding.y, g.Style.ItemSpacing.y) local target_pos_y = ImLerp(window.DC.CursorPosPrevLine.y - spacing_y, window.DC.CursorPosPrevLine.y + window.DC.PrevLineSize.y + spacing_y, center_y_ratio) - ImGui.SetScrollFromPosY(window, target_pos_y - window.Pos.y, center_y_ratio) + ImGui.SetScrollFromPosY(window, target_pos_y - window.Pos.y, center_y_ratio) -- Convert from absolute to local pos + + -- Tweak: snap on edges when aiming at an item very close to the edge window.ScrollTargetEdgeSnapDist.y = ImMax(0.0, window.WindowPadding.y - spacing_y) end @@ -12965,6 +15192,16 @@ function ImGui.SetScrollY(window, scroll_y) window.ScrollTargetEdgeSnapDist.y = 0.0 end +-- Note that a local position will vary depending on initial scroll value, +-- This is a little bit confusing so bear with us: +-- - local_pos = (absolution_pos - window.Pos) +-- - So local_x/local_y are 0.0 for a position at the upper-left corner of a window, +-- and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area. +-- - They mostly exist because of legacy API. +-- Following the rules above, when trying to work with scrolling code, consider that: +-- - SetScrollFromPosY(0.0) == SetScrollY(0.0 + scroll.y) == has no effect! +-- - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0) == reset scroll. Of course writing SetScrollY(0.0) directly then makes more sense +-- We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size --- @param window ImGuiWindow --- @param local_x float --- @param center_x_ratio float @@ -12972,7 +15209,7 @@ function ImGui.SetScrollFromPosX(window, local_x, center_x_ratio) if type(window) == "number" then window, local_x, center_x_ratio = GImGui.CurrentWindow, window, local_x end if center_x_ratio == nil then center_x_ratio = 0.5 end IM_ASSERT(center_x_ratio >= 0.0 and center_x_ratio <= 1.0) - window.ScrollTarget.x = IM_TRUNC(local_x - window.DecoOuterSizeX1 - window.DecoInnerSizeX1 + window.Scroll.x) + window.ScrollTarget.x = IM_TRUNC(local_x - window.DecoOuterSizeX1 - window.DecoInnerSizeX1 + window.Scroll.x) -- Convert local position to scroll offset window.ScrollTargetCenterRatio.x = center_x_ratio window.ScrollTargetEdgeSnapDist.x = 0.0 end @@ -12984,14 +15221,14 @@ function ImGui.SetScrollFromPosY(window, local_y, center_y_ratio) if type(window) == "number" then window, local_y, center_y_ratio = GImGui.CurrentWindow, window, local_y end if center_y_ratio == nil then center_y_ratio = 0.5 end IM_ASSERT(center_y_ratio >= 0.0 and center_y_ratio <= 1.0) - window.ScrollTarget.y = IM_TRUNC(local_y - window.DecoOuterSizeY1 - window.DecoInnerSizeY1 + window.Scroll.y) + window.ScrollTarget.y = IM_TRUNC(local_y - window.DecoOuterSizeY1 - window.DecoInnerSizeY1 + window.Scroll.y) -- Convert local position to scroll offset window.ScrollTargetCenterRatio.y = center_y_ratio window.ScrollTargetEdgeSnapDist.y = 0.0 end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] TOOLTIPS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- @param tooltip_flags ImGuiTooltipFlags --- @param extra_window_flags ImGuiWindowFlags @@ -13000,6 +15237,12 @@ function ImGui.BeginTooltipEx(tooltip_flags, extra_window_flags) local is_dragdrop_tooltip = g.DragDropWithinSource or g.DragDropWithinTarget if is_dragdrop_tooltip then + -- Drag and Drop tooltips are positioning differently than other tooltips: + -- - 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 positioning logic of other tooltips (not drag and drop ones). + -- local tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding local is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource.TouchScreen) if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) == 0 then @@ -13016,10 +15259,12 @@ function ImGui.BeginTooltipEx(tooltip_flags, extra_window_flags) local bg_alpha = g.Style.Colors[ImGuiCol.PopupBg].w * 0.60 ImGui.SetNextWindowBgAlpha(bg_alpha) + -- PushStyleVar(ImGuiStyleVar.Alpha, g.Style.Alpha * 0.60) -- This would be nice but e.g ColorButton with checkerboard has issue with transparent colors :( tooltip_flags = bit32.bor(tooltip_flags, ImGuiTooltipFlags.OverridePrevious) end + -- Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. if (bit32.band(tooltip_flags, ImGuiTooltipFlags.OverridePrevious) ~= 0) and g.TooltipPreviousWindow ~= nil and g.TooltipPreviousWindow.Active and not ImGui.IsWindowInBeginStack(g.TooltipPreviousWindow) then -- IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name) ImGui.SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow) @@ -13032,7 +15277,11 @@ function ImGui.BeginTooltipEx(tooltip_flags, extra_window_flags) local flags = bit32.bor(ImGuiWindowFlags.Tooltip, ImGuiWindowFlags.NoInputs, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.AlwaysAutoResize) ImGui.Begin(window_name, nil, bit32.bor(flags, extra_window_flags)) - + -- 2023-03-09: Added bool return value to the API, but currently always returning true. + -- If this ever returns false we need to update BeginDragDropSource() accordingly. + -- if (!ret) + -- End(); + -- return ret; return true end @@ -13062,6 +15311,8 @@ function ImGui.SetTooltip(fmt, ...) ImGui.EndTooltip() end +-- Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'. +-- Defaults to == ImGuiHoveredFlags.Stationary | ImGuiHoveredFlags.DelayShort when using the mouse. --- @param fmt string --- @param ... any function ImGui.SetItemTooltip(fmt, ...) @@ -13070,10 +15321,23 @@ function ImGui.SetItemTooltip(fmt, ...) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] POPUPS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- 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 nil +-- Notes: +-- - FindBlockingModal(nil) == nil is generally equivalent to GetTopMostPopupModal() == nil. +-- Only difference is here we check for .Active/WasActive but it may be unnecessary. --- @param window? ImGuiWindow function ImGui.FindBlockingModal(window) local g = GImGui @@ -13081,6 +15345,7 @@ function ImGui.FindBlockingModal(window) return nil end + -- Find a modal that has common parent with specified window. Specified window should be positioned behind that modal. for i = 1, g.OpenPopupStack.Size do repeat local popup_data = g.OpenPopupStack.Data[i] @@ -13088,17 +15353,17 @@ function ImGui.FindBlockingModal(window) if popup_window == nil or bit32.band(popup_window.Flags, ImGuiWindowFlags.Modal) == 0 then break end - if not popup_window.Active and not popup_window.WasActive then + if not popup_window.Active and not popup_window.WasActive then -- Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows. break end - if window == nil then + if window == nil then -- FindBlockingModal(nil) test for if FocusWindow(nil) is naturally possible via a mouse click. return popup_window end - if ImGui.IsWindowWithinBeginStackOf(window, popup_window) then + if ImGui.IsWindowWithinBeginStackOf(window, popup_window) then -- Window may be over modal break end - do return popup_window end + do return popup_window end -- Place window right below first block modal until true end @@ -13120,6 +15385,12 @@ function ImGui.OpenPopup(id, popup_flags) end end +-- Mark popup as open (toggle toward open state). +-- - Return true when the popup is toggled open, which allows you to capture local state if needed. +-- You may also call IsWindowAppearing() inside the later BeginPopup() scope if you need to prepare/compute data for the popup. +-- - Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. +-- - Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). +-- - One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to nil). --- @param id ImGuiID --- @param popup_flags ImGuiPopupFlags function ImGui.OpenPopupEx(id, popup_flags) @@ -13133,7 +15404,7 @@ function ImGui.OpenPopupEx(id, popup_flags) end end - local popup_ref = ImGuiPopupData() + local popup_ref = ImGuiPopupData() -- Tagged as new ref as Window will be set back to nil if we write this into OpenPopupStack. popup_ref.PopupId = id popup_ref.Window = nil popup_ref.RestoreNavWindow = g.NavWindow -- When popup closes focus may be restored to NavWindow (depend on window type). @@ -13146,7 +15417,7 @@ function ImGui.OpenPopupEx(id, popup_flags) ImVec2_Copy(popup_ref.OpenMousePos, popup_ref.OpenPopupPos) end - -- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)", id) + -- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id) if g.OpenPopupStack.Size < current_stack_size + 1 then g.OpenPopupStack:push_back(popup_ref) return true @@ -13192,7 +15463,7 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p end -- Don't close our own child popup windows. - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d", ref_window and ref_window.Name or "", restore_focus_to_window_under_popup) + -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window and ref_window.Name or "", restore_focus_to_window_under_popup) local popup_count_to_keep = 0 if ref_window then -- Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow) @@ -13212,12 +15483,13 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p -- Window -> Popup1 -> Window2(Ref) -- - Clicking/focusing Popup1 will close Popup2 and Popup3: -- Window -> Popup1(Ref) -> Popup2 -> Popup3 - -- - Each popups may contain child windows, which is why we compare ->RootWindow! + -- - Each popups may contain child windows, which is why we compare .RootWindowDockTree! -- Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child -- We step through every popup from bottom to top to validate their position relative to reference window. ref_window_is_descendent_of_popup = false for n = popup_count_to_keep, g.OpenPopupStack.Size - 1 do local popup_window = g.OpenPopupStack.Data[n + 1].Window + -- if (popup_window.RootWindowDockTree == ref_window.RootWindowDockTree) -- FIXME-MERGE if popup_window and ImGui.IsWindowWithinBeginStackOf(ref_window, popup_window) then ref_window_is_descendent_of_popup = true break @@ -13235,7 +15507,7 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p end end if popup_count_to_keep < g.OpenPopupStack.Size then -- This test is not required but it allows to set a convenient breakpoint on the statement below - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")", ref_window and ref_window.Name or "") + -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window and ref_window.Name or "") ImGui.ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup) end end @@ -13244,7 +15516,7 @@ end --- @param restore_focus_to_window_under_popup bool function ImGui.ClosePopupToLevel(remaining, restore_focus_to_window_under_popup) local g = GImGui - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d", remaining, restore_focus_to_window_under_popup) + -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup) IM_ASSERT(remaining >= 0 and remaining < g.OpenPopupStack.Size) -- if bit32.band(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then -- for n = remaining + 1, g.OpenPopupStack.Size do @@ -13277,7 +15549,7 @@ function ImGui.ClosePopupToLevel(remaining, restore_focus_to_window_under_popup) end end --- Close the popup we have Begin-ed into +-- Close the popup we have begin-ed into. function ImGui.CloseCurrentPopup() local g = GImGui local popup_idx = g.BeginPopupStack.Size @@ -13315,12 +15587,13 @@ function ImGui.CloseCurrentPopup() end end +-- Attention! BeginPopup() adds default flags when calling BeginPopupEx()! --- @param id ImGuiID --- @param extra_window_flags ImGuiWindowFlags function ImGui.BeginPopupEx(id, extra_window_flags) local g = GImGui if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values return false end @@ -13343,21 +15616,24 @@ end function ImGui.BeginPopupMenuEx(id, label, extra_window_flags) local g = GImGui if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values return false end + -- As we bypass BeginChild(), set ImGuiChildFlags.AlwaysAutoResize as it is checked independently from ImGuiWindowFlags.AlwaysAutoResize for now (see #9355) + -- Ideally we should remove setting ImGuiWindowFlags.AlwaysAutoResize in BeginChild(). if bit32.band(extra_window_flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(extra_window_flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0 then ImGui.SetNextWindowChildFlags(ImGuiChildFlags.AlwaysAutoResize, true) end IM_ASSERT(bit32.band(extra_window_flags, ImGuiWindowFlags.ChildMenu) ~= 0) - local name = ImFormatString("%s###Menu_%02d", label, g.BeginMenuDepth) + local name = ImFormatString("%s###Menu_%02d", label, g.BeginMenuDepth) -- Recycle windows based on depth local is_open _, is_open = ImGui.Begin(name, nil, bit32.bor(extra_window_flags, ImGuiWindowFlags.Popup)) - if not is_open then + if not is_open then -- NB: Begin can return false when the popup is completely clipped (e.g. zero size display) ImGui.EndPopup() end + -- g.CurrentWindow.FocusRouteParentWindow = g.CurrentWindow.ParentWindowInBeginStack return is_open end @@ -13399,6 +15675,11 @@ function ImGui.EndPopup() g.WithinEndChildID = backup_within_end_child_id end +-- r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) +-- r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it. +-- (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor +-- information are available, it may represent the entire platform monitor from the frame of reference of the current viewport. +-- this allows us to have tooltips/popups displayed out of the parent viewport.) --- @param ref_pos ImVec2 --- @param size ImVec2 --- @param last_dir ImGuiDir @@ -13450,7 +15731,7 @@ function ImGui.FindBestWindowPosForPopupEx(ref_pos, size, last_dir, r_outer, r_a repeat local dir = (n == 0) and last_dir or dir_preferred_order[n] - if n ~= 0 and dir == last_dir then + if n ~= 0 and dir == last_dir then -- Already tried this direction? break end @@ -13497,6 +15778,7 @@ function ImGui.FindBestWindowPosForPopupEx(ref_pos, size, last_dir, r_outer, r_a return pos, last_dir end +-- Note that this is used for popups, which can overlap the non work-area of individual viewports. --- @param window ImGuiWindow --- @return ImRect --- @nodiscard @@ -13577,6 +15859,7 @@ function ImGui.FindBestWindowPosForPopup(window) 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. end + -- ImGui.GetForegroundDrawList():AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255)) local pos pos, window.AutoPosLastDirection = ImGui.FindBestWindowPosForPopupEx(tooltip_pos, window.Size, window.AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy.Tooltip) @@ -13592,7 +15875,6 @@ end --- @return ImGuiMouseButton function ImGui.GetMouseButtonFromPopupFlags(flags) IM_ASSERT(bit32.band(flags, ImGuiPopupFlags.InvalidMask_) == 0) - if bit32.band(flags, ImGuiPopupFlags.MouseButtonMask_) ~= 0 then return bit32.rshift(bit32.band(flags, ImGuiPopupFlags.MouseButtonMask_), ImGuiPopupFlags.MouseButtonShift_) - 1 end @@ -13615,6 +15897,8 @@ function ImGui.IsPopupOpenRequestForItem(popup_flags, id) return false end +-- Helper to open a popup if mouse button is released over the item +-- - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup() --- @param str_id? string --- @param popup_flags? ImGuiPopupFlags @@ -13625,14 +15909,30 @@ function ImGui.OpenPopupOnItemClick(str_id, popup_flags) if ImGui.IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID) then local window = g.CurrentWindow local id - if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end - IM_ASSERT(id ~= 0) + if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end -- If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + IM_ASSERT(id ~= 0) -- You cannot pass a nil str_id if the last item has no identifier (e.g. a Text() item) return ImGui.OpenPopupEx(id, popup_flags) end return false end +-- This is a helper to handle the simplest case of associating one named popup to one given widget. +-- - To create a popup associated to the last item, you generally want to pass a nil value to str_id. +-- - To create a popup with a specific identifier, pass it in str_id. +-- - This is useful when using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call. +-- - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id. +-- - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). +-- This is essentially the same as: +-- id = str_id ? GetID(str_id) : GetItemID(); +-- OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight); +-- return BeginPopup(id); +-- Which is essentially the same as: +-- id = str_id ? GetID(str_id) : GetItemID(); +-- if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) +-- OpenPopup(id); +-- return BeginPopup(id); +-- The main difference being that this is tweaked to avoid computing the ID twice. --- @param str_id? string --- @param popup_flags? ImGuiPopupFlags --- @return bool @@ -13645,17 +15945,21 @@ function ImGui.BeginPopupContextItem(str_id, popup_flags) return false end local id - if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end - IM_ASSERT(id ~= 0) + if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end -- If user hasn't passed an ID, we can use the LastItem ID. Using LastItem ID as a Popup ID won't conflict! + IM_ASSERT(id ~= 0) -- You cannot pass a nil str_id if the last item has no identifier (e.g. a Text() item) if ImGui.IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID) then ImGui.OpenPopupEx(id, popup_flags) end return ImGui.BeginPopupEx(id, bit32.bor(ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoSavedSettings)) end ---------------------------------------------------------------------------------------- --- [SECTION] NAVIGATION ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] KEYBOARD/GAMEPAD NAVIGATION +------------------------------------------------------------------------------- + +-- FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked. +-- In our terminology those should be interchangeable, yet right now this is super confusing. +-- Those two functions are merely a legacy artifact, so at minimum naming should be clarified. --- @param id ImGuiID function ImGui.PushFocusScope(id) @@ -13696,13 +16000,15 @@ end function ImGui.SetNavFocusScope(focus_scope_id) local g = GImGui g.NavFocusScopeId = focus_scope_id - g.NavFocusRoute:resize(0) + g.NavFocusRoute:resize(0) -- Invalidate if focus_scope_id == 0 then return end IM_ASSERT(g.NavWindow ~= nil) + -- Store current path (in reverse order) if focus_scope_id == g.CurrentFocusScopeId then + -- Top of focus stack contains local focus scopes inside current window for n = g.FocusScopeStack.Size, 1, -1 do local data = g.FocusScopeStack.Data[n] if data.WindowID ~= g.CurrentWindow.ID then @@ -13719,6 +16025,7 @@ function ImGui.SetNavFocusScope(focus_scope_id) return end + -- Then follow on manually set ParentWindowForFocusRoute field (#6798) local window = g.NavWindow.ParentWindowForFocusRoute while window ~= nil do local data = ImGuiFocusScopeData() @@ -13727,7 +16034,7 @@ function ImGui.SetNavFocusScope(focus_scope_id) g.NavFocusRoute:push_back(data) window = window.ParentWindowForFocusRoute end - IM_ASSERT(g.NavFocusRoute.Size < 100) + IM_ASSERT(g.NavFocusRoute.Size < 100) -- Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3 end function ImGui.SetItemDefaultFocus() @@ -13744,11 +16051,13 @@ function ImGui.SetItemDefaultFocus() ImGui.NavApplyItemToResult(g.NavInitResult) ImGui.NavUpdateAnyRequestFlag() + -- Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll) if not window.ClipRect:Contains(g.LastItemData.Rect) then ImGui.ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags.None) end end +-- (was called NavRestoreHighlightAfterMove() before 1.91.4) function ImGui.SetNavCursorVisibleAfterMove() local g = GImGui if g.NavWindow and (bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) ~= 0) then @@ -13798,10 +16107,13 @@ function ImGui.SetNavID(id, nav_layer, focus_scope_id, rect_rel) g.NavWindow.NavLastIds[nav_layer] = id ImRect_Copy(g.NavWindow.NavRectRel[nav_layer], rect_rel) + -- Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y) end +-- FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0). +-- This way we could find the last focused window among our children. It would be much less confusing this way? --- @param nav_window ImGuiWindow function ImGui.NavSaveLastChildNavWindowIntoParent(nav_window) local parent = nav_window @@ -13813,6 +16125,8 @@ function ImGui.NavSaveLastChildNavWindowIntoParent(nav_window) end end +-- Restore the last focused child. +-- Call when we are expected to land on the Main Layer (0) after FocusWindow() --- @param window ImGuiWindow function ImGui.NavRestoreLastChildNavWindow(window) if window.NavLastChildNavWindow and window.NavLastChildNavWindow.WasActive then @@ -13826,8 +16140,9 @@ function ImGui.NavRestoreLayer(layer) local g = GImGui if layer == ImGuiNavLayer.Main then local prev_nav_window = g.NavWindow - g.NavWindow = ImGui.NavRestoreLastChildNavWindow(g.NavWindow) + g.NavWindow = ImGui.NavRestoreLastChildNavWindow(g.NavWindow) -- FIXME-NAV: Should clear ongoing nav requests? g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid + -- if (prev_nav_window) IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name) end local window = g.NavWindow if window.NavLastIds[layer] ~= 0 then @@ -13853,9 +16168,11 @@ function ImGui.NavUpdateAnyRequestFlag() end end +-- This needs to be called before we submit any widget (aka in or before Begin) --- @param window ImGuiWindow --- @param force_reinit bool function ImGui.NavInitWindow(window, force_reinit) + -- FIXME: ChildWindow test here is wrong for docking local g = GImGui IM_ASSERT(window == g.NavWindow) @@ -13882,6 +16199,8 @@ function ImGui.NavInitWindow(window, force_reinit) end end +-- Positioning logic altered slightly for remote activation: for Popup we want to use item rect, for Tooltip we leave things alone. (#9138) +-- When calling for ImGuiWindowFlags.Popup we use LastItemData. --- @param window_type ImGuiWindowFlags --- @return ImGuiInputSource function ImGui.NavCalcPreferredRefPosSource(window_type) @@ -13985,7 +16304,7 @@ function ImGui.NavUpdateWindowingTarget(focus_change_dir) if window_target == nil then window_target = ImGui.FindWindowNavFocusable((focus_change_dir < 0) and g.WindowsFocusOrder.Size or 1, i_current, focus_change_dir) end - if window_target then + if window_target then -- Don't reset windowing target if there's a single window in the list g.NavWindowingTarget = window_target g.NavWindowingTargetAnim = window_target ImVec2_CopyV(g.NavWindowingAccumDeltaPos, 0.0, 0.0) @@ -13994,8 +16313,11 @@ function ImGui.NavUpdateWindowingTarget(focus_change_dir) g.NavWindowingToggleLayer = false end +-- Apply focus and close overlay --- @param apply_focus_window ImGuiWindow function ImGui.NavUpdateWindowingApplyFocus(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() local g = GImGui if g.NavWindow == nil or apply_focus_window ~= g.NavWindow.RootWindow then local previous_viewport = g.NavWindow and g.NavWindow.Viewport or nil @@ -14005,14 +16327,22 @@ function ImGui.NavUpdateWindowingApplyFocus(apply_focus_window) ImGui.FocusWindow(apply_focus_window, ImGuiFocusRequestFlags.RestoreFocusedChild) IM_ASSERT(g.NavWindow ~= nil) apply_focus_window = g.NavWindow - if apply_focus_window.NavLastIds[ImGuiNavLayer.Main] == 0 then + if apply_focus_window.NavLastIds[ImGuiNavLayer.Main] == 0 then -- FIXME: This is the equivalent of the 'if (g.NavId == 0) { NavInitWindow() }' in DockNodeUpdateTabBar(). ImGui.NavInitWindow(apply_focus_window, false) end + -- 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 == bit32.lshift(1, ImGuiNavLayer.Menu) then g.NavLayer = ImGuiNavLayer.Menu end + -- Request OS level focus if apply_focus_window.Viewport ~= previous_viewport and g.PlatformIO.Platform_SetWindowFocus then g.PlatformIO.Platform_SetWindowFocus(apply_focus_window.Viewport) end @@ -14020,6 +16350,9 @@ function ImGui.NavUpdateWindowingApplyFocus(apply_focus_window) g.NavWindowingTarget = nil end +-- 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) function ImGui.NavUpdateWindowing() local g = GImGui local io = g.IO @@ -14028,11 +16361,12 @@ function ImGui.NavUpdateWindowing() local apply_toggle_layer = false local modal_window = ImGui.GetTopMostPopupModal() - local allow_windowing = (modal_window == nil) + local allow_windowing = (modal_window == nil) -- FIXME: This prevent Ctrl+Tab from being usable with windows that are inside the Begin-stack of that modal. if not allow_windowing then g.NavWindowingTarget = nil end + -- Fade out if g.NavWindowingTargetAnim and g.NavWindowingTarget == nil then g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0, 0.0) if g.DimBgRatio <= 0.0 and g.NavWindowingHighlightAlpha <= 0.0 then @@ -14040,6 +16374,8 @@ function ImGui.NavUpdateWindowing() end end + -- 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) local owner_id = ImHashStr("##NavUpdateWindowing") local nav_gamepad_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0 local nav_keyboard_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 @@ -14047,10 +16383,10 @@ function ImGui.NavUpdateWindowing() local keyboard_prev_window = allow_windowing and g.ConfigNavWindowingKeyPrev ~= 0 and ImGui.Shortcut(g.ConfigNavWindowingKeyPrev, bit32.bor(ImGuiInputFlags.Repeat, ImGuiInputFlags.RouteAlways), owner_id) local start_toggling_with_gamepad = nav_gamepad_active and g.NavWindowingTarget == nil and ImGui.Shortcut(ImGuiKey.NavGamepadMenu, ImGuiInputFlags.RouteAlways, owner_id) local start_windowing_with_gamepad = allow_windowing and start_toggling_with_gamepad - local start_windowing_with_keyboard = allow_windowing and g.NavWindowingTarget == nil and (keyboard_next_window or keyboard_prev_window) + local start_windowing_with_keyboard = allow_windowing and g.NavWindowingTarget == nil and (keyboard_next_window or keyboard_prev_window) -- Note: enabled even without NavEnableKeyboard! local just_started_windowing_from_null_focus = false if start_toggling_with_gamepad then - g.NavWindowingToggleLayer = true + g.NavWindowingToggleLayer = true -- Gamepad starts toggling layer g.NavWindowingToggleKey = ImGuiKey.NavGamepadMenu g.NavWindowingInputSource = ImGuiInputSource.Gamepad g.NavInputSource = ImGuiInputSource.Gamepad @@ -14060,7 +16396,7 @@ function ImGui.NavUpdateWindowing() if window then if start_windowing_with_keyboard or g.ConfigNavWindowingWithGamepad then g.NavWindowingTarget = window.RootWindow - g.NavWindowingTargetAnim = window.RootWindow + g.NavWindowingTargetAnim = window.RootWindow -- Current location end g.NavWindowingTimer = 0.0 g.NavWindowingHighlightAlpha = 0.0 @@ -14072,17 +16408,22 @@ function ImGui.NavUpdateWindowing() just_started_windowing_from_null_focus = true end + -- Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects. if keyboard_next_window or keyboard_prev_window then ImGui.SetKeyOwnersForKeyChord(bit32.band(bit32.bor(g.ConfigNavWindowingKeyNext, g.ConfigNavWindowingKeyPrev), ImGuiMod_Mask_), owner_id) end end end + -- Gamepad update if (g.NavWindowingTarget or g.NavWindowingToggleLayer) and g.NavWindowingInputSource == ImGuiInputSource.Gamepad then if g.NavWindowingTarget ~= nil then + -- 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 = g.NavWindowingTimer + io.DeltaTime g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05)) + -- Select window to focus local focus_change_dir = (ImGui.IsKeyPressedEx(ImGuiKey.GamepadL1, ImGuiInputFlags.None, ImGuiKeyOwner_Any) and 1 or 0) - (ImGui.IsKeyPressedEx(ImGuiKey.GamepadR1, ImGuiInputFlags.None, ImGuiKeyOwner_Any) and 1 or 0) if focus_change_dir ~= 0 and not just_started_windowing_from_null_focus then ImGui.NavUpdateWindowingTarget(focus_change_dir) @@ -14090,8 +16431,9 @@ function ImGui.NavUpdateWindowing() end end + -- Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most) if not ImGui.IsKeyDown(ImGuiKey.NavGamepadMenu) then - g.NavWindowingToggleLayer = g.NavWindowingToggleLayer and (g.NavWindowingHighlightAlpha < 1.0) + g.NavWindowingToggleLayer = g.NavWindowingToggleLayer and (g.NavWindowingHighlightAlpha < 1.0) -- Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. if g.NavWindowingToggleLayer and g.NavWindow then apply_toggle_layer = true elseif not g.NavWindowingToggleLayer then @@ -14102,13 +16444,15 @@ function ImGui.NavUpdateWindowing() end end + -- Keyboard: Focus if g.NavWindowingTarget and g.NavWindowingInputSource == ImGuiInputSource.Keyboard then + -- Visuals only appears after a brief time after pressing TAB the first time, so that a fast Ctrl+Tab doesn't add visual noise local shared_mods = bit32.band( bit32.band((g.ConfigNavWindowingKeyNext ~= 0) and g.ConfigNavWindowingKeyNext or ImGuiMod_Mask_, (g.ConfigNavWindowingKeyPrev ~= 0) and g.ConfigNavWindowingKeyPrev or ImGuiMod_Mask_), ImGuiMod_Mask_) - IM_ASSERT(shared_mods ~= 0) + 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 = g.NavWindowingTimer + io.DeltaTime - g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05)) + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05)) -- 1.0f if (keyboard_next_window or keyboard_prev_window) and not just_started_windowing_from_null_focus then ImGui.NavUpdateWindowingTarget(keyboard_next_window and -1 or 1) elseif bit32.band(io.KeyMods, shared_mods) ~= shared_mods then @@ -14116,6 +16460,7 @@ function ImGui.NavUpdateWindowing() end end + -- Keyboard: Press and Release Alt to toggle menu layer local windowing_toggle_keys = { ImGuiKey.LeftAlt, ImGuiKey.RightAlt } local windowing_toggle_layer_start = false if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 then @@ -14131,6 +16476,10 @@ function ImGui.NavUpdateWindowing() end end if g.NavWindowingToggleLayer and g.NavWindowingInputSource == ImGuiInputSource.Keyboard then + -- 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) + -- - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). + -- We cancel toggling nav layer if an owner has claimed the key. if io.InputQueueCharacters.Size > 0 or io.KeyCtrl or io.KeyShift or io.KeySuper then g.NavWindowingToggleLayer = false elseif windowing_toggle_layer_start == false and g.LastKeyboardKeyPressTime == g.Time then @@ -14139,6 +16488,8 @@ function ImGui.NavUpdateWindowing() g.NavWindowingToggleLayer = false end + -- Apply layer toggle on Alt release + -- Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss. if ImGui.IsKeyReleased(g.NavWindowingToggleKey) and g.NavWindowingToggleLayer then if g.ActiveId == 0 or g.ActiveIdAllowOverlap then if ImGui.IsMousePosValid(io.MousePos) == ImGui.IsMousePosValid(io.MousePosPrev) then @@ -14151,6 +16502,7 @@ function ImGui.NavUpdateWindowing() end end + -- Move window if g.NavWindowingTarget and bit32.band(g.NavWindowingTarget.Flags, ImGuiWindowFlags.NoMove) == 0 then local nav_move_dir if g.NavInputSource == ImGuiInputSource.Keyboard and not io.KeyShift then @@ -14173,13 +16525,16 @@ function ImGui.NavUpdateWindowing() end end + -- Apply final focus if apply_focus_window then ImGui.NavUpdateWindowingApplyFocus(apply_focus_window) end + -- Apply menu/layer toggle if apply_toggle_layer and g.NavWindow then ImGui.ClearActiveID() + -- Move to parent menu if necessary local new_nav_window = g.NavWindow while new_nav_window.ParentWindow and bit32.band(new_nav_window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) == 0 @@ -14193,8 +16548,10 @@ function ImGui.NavUpdateWindowing() new_nav_window.NavLastChildNavWindow = old_nav_window end + -- Toggle layer local new_nav_layer = (bit32.band(g.NavWindow.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) ~= 0) and bit32.bxor(g.NavLayer, 1) or ImGuiNavLayer.Main if new_nav_layer ~= g.NavLayer then + -- Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?) local preserve_layer_1_nav_id = (new_nav_window.DockNodeAsHost ~= nil) if new_nav_layer == ImGuiNavLayer.Menu and not preserve_layer_1_nav_id then g.NavWindow.NavLastIds[new_nav_layer] = 0 @@ -14226,6 +16583,7 @@ function ImGui.NavUpdateContextMenuRequest() g.NavOpenContextMenuItemId = g.NavId g.NavOpenContextMenuWindowId = g.NavWindow.ID + -- Allow triggering for Begin()..BeginPopupContextItem(). A possible alternative would be to use g.NavLayer == ImGuiNavLayer.Menu. if g.NavId == g.NavWindow:GetID("#CLOSE") or g.NavId == g.NavWindow:GetID("#COLLAPSE") then g.NavOpenContextMenuItemId = g.NavWindow.MoveId end @@ -14234,6 +16592,7 @@ function ImGui.NavUpdateContextMenuRequest() ImGui.SetNavCursorVisibleAfterMove() end +-- FIXME: ScoringRect is not set --- @param move_dir ImGuiDir --- @param clip_dir ImGuiDir --- @param move_flags ImGuiNavMoveFlags @@ -14241,6 +16600,8 @@ end function ImGui.NavMoveRequestSubmit(move_dir, clip_dir, move_flags, scroll_flags) local g = GImGui IM_ASSERT(g.NavWindow ~= nil) + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name) + if bit32.band(move_flags, ImGuiNavMoveFlags.IsTabbing) ~= 0 then move_flags = bit32.bor(move_flags, ImGuiNavMoveFlags.AllowCurrentNavId) end @@ -14260,13 +16621,19 @@ function ImGui.NavMoveRequestSubmit(move_dir, clip_dir, move_flags, scroll_flags ImGui.NavUpdateAnyRequestFlag() end +-- Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position --- @param r ImRect --- @param preferred_pos_rel ImVec2 --- @param move_dir ImGuiDir --- @param move_flags ImGuiNavMoveFlags function ImGui.NavBiasScoringRect(r, preferred_pos_rel, move_dir, move_flags) + -- Bias initial rect local g = GImGui local rel_to_abs_offset = g.NavWindow.DC.CursorStartPos + + -- Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias. + -- - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column. + -- - But each successful move sets new bias on one axis, only cleared when using mouse. if bit32.band(move_flags, ImGuiNavMoveFlags.Forwarded) == 0 then if preferred_pos_rel.x == FLT_MAX then preferred_pos_rel.x = ImMin(r.Min.x + 1.0, r.Max.x) - rel_to_abs_offset.x @@ -14275,6 +16642,8 @@ function ImGui.NavBiasScoringRect(r, preferred_pos_rel, move_dir, move_flags) preferred_pos_rel.y = r:GetCenter().y - rel_to_abs_offset.y end end + + -- Apply general bias on the other axis if (move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and preferred_pos_rel.x ~= FLT_MAX then local new_x = preferred_pos_rel.x + rel_to_abs_offset.x r.Min.x = new_x; r.Max.x = new_x @@ -14284,6 +16653,10 @@ function ImGui.NavBiasScoringRect(r, preferred_pos_rel, move_dir, move_flags) end end +-- Handle PageUp/PageDown/Home/End keys +-- Called from NavUpdateCreateMoveRequest() which will use our output to create a move request +-- FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference +-- FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid? --- @return float function ImGui.NavUpdatePageUpPageDown() local g = GImGui @@ -14296,7 +16669,7 @@ function ImGui.NavUpdatePageUpPageDown() local page_down_held = ImGui.IsKeyDown(ImGuiKey.PageDown, ImGuiKeyOwner_NoOwner) local home_pressed = ImGui.IsKeyPressedEx(ImGuiKey.Home, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) local end_pressed = ImGui.IsKeyPressedEx(ImGuiKey.End, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) - if page_up_held == page_down_held and home_pressed == end_pressed then + if page_up_held == page_down_held and home_pressed == end_pressed then -- Proceed if either (not both) are pressed, otherwise early out return 0.0 end @@ -14305,6 +16678,7 @@ function ImGui.NavUpdatePageUpPageDown() end if bit32.band(window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Main)) == 0 and window.DC.NavWindowHasScrollY then + -- Fallback manual-scroll when window has no navigable item if ImGui.IsKeyPressedEx(ImGuiKey.PageUp, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then ImGui.SetScrollY(window, window.Scroll.y - window.InnerRect:GetHeight()) elseif ImGui.IsKeyPressedEx(ImGuiKey.PageDown, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then @@ -14320,21 +16694,25 @@ function ImGui.NavUpdatePageUpPageDown() local nav_scoring_rect_offset_y = 0.0 if ImGui.IsKeyPressedEx(ImGuiKey.PageUp, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then nav_scoring_rect_offset_y = -page_offset_y - g.NavMoveDir = ImGuiDir.Down + g.NavMoveDir = ImGuiDir.Down -- Because our scoring rect is offset up, we request the down direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir.Up - g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) + g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) -- ImGuiNavMoveFlags.AlsoScoreVisibleSet may be added later elseif ImGui.IsKeyPressedEx(ImGuiKey.PageDown, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then nav_scoring_rect_offset_y = page_offset_y - g.NavMoveDir = ImGuiDir.Up + g.NavMoveDir = ImGuiDir.Up -- Because our scoring rect is offset down, we request the up direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir.Down - g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) + g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) -- ImGuiNavMoveFlags.AlsoScoreVisibleSet may be added later elseif home_pressed then + -- FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y + -- Scrolling will be handled via the ImGuiNavMoveFlags.ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result. + -- Preserve current horizontal position if we have any. nav_rect_rel.Min.y = 0.0; nav_rect_rel.Max.y = 0.0 if nav_rect_rel:IsInverted() then nav_rect_rel.Min.x = 0.0; nav_rect_rel.Max.x = 0.0 end g.NavMoveDir = ImGuiDir.Down g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.ScrollToEdgeY) + -- FIXME-NAV: MoveClipDir left to _None, intentional? elseif end_pressed then nav_rect_rel.Min.y = window.ContentSize.y; nav_rect_rel.Max.y = window.ContentSize.y if nav_rect_rel:IsInverted() then @@ -14342,6 +16720,7 @@ function ImGui.NavUpdatePageUpPageDown() end g.NavMoveDir = ImGuiDir.Up g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.ScrollToEdgeY) + -- FIXME-NAV: MoveClipDir left to _None, intentional? end return nav_scoring_rect_offset_y end @@ -14356,9 +16735,13 @@ function ImGui.NavUpdateCreateMoveRequest() local nav_keyboard_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 if g.NavMoveForwardToNextFrame and window ~= nil then + -- Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window) + -- (preserve most state, which were already set by the NavMoveRequestForward() function) IM_ASSERT(g.NavMoveDir ~= ImGuiDir.None and g.NavMoveClipDir ~= ImGuiDir.None) IM_ASSERT(bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) ~= 0) + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir) else + -- Initiate directional inputs request g.NavMoveDir = ImGuiDir.None g.NavMoveFlags = ImGuiNavMoveFlags.None g.NavMoveScrollFlags = ImGuiScrollFlags.None @@ -14373,33 +16756,46 @@ function ImGui.NavUpdateCreateMoveRequest() ImRect_Copy(g.NavScoringNoClipRect, ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX)) end + -- Update PageUp/PageDown/Home/End scroll + -- FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags.NavEnableKeyboard flag? local scoring_page_offset_y = 0.0 if window and g.NavMoveDir == ImGuiDir.None and nav_keyboard_active then scoring_page_offset_y = ImGui.NavUpdatePageUpPageDown() end + -- Submit g.NavMoveForwardToNextFrame = false if g.NavMoveDir ~= ImGuiDir.None then ImGui.NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags) end + -- Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match) if g.NavMoveSubmitted and g.NavId == 0 then + -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer) g.NavInitRequest = true; g.NavInitRequestFromMove = true g.NavInitResult.ID = 0 - if g.IO.ConfigNavCursorVisibleAuto then + if g.IO.ConfigNavCursorVisibleAuto then -- NO check for _NoNavInputs here as we assume MoveRequests cannot be created. g.NavCursorVisible = true end end - if g.NavMoveSubmitted and g.NavInputSource == ImGuiInputSource.Gamepad and g.NavLayer == ImGuiNavLayer.Main and window ~= nil then + -- When using gamepad, we project the reference nav bounding box into window visible area. + -- This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, + -- since with gamepad all movements are relative (can't focus a visible object like we can with the mouse). + if g.NavMoveSubmitted and g.NavInputSource == ImGuiInputSource.Gamepad and g.NavLayer == ImGuiNavLayer.Main and window ~= nil then -- and (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded)) local clamp_x = bit32.band(g.NavMoveFlags, bit32.bor(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.WrapX)) == 0 local clamp_y = bit32.band(g.NavMoveFlags, bit32.bor(ImGuiNavMoveFlags.LoopY, ImGuiNavMoveFlags.WrapY)) == 0 local inner_rect_rel = ImGui.WindowRectAbsToRel(window, ImRect(ImVec2(window.InnerRect.Min.x - 1, window.InnerRect.Min.y - 1), ImVec2(window.InnerRect.Max.x + 1, window.InnerRect.Max.y + 1))) + + -- Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171) + -- Otherwise 'inner_rect_rel' would be off on the move result frame. local next_scroll = CalcNextScrollFromScrollTargetAndClamp(window) inner_rect_rel:Translate(ImVec2(next_scroll.x - window.Scroll.x, next_scroll.y - window.Scroll.y)) + if (clamp_x or clamp_y) and not inner_rect_rel:Contains(window.NavRectRel[g.NavLayer]) then + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n") local pad_x = ImMin(inner_rect_rel:GetWidth(), window.FontRefSize * 0.5) - local pad_y = ImMin(inner_rect_rel:GetHeight(), window.FontRefSize * 0.5) + local pad_y = ImMin(inner_rect_rel:GetHeight(), window.FontRefSize * 0.5) -- Terrible approximation for the intent of starting navigation from first fully visible item inner_rect_rel.Min.x = clamp_x and (inner_rect_rel.Min.x + pad_x) or -FLT_MAX inner_rect_rel.Max.x = clamp_x and (inner_rect_rel.Max.x - pad_x) or FLT_MAX inner_rect_rel.Min.y = clamp_y and (inner_rect_rel.Min.y + pad_y) or -FLT_MAX @@ -14409,6 +16805,8 @@ function ImGui.NavUpdateCreateMoveRequest() end end + -- 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) local scoring_rect = ImRect() if window ~= nil then local nav_rect_rel = ImRect() @@ -14418,6 +16816,7 @@ function ImGui.NavUpdateCreateMoveRequest() scoring_rect = ImGui.WindowRectRelToAbs(window, nav_rect_rel) if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsPageMove) ~= 0 then + -- When we start from a visible location, score visible items and prioritize this result. if window.InnerRect:Contains(scoring_rect) then g.NavMoveFlags = bit32.bor(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) end @@ -14426,12 +16825,16 @@ function ImGui.NavUpdateCreateMoveRequest() g.NavScoringNoClipRect:Add(scoring_rect) end + -- ImGui.GetForegroundDrawList():AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)) -- [DEBUG] Pre-bias if g.NavMoveSubmitted then ImGui.NavBiasScoringRect(scoring_rect, window.RootWindowForNav.NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags) end - IM_ASSERT(not scoring_rect:IsInverted()) + IM_ASSERT(not scoring_rect:IsInverted()) -- Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem(). + -- ImGui.GetForegroundDrawList():AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)) -- [DEBUG] Post-bias + -- if not g.NavScoringNoClipRect:IsInverted() then ImGui.GetForegroundDrawList():AddRectFilled(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(100, 255, 0, 80)) end -- [DEBUG] end ImRect_Copy(g.NavScoringRect, scoring_rect) + -- g.NavScoringNoClipRect:Add(scoring_rect) end function ImGui.NavUpdateCreateTabbingRequest() @@ -14447,6 +16850,9 @@ function ImGui.NavUpdateCreateTabbingRequest() return end + -- Initiate tabbing request + -- (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags.NavEnableKeyboard flag!) + -- See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping. local nav_keyboard_active = bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 if nav_keyboard_active then g.NavTabbingDir = g.IO.KeyShift and -1 or ((g.NavCursorVisible == false and g.ActiveId == 0) and 0 or 1) @@ -14456,7 +16862,7 @@ function ImGui.NavUpdateCreateTabbingRequest() local move_flags = bit32.bor(ImGuiNavMoveFlags.IsTabbing, ImGuiNavMoveFlags.Activate) local scroll_flags = window.Appearing and bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.AlwaysCenterY) or bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleEdgeY) local clip_dir = (g.NavTabbingDir < 0) and ImGuiDir.Up or ImGuiDir.Down - ImGui.NavMoveRequestSubmit(ImGuiDir.None, clip_dir, move_flags, scroll_flags) + ImGui.NavMoveRequestSubmit(ImGuiDir.None, clip_dir, move_flags, scroll_flags) -- FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable. g.NavTabbingCounter = -1 end @@ -14465,7 +16871,10 @@ function ImGui.NavUpdate() local io = g.IO io.WantSetMousePos = false + -- if g.NavScoringDebugCount > 0 then IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest) end + -- Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard) + -- FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource? local nav_gamepad_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0 if nav_gamepad_active and g.NavInputSource ~= ImGuiInputSource.Gamepad then for _, key in ipairs(nav_gamepad_keys_to_change_source) do @@ -14484,6 +16893,7 @@ function ImGui.NavUpdate() end end + -- Process navigation init request (select first/default focus) g.NavJustMovedToId = 0 g.NavJustMovedToFocusScopeId = 0 g.NavJustMovedFromFocusScopeId = 0 @@ -14494,6 +16904,7 @@ function ImGui.NavUpdate() g.NavInitRequestFromMove = false g.NavInitResult.ID = 0 + -- Process navigation move request if g.NavMoveSubmitted then ImGui.NavMoveRequestApplyResult() end @@ -14507,6 +16918,7 @@ function ImGui.NavUpdate() end end + -- Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling) local set_mouse_pos = false if g.NavMousePosDirty and g.NavIdIsAlive then if g.NavCursorVisible and g.NavHighlightItemUnderNav and g.NavWindow then @@ -14516,6 +16928,7 @@ function ImGui.NavUpdate() g.NavMousePosDirty = false IM_ASSERT(g.NavLayer == ImGuiNavLayer.Main or g.NavLayer == ImGuiNavLayer.Menu) + -- Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0 if g.NavWindow then ImGui.NavSaveLastChildNavWindowIntoParent(g.NavWindow) end @@ -14523,14 +16936,18 @@ function ImGui.NavUpdate() g.NavWindow.NavLastChildNavWindow = nil end + -- Update Ctrl+Tab and Windowing features (hold Square to move/resize/etc.) ImGui.NavUpdateWindowing() + -- Set output flags for user application io.NavActive = (nav_keyboard_active or nav_gamepad_active) and g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 io.NavVisible = (io.NavActive and g.NavId ~= 0 and g.NavCursorVisible) or (g.NavWindowingTarget ~= nil) + -- Process NavCancel input (to close a popup, get back to parent, clear focus) ImGui.NavUpdateCancelRequest() ImGui.NavUpdateContextMenuRequest() + -- Process manual activation request g.NavActivateId = 0 g.NavActivateDownId = 0 g.NavActivatePressedId = 0 @@ -14541,7 +16958,7 @@ function ImGui.NavUpdate() local activate_pressed = activate_down and ((nav_keyboard_active and ImGui.IsKeyPressedEx(ImGuiKey.Space, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner)) or (nav_gamepad_active and ImGui.IsKeyPressedEx(ImGuiKey.NavGamepadActivate, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner))) local input_pressed_keyboard = nav_keyboard_active and (ImGui.IsKeyPressedEx(ImGuiKey.Enter, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) or ImGui.IsKeyPressedEx(ImGuiKey.KeypadEnter, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner)) local input_pressed_gamepad = false - if activate_down and nav_gamepad_active and ImGui.IsKeyDown(ImGuiKey.NavGamepadActivate, ImGuiKeyOwner_NoOwner) and bit32.band(g.NavIdItemFlags, ImGuiItemFlags.Inputable) ~= 0 then + if activate_down and nav_gamepad_active and ImGui.IsKeyDown(ImGuiKey.NavGamepadActivate, ImGuiKeyOwner_NoOwner) and bit32.band(g.NavIdItemFlags, ImGuiItemFlags.Inputable) ~= 0 then -- requires ImGuiItemFlags.Inputable to avoid retriggering regular buttons. if ImGui.GetKeyData(g, ImGuiKey.NavGamepadActivate).DownDurationPrev < NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY and ImGui.GetKeyData(g, ImGuiKey.NavGamepadActivate).DownDuration >= NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY then input_pressed_gamepad = true end @@ -14555,7 +16972,7 @@ function ImGui.NavUpdate() g.NavActivateId = g.NavId g.NavActivateFlags = ImGuiActivateFlags.PreferInput end - if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_down or input_pressed_keyboard or input_pressed_gamepad) then + if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_down or input_pressed_keyboard or input_pressed_gamepad) then -- FIXME-NAV: Unsure why input_pressed_xxx (migrated from input_down which was already dubious) g.NavActivateDownId = g.NavId end if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_pressed or input_pressed_keyboard or input_pressed_gamepad) then @@ -14572,6 +16989,7 @@ function ImGui.NavUpdate() IM_ASSERT(g.NavActivateDownId == g.NavActivateId) end + -- Highlight if g.NavHighlightActivatedTimer > 0.0 then g.NavHighlightActivatedTimer = ImMax(0.0, g.NavHighlightActivatedTimer - io.DeltaTime) end @@ -14579,6 +16997,8 @@ function ImGui.NavUpdate() g.NavHighlightActivatedId = 0 end + -- Process programmatic activation request + -- FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others) if g.NavNextActivateId ~= 0 then g.NavActivateId = g.NavNextActivateId g.NavActivateDownId = g.NavNextActivateId @@ -14587,6 +17007,7 @@ function ImGui.NavUpdate() end g.NavNextActivateId = 0 + -- Process move requests ImGui.NavUpdateCreateMoveRequest() if g.NavMoveDir == ImGuiDir.None then ImGui.NavUpdateCreateTabbingRequest() @@ -14594,9 +17015,11 @@ function ImGui.NavUpdate() ImGui.NavUpdateAnyRequestFlag() g.NavIdIsAlive = false + -- Scrolling if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 and not g.NavWindowingTarget then + -- *Fallback* manual-scroll with Nav directional keys when window has no navigable item local window = g.NavWindow - local scroll_speed = IM_ROUND(window.FontRefSize * 100 * io.DeltaTime) + local scroll_speed = IM_ROUND(window.FontRefSize * 100 * io.DeltaTime) -- We need round the scrolling speed because sub-pixel scroll isn't reliably supported. local move_dir = g.NavMoveDir if window.DC.NavLayersActiveMask == 0x00 and window.DC.NavWindowHasScrollY and move_dir ~= ImGuiDir.None then if move_dir == ImGuiDir.Left or move_dir == ImGuiDir.Right then @@ -14609,6 +17032,8 @@ function ImGui.NavUpdate() end end + -- *Normal* Manual scroll with LStick + -- Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. if nav_gamepad_active then local scroll_dir = ImGui.GetKeyMagnitude2d(ImGuiKey.GamepadLStickLeft, ImGuiKey.GamepadLStickRight, ImGuiKey.GamepadLStickUp, ImGuiKey.GamepadLStickDown) local tweak_factor = 1.0 @@ -14626,21 +17051,29 @@ function ImGui.NavUpdate() end end + -- Always prioritize mouse highlight if navigation is disabled if not nav_keyboard_active and not nav_gamepad_active then g.NavCursorVisible = false g.NavHighlightItemUnderNav = false set_mouse_pos = false end + -- Update mouse position if requested + -- (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied) if set_mouse_pos and io.ConfigNavMoveSetMousePos and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasSetMousePos) ~= 0 then ImGui.TeleportMousePos(ImGui.NavCalcPreferredRefPos(ImGuiWindowFlags.Popup)) end + -- [DEBUG] g.NavScoringDebugCount = 0 end end +-- Process Escape/NavCancel input (to close a popup, get back to parent, clear focus) +-- FIXME: In order to support e.g. Escape to clear a selection we'll need: +-- - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it. +-- - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept function ImGui.NavUpdateCancelRequest() local g = GImGui local nav_gamepad_active = bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0 @@ -14653,9 +17086,11 @@ function ImGui.NavUpdateCancelRequest() if g.ActiveId ~= 0 then ImGui.ClearActiveID() elseif g.NavLayer ~= ImGuiNavLayer.Main then + -- Leave the "menu" layer ImGui.NavRestoreLayer(ImGuiNavLayer.Main) ImGui.SetNavCursorVisibleAfterMove() elseif g.NavWindow and g.NavWindow ~= g.NavWindow.RootWindow and bit32.band(g.NavWindow.RootWindowForNav.Flags, ImGuiWindowFlags.Popup) == 0 and g.NavWindow.RootWindowForNav.ParentWindow then + -- Exit child window local child_window = g.NavWindow.RootWindowForNav local parent_window = child_window.ParentWindow IM_ASSERT(child_window.ChildId ~= 0) @@ -14663,13 +17098,18 @@ function ImGui.NavUpdateCancelRequest() ImGui.SetNavID(child_window.ChildId, ImGuiNavLayer.Main, 0, ImGui.WindowRectAbsToRel(parent_window, child_window:Rect())) ImGui.SetNavCursorVisibleAfterMove() elseif g.OpenPopupStack.Size > 0 and g.OpenPopupStack:back().Window ~= nil and bit32.band(g.OpenPopupStack:back().Window.Flags, ImGuiWindowFlags.Modal) == 0 then + -- Close open popup/menu ImGui.ClosePopupToLevel(g.OpenPopupStack.Size - 1, true) else + -- Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were + -- FIXME-NAV: This should happen on window appearing. if g.IO.ConfigNavEscapeClearFocusItem or g.IO.ConfigNavEscapeClearFocusWindow then - if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.Popup) ~= 0 then + if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.Popup) ~= 0 then -- or not (g.NavWindow.Flags & ImGuiWindowFlags.ChildWindow) g.NavWindow.NavLastIds[0] = 0 end end + + -- Clear nav focus if g.IO.ConfigNavEscapeClearFocusItem or g.IO.ConfigNavEscapeClearFocusWindow then g.NavId = 0 end @@ -14701,6 +17141,7 @@ local function NavScoreItemDistInterval(cand_min, cand_max, curr_min, curr_max) return 0.0 end +-- Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057 --- @param result ImGuiNavItemData --- @param nav_bb ImRect --- @return bool @@ -14711,70 +17152,93 @@ function ImGui.NavScoreItem(result, nav_bb) return false end + -- FIXME: Those are not good variables names local cand = ImRect() - ImRect_Copy(cand, nav_bb) - local curr = g.NavScoringRect + ImRect_Copy(cand, nav_bb) -- Current item nav rectangle + local 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 = g.NavScoringDebugCount + 1 + -- When entering through a NavFlattened border, we consider child window items as fully clipped for scoring if window.ParentWindow == g.NavWindow then IM_ASSERT(bit32.band(bit32.bor(window.ChildFlags, g.NavWindow.ChildFlags), ImGuiChildFlags.NavFlattened) ~= 0) if not window.ClipRect:Overlaps(cand) then return false end - cand:ClipWithFull(window.ClipRect) + cand:ClipWithFull(window.ClipRect) -- This allows the scored item to not overlap other candidates in the parent window end + -- Compute distance between boxes + -- FIXME-NAV: Introducing biases for vertical navigation, needs to be removed. local dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x) - local dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2), ImLerp(cand.Min.y, cand.Max.y, 0.8), ImLerp(curr.Min.y, curr.Max.y, 0.2), ImLerp(curr.Min.y, curr.Max.y, 0.8)) + local dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2), ImLerp(cand.Min.y, cand.Max.y, 0.8), ImLerp(curr.Min.y, curr.Max.y, 0.2), ImLerp(curr.Min.y, curr.Max.y, 0.8)) -- Scale down on Y to keep using box-distance for vertically touching items if dby ~= 0.0 and dbx ~= 0.0 then dbx = (dbx / 1000.0) + ((dbx > 0.0) and 1.0 or -1.0) end local dist_box = ImFabs(dbx) + ImFabs(dby) + -- Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) local dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x) local dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y) - local dist_center = ImFabs(dcx) + ImFabs(dcy) + local dist_center = ImFabs(dcx) + ImFabs(dcy) -- L1 metric (need this for our connectedness guarantee) + -- Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance local quadrant local dax = 0.0 local day = 0.0 local dist_axial = 0.0 if dbx ~= 0.0 or dby ~= 0.0 then + -- For non-overlapping boxes, use distance between boxes + -- FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y + -- One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir.Right, pressing Left to navigate from Close to Collapse tends to fail. + -- Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty. dax = dbx day = dby dist_axial = dist_box quadrant = ImGetDirQuadrantFromDelta(dbx, dby) elseif dcx ~= 0.0 or dcy ~= 0.0 then + -- For overlapping boxes with different centers, use distance between centers dax = dcx day = dcy dist_axial = dist_center quadrant = ImGetDirQuadrantFromDelta(dcx, dcy) else + -- Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter) quadrant = (g.LastItemData.ID < g.NavId) and ImGuiDir.Left or ImGuiDir.Right end local move_dir = g.NavMoveDir + -- Is it in the quadrant we're interested in moving to? local new_best = false if quadrant == move_dir then + -- Does it beat the current best candidate? if dist_box < result.DistBox then result.DistBox = dist_box result.DistCenter = dist_center return true end if dist_box == result.DistBox then + -- Try using distance between center points to break ties if dist_center < result.DistCenter then result.DistCenter = dist_center new_best = true elseif dist_center == result.DistCenter then - if (((move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and dby) or dbx) < 0.0 then + -- Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items + -- (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index), + -- this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis. + if (((move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and dby) or dbx) < 0.0 then -- moving bj to the right/down decreases distance new_best = true end end end end - if result.DistBox == FLT_MAX and dist_axial < result.DistAxial then + -- Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches + -- are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness) + -- This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too. + -- 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward. + -- Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option? + if result.DistBox == FLT_MAX and dist_axial < result.DistAxial then -- Check axial match if g.NavLayer == ImGuiNavLayer.Menu and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.ChildMenu) == 0 then if (move_dir == ImGuiDir.Left and dax < 0.0) or (move_dir == ImGuiDir.Right and dax > 0.0) or (move_dir == ImGuiDir.Up and day < 0.0) or (move_dir == ImGuiDir.Down and day > 0.0) then result.DistAxial = dist_axial @@ -14797,18 +17261,25 @@ function ImGui.NavApplyItemToResult(result) ImRect_Copy(result.RectRel, ImGui.WindowRectAbsToRel(window, g.LastItemData.NavRect)) if bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 then IM_ASSERT(g.NextItemData.SelectionUserData ~= ImGuiSelectionUserData_Invalid) - result.SelectionUserData = g.NextItemData.SelectionUserData + result.SelectionUserData = g.NextItemData.SelectionUserData -- INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData. end end --- @param result ImGuiNavItemData function ImGui.NavMoveRequestResolveWithLastItem(result) local g = GImGui - g.NavMoveScoringItems = false + g.NavMoveScoringItems = false -- Ensure request doesn't need more processing ImGui.NavApplyItemToResult(result) ImGui.NavUpdateAnyRequestFlag() end +-- Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest(). +-- Note that SetKeyboardFocusHere() API calls are considered tabbing requests! +-- - Case 1: no nav/active id: set result to first eligible item, stop storing. +-- - Case 2: tab forward: on ref id set counter, on counter elapse store result +-- - Case 3: tab forward wrap: set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. -- FIXME-TABBING: Could be done as a next-frame forwarded request +-- - Case 4: tab backward: store all results, on ref id pick prev, stop storing +-- - Case 5: tab backward wrap: store all results, on ref id if no result keep storing until last -- FIXME-TABBING: Could be done as next-frame forwarded requested --- @param id ImGuiID --- @param item_flags ImGuiItemFlags --- @param move_flags ImGuiNavMoveFlags @@ -14824,6 +17295,9 @@ function ImGui.NavProcessItemForTabbingRequest(id, item_flags, move_flags) end end + -- - Can always land on an item when using API call. + -- - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item. + -- - Tabbing without _NavEnableKeyboard: goes through inputable items only. local can_stop if bit32.band(move_flags, ImGuiNavMoveFlags.FocusApi) ~= 0 then can_stop = true @@ -14831,8 +17305,10 @@ function ImGui.NavProcessItemForTabbingRequest(id, item_flags, move_flags) can_stop = bit32.band(item_flags, ImGuiItemFlags.NoTabStop) == 0 and (bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 or bit32.band(item_flags, ImGuiItemFlags.Inputable) ~= 0) end + -- Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows) local result = g.NavMoveResultLocal if g.NavTabbingDir == 1 then + -- Tab Forward or SetKeyboardFocusHere() with >= 0 if can_stop and g.NavTabbingResultFirst.ID == 0 then ImGui.NavApplyItemToResult(g.NavTabbingResultFirst) end @@ -14845,30 +17321,35 @@ function ImGui.NavProcessItemForTabbingRequest(id, item_flags, move_flags) g.NavTabbingCounter = 1 end elseif g.NavTabbingDir == -1 then + -- Tab Backward if g.NavId == id then if result.ID ~= 0 then g.NavMoveScoringItems = false ImGui.NavUpdateAnyRequestFlag() end elseif can_stop then + -- Keep applying until reaching NavId ImGui.NavApplyItemToResult(result) end elseif g.NavTabbingDir == 0 then if can_stop and g.NavId == id then ImGui.NavMoveRequestResolveWithLastItem(result) end - if can_stop and g.NavTabbingResultFirst.ID == 0 then + if can_stop and g.NavTabbingResultFirst.ID == 0 then -- Tab init ImGui.NavApplyItemToResult(g.NavTabbingResultFirst) end end end +-- We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above) +-- This is called after LastItemData is set, but NextItemData is also still valid. function ImGui.NavProcessItem() local g = GImGui local window = g.CurrentWindow local id = g.LastItemData.ID local item_flags = g.LastItemData.ItemFlags + -- When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816, #7994) local nav_bb = ImRect() ImRect_Copy(nav_bb, g.LastItemData.NavRect) if window.DC.NavIsScrollPushableX == false then @@ -14876,17 +17357,21 @@ function ImGui.NavProcessItem() nav_bb.Max.x = ImClamp(nav_bb.Max.x, window.ClipRect.Min.x, window.ClipRect.Max.x) end + -- Process Init Request if g.NavInitRequest and g.NavLayer == window.DC.NavLayerCurrent and bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then + -- Even if 'ImGuiItemFlags.NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback local candidate_for_nav_default_focus = bit32.band(item_flags, ImGuiItemFlags.NoNavDefaultFocus) == 0 if candidate_for_nav_default_focus or g.NavInitResult.ID == 0 then ImGui.NavApplyItemToResult(g.NavInitResult) end if candidate_for_nav_default_focus then - g.NavInitRequest = false + g.NavInitRequest = false -- Found a match, clear request ImGui.NavUpdateAnyRequestFlag() end end + -- Process Move Request (scoring for navigation) + -- FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy) if g.NavMoveScoringItems and bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.FocusApi) ~= 0 or bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) == 0 then local is_tabbing = bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 @@ -14898,9 +17383,10 @@ function ImGui.NavProcessItem() ImGui.NavApplyItemToResult(result) end + -- Features like PageUp/PageDown need to maintain a separate score for the visible set of items. local VISIBLE_RATIO = 0.70 if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) ~= 0 then - local r = window.InnerRect + local r = window.InnerRect -- window.ClipRect if r:Overlaps(nav_bb) then if ImClamp(nav_bb.Max.y, r.Min.y, r.Max.y) - ImClamp(nav_bb.Min.y, r.Min.y, r.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO then if ImGui.NavScoreItem(g.NavMoveResultLocalVisible, nav_bb) then @@ -14913,24 +17399,26 @@ function ImGui.NavProcessItem() end end + -- Update information for currently focused/navigated item if g.NavId == id then if g.NavWindow ~= window then - ImGui.SetNavWindow(window) + ImGui.SetNavWindow(window) -- Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window. end g.NavLayer = window.DC.NavLayerCurrent - ImGui.SetNavFocusScope(g.CurrentFocusScopeId) + ImGui.SetNavFocusScope(g.CurrentFocusScopeId) -- Will set g.NavFocusScopeId AND store g.NavFocusScopePath g.NavFocusScopeId = g.CurrentFocusScopeId g.NavIdIsAlive = true g.NavIdItemFlags = item_flags if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 then IM_ASSERT(g.NextItemData.SelectionUserData ~= ImGuiSelectionUserData_Invalid) - g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData + g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData -- INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData. end - window.NavRectRel[window.DC.NavLayerCurrent] = ImGui.WindowRectAbsToRel(window, nav_bb) + window.NavRectRel[window.DC.NavLayerCurrent] = ImGui.WindowRectAbsToRel(window, nav_bb) -- Store item bounding box (relative to window position) end end function ImGui.NavInitRequestApplyResult() + -- In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void) local g = GImGui if not g.NavWindow then return @@ -14946,8 +17434,11 @@ function ImGui.NavInitRequestApplyResult() g.NavJustMovedToHasSelectionData = bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 end + -- Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) + -- FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently. + -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) ImGui.SetNavID(result.ID, g.NavLayer, result.FocusScopeId, result.RectRel) - g.NavIdIsAlive = true + g.NavIdIsAlive = true -- Mark as alive from previous frame as we got a result if result.SelectionUserData ~= ImGuiSelectionUserData_Invalid then g.NavLastValidSelectionUserData = result.SelectionUserData end @@ -14956,9 +17447,11 @@ function ImGui.NavInitRequestApplyResult() end end +-- Apply result from previous frame navigation directional move request. Always called from NavUpdate() function ImGui.NavMoveRequestApplyResult() local g = GImGui + -- Select which result to use local result if g.NavMoveResultLocal.ID ~= 0 then result = g.NavMoveResultLocal @@ -14968,12 +17461,14 @@ function ImGui.NavMoveRequestApplyResult() result = nil end + -- Tabbing forward wrap if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 and result == nil then if (g.NavTabbingCounter == 1 or g.NavTabbingDir == 0) and g.NavTabbingResultFirst.ID ~= 0 then result = g.NavTabbingResultFirst end end + -- In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result) local axis = (g.NavMoveDir == ImGuiDir.Up or g.NavMoveDir == ImGuiDir.Down) and ImGuiAxis.Y or ImGuiAxis.X if result == nil then if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 then @@ -14982,15 +17477,18 @@ function ImGui.NavMoveRequestApplyResult() if g.NavId ~= 0 and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSetNavCursorVisible) == 0 then ImGui.SetNavCursorVisibleAfterMove() end - ImGui.NavClearPreferredPosForAxis(axis) + ImGui.NavClearPreferredPosForAxis(axis) -- On a failed move, clear preferred pos for this axis. + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n") return end + -- PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page. if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) ~= 0 and g.NavMoveResultLocalVisible.ID ~= 0 and g.NavMoveResultLocalVisible.ID ~= g.NavId then result = g.NavMoveResultLocalVisible end + -- Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules. if result ~= g.NavMoveResultOther and g.NavMoveResultOther.ID ~= 0 and g.NavMoveResultOther.Window.ParentWindow == g.NavWindow then if g.NavMoveResultOther.DistBox < result.DistBox or (g.NavMoveResultOther.DistBox == result.DistBox and g.NavMoveResultOther.DistCenter < result.DistCenter) then @@ -14999,24 +17497,33 @@ function ImGui.NavMoveRequestApplyResult() end IM_ASSERT(g.NavWindow and result.Window) + -- Scroll to keep newly navigated item fully into view. if g.NavLayer == ImGuiNavLayer.Main then local rect_abs = ImGui.WindowRectRelToAbs(result.Window, result.RectRel) ImGui.ScrollToRectEx(result.Window, rect_abs, g.NavMoveScrollFlags) + if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.ScrollToEdgeY) ~= 0 then + -- FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge? local scroll_target = (g.NavMoveDir == ImGuiDir.Up) and result.Window.ScrollMax.y or 0.0 ImGui.SetScrollY(result.Window, scroll_target) end end if g.NavWindow ~= result.Window then + -- IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name) g.NavWindow = result.Window g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid end + -- Clear active id unless requested not to + -- FIXME: ImGuiNavMoveFlags.NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction, + -- so this is mostly provided as a gateway for further experiments (see #1418, #2890) if g.ActiveId ~= result.ID and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoClearActiveId) == 0 then ImGui.ClearActiveID() end + -- Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags.AllowCurrentNavId) + -- PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior. if (g.NavId ~= result.ID or bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsPageMove) ~= 0) and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSelect) == 0 then g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId @@ -15025,8 +17532,11 @@ function ImGui.NavMoveRequestApplyResult() g.NavJustMovedToKeyMods = g.NavMoveKeyMods g.NavJustMovedToIsTabbing = bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 g.NavJustMovedToHasSelectionData = bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 + -- IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId) end + -- Apply new NavID/Focus + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) local root_for_nav = g.NavWindow.RootWindowForNav local preferred_scoring_pos_rel = ImVec2() ImVec2_Copy(preferred_scoring_pos_rel, root_for_nav.NavPreferredScoringPosRel[g.NavLayer]) @@ -15035,16 +17545,20 @@ function ImGui.NavMoveRequestApplyResult() g.NavLastValidSelectionUserData = result.SelectionUserData end + -- Restore last preferred position for current axis + -- (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..) if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) == 0 then preferred_scoring_pos_rel[axis] = result.RectRel:GetCenter()[axis] ImVec2_Copy(root_for_nav.NavPreferredScoringPosRel[g.NavLayer], preferred_scoring_pos_rel) end + -- Tabbing: Activates Inputable, otherwise only Focus if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 and bit32.band(result.ItemFlags, ImGuiItemFlags.Inputable) == 0 then g.NavMoveFlags = bit32.band(g.NavMoveFlags, bit32.bnot(ImGuiNavMoveFlags.Activate)) end + -- Activate if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Activate) ~= 0 then g.NavNextActivateId = result.ID g.NavNextActivateFlags = ImGuiActivateFlags.None @@ -15056,26 +17570,30 @@ function ImGui.NavMoveRequestApplyResult() end end + -- Make nav cursor visible if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSetNavCursorVisible) == 0 then ImGui.SetNavCursorVisibleAfterMove() end end +-- True when current work location may be scrolled horizontally when moving left / right. +-- This is generally always true UNLESS within a column. We don't have a vertical equivalent. function ImGui.NavUpdateCurrentWindowIsScrollPushableX() local g = GImGui local window = g.CurrentWindow window.DC.NavIsScrollPushableX = (g.CurrentTable == nil and window.DC.CurrentColumns == nil) end +-- Called by TreePop() to implement ImGuiTreeNodeFlags.NavLeftJumpsToParent --- @param result ImGuiNavItemData --- @param tree_node_data ImGuiTreeNodeStackData function ImGui.NavMoveRequestResolveWithPastTreeNode(result, tree_node_data) local g = GImGui g.NavMoveScoringItems = false g.LastItemData.ID = tree_node_data.ID - g.LastItemData.ItemFlags = bit32.band(tree_node_data.ItemFlags, bit32.bnot(ImGuiItemFlags.HasSelectionUserData)) + g.LastItemData.ItemFlags = bit32.band(tree_node_data.ItemFlags, bit32.bnot(ImGuiItemFlags.HasSelectionUserData)) -- Losing SelectionUserData, recovered next-frame (cheaper). ImRect_Copy(g.LastItemData.NavRect, tree_node_data.NavRect) - ImGui.NavApplyItemToResult(result) + ImGui.NavApplyItemToResult(result) -- Result this instead of implementing a NavApplyPastTreeNodeToResult() ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y) ImGui.NavUpdateAnyRequestFlag() end @@ -15087,6 +17605,7 @@ function ImGui.NavMoveRequestCancel() ImGui.NavUpdateAnyRequestFlag() end +-- Forward will reuse the move request again on the next frame (generally with modifications done to it) --- @param move_dir ImGuiDir --- @param clip_dir ImGuiDir --- @param move_flags ImGuiNavMoveFlags @@ -15102,29 +17621,33 @@ function ImGui.NavMoveRequestForward(move_dir, clip_dir, move_flags, scroll_flag g.NavMoveScrollFlags = scroll_flags end +-- Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire +-- popup is assembled and in case of appended popups it is not clear which EndPopup() call is final. --- @param window ImGuiWindow --- @param wrap_flags ImGuiNavMoveFlags function ImGui.NavMoveRequestTryWrapping(window, wrap_flags) local g = GImGui - IM_ASSERT(bit32.band(wrap_flags, ImGuiNavMoveFlags.WrapMask_) ~= 0 and bit32.band(wrap_flags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)) == 0) + IM_ASSERT(bit32.band(wrap_flags, ImGuiNavMoveFlags.WrapMask_) ~= 0 and bit32.band(wrap_flags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)) == 0) -- Call with _WrapX, _WrapY, _LoopX, _LoopY + -- In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it: + -- as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest(). if g.NavWindow == window and g.NavMoveScoringItems and g.NavLayer == window.DC.NavLayerCurrent then g.NavMoveFlags = bit32.bor(bit32.band(g.NavMoveFlags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)), wrap_flags) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] DRAG AND DROP ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.IsDragDropPayloadBeingAccepted() local g = GImGui return g.DragDropActive and g.DragDropAcceptIdPrev ~= 0 end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] LOCALIZATION ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- @param entries ImGuiLocEntry[] --- @param count int @@ -15135,9 +17658,32 @@ function ImGui.LocalizeRegisterEntries(entries, count) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] VIEWPORTS, PLATFORM WINDOWS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - GetMainViewport() +-- - FindViewportByID() +-- - SetCurrentViewport() [Internal] +-- - SetWindowViewport() [Internal] +-- - GetWindowAlwaysWantOwnViewport() [Internal] +-- - UpdateTryMergeWindowIntoHostViewport() [Internal] +-- - UpdateTryMergeWindowIntoHostViewports() [Internal] +-- - TranslateWindowsInViewport() [Internal] +-- - ScaleWindowsInViewport() [Internal] +-- - FindHoveredViewportFromPlatformWindowStack() [Internal] +-- - UpdateViewportsNewFrame() [Internal] +-- - UpdateViewportsEndFrame() [Internal] +-- - AddUpdateViewport() [Internal] +-- - WindowSelectViewport() [Internal] +-- - WindowSyncOwnedViewport() [Internal] +-- - UpdatePlatformWindows() +-- - RenderPlatformWindowsDefault() +-- - FindPlatformMonitorForPos() [Internal] +-- - FindPlatformMonitorForRect() [Internal] +-- - UpdateViewportPlatformMonitor() [Internal] +-- - DestroyPlatformWindow() [Internal] +-- - DestroyPlatformWindows() +------------------------------------------------------------------------------- function MT.ImGuiViewport:GetDebugName() local viewport = self @@ -15173,6 +17719,7 @@ function ImGui.GetMainViewport() return g.Viewports[1] end +-- FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236) --- @param viewport_id ImGuiID --- @return ImGuiViewport? function ImGui.FindViewportByID(viewport_id) @@ -15245,8 +17792,8 @@ function ImGui.GetWindowAlwaysWantOwnViewport(window) return false end ---- Heuristic, see #8948: depends on how backends handle OS-level parenting. ---- Due to how parent viewport stack is layed out, note that IsViewportAbove(a,b) isn't always the same as !IsViewportAbove(b,a). +-- Heuristic, see #8948: depends on how backends handle OS-level parenting. +-- Due to how parent viewport stack is layed out, note that IsViewportAbove(a,b) isn't always the same as !IsViewportAbove(b,a). --- @param potential_above ImGuiViewportP --- @param potential_below ImGuiViewportP --- @return bool @@ -15340,8 +17887,8 @@ function ImGui.UpdateTryMergeWindowIntoHostViewports(window) return ImGui.UpdateTryMergeWindowIntoHostViewport(window, g.Viewports.Data[1]) end ---- Translate Dear ImGui windows when a Host Viewport has been moved ---- (This additionally keeps windows at the same place when ImGuiConfigFlags.ViewportsEnable is toggled!) +-- Translate Dear ImGui windows when a Host Viewport has been moved +-- (This additionally keeps windows at the same place when ImGuiConfigFlags.ViewportsEnable is toggled!) --- @param viewport ImGuiViewportP --- @param old_pos ImVec2 --- @param new_pos ImVec2 @@ -15368,7 +17915,7 @@ function ImGui.TranslateWindowsInViewport(viewport, old_pos, new_pos, old_size, end end --- If the backend doesn't support ImGuiBackendFlags_HasMouseHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs for it, we do a search ourselves. +-- If the backend doesn't support ImGuiBackendFlags.HasMouseHoveredViewport or doesn't honor ImGuiViewportFlags.NoInputs for it, we do a search ourselves. -- A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. -- B) It requires Platform_GetWindowFocus to be implemented by backend. --- @param mouse_platform_pos ImVec2 @@ -15388,6 +17935,8 @@ function ImGui.FindHoveredViewportFromPlatformWindowStack(mouse_platform_pos) return best_candidate end +-- Update viewports and monitor infos +-- Note that this is running even if 'ImGuiConfigFlags.ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info. function ImGui.UpdateViewportsNewFrame() local g = GImGui IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size) @@ -15544,6 +18093,7 @@ function ImGui.UpdateViewportsNewFrame() viewport:UpdateWorkRect() + -- Garbage collect transient buffers of recently BG/FG drawlists for dl_n = 1, 2 do -- IM_COUNTOF(viewport->BgFgDrawLists) if viewport.BgFgDrawListsLastTimeActive[dl_n] < memory_compact_start_time and viewport.BgFgDrawLists[dl_n] ~= nil then IM_DELETE(viewport.BgFgDrawLists, dl_n) @@ -15673,6 +18223,7 @@ function ImGui.UpdateViewportsNewFrame() IM_ASSERT(g.MouseViewport ~= nil) end +-- Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) function ImGui.UpdateViewportsEndFrame() local g = GImGui g.PlatformIO.Viewports:resize(0) @@ -15683,7 +18234,7 @@ function ImGui.UpdateViewportsEndFrame() ImVec2_Copy(viewport.LastPos, ImVec2(viewport.Pos.x, viewport.Pos.y)) ImVec2_Copy(viewport.LastSize, ImVec2(viewport.Size.x, viewport.Size.y)) - if (viewport.LastFrameActive < g.FrameCount or viewport.Size.x <= 0.0 or viewport.Size.y <= 0.0) and (i > 1) then + if (viewport.LastFrameActive < g.FrameCount or viewport.Size.x <= 0.0 or viewport.Size.y <= 0.0) and (i > 1) then -- Always include main viewport in the list break end if viewport.Window and not ImGui.IsWindowActiveAndVisible(viewport.Window) then @@ -15700,6 +18251,7 @@ function ImGui.UpdateViewportsEndFrame() g.Viewports.Data[1]:ClearRequestFlags() -- Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called end +-- FIXME: We should ideally refactor the system to call this every frame (we currently don't) --- @param window? ImGuiWindow --- @param id ImGuiID --- @param pos ImVec2 @@ -15737,8 +18289,7 @@ function ImGui.AddUpdateViewport(window, id, pos, size, flags) if not viewport.PlatformRequestResize or viewport.ID == IMGUI_VIEWPORT_DEFAULT_ID then ImVec2_Copy(viewport.Size, size) end - -- Preserve existing flags - viewport.Flags = bit32.bor(flags, bit32.band(viewport.Flags, bit32.bor(ImGuiViewportFlags.IsMinimized, ImGuiViewportFlags.IsFocused))) + viewport.Flags = bit32.bor(flags, bit32.band(viewport.Flags, bit32.bor(ImGuiViewportFlags.IsMinimized, ImGuiViewportFlags.IsFocused))) -- Preserve existing flags if prev_pos.x ~= viewport.Pos.x or prev_pos.y ~= viewport.Pos.y or prev_size.x ~= viewport.Size.x or prev_size.y ~= viewport.Size.y then ImGui.UpdateViewportPlatformMonitor(viewport) end @@ -15811,6 +18362,7 @@ function ImGui.DestroyViewport(viewport) -- IM_DELETE(viewport) end +-- FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. --- @param window ImGuiWindow function ImGui.WindowSelectViewport(window) local g = GImGui @@ -15989,7 +18541,7 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) -- Not correct to set modal as topmost because: -- - Because other popups can be stacked above a modal (e.g. combo box in a modal) - -- - ImGuiViewportFlags.TopMost is currently handled different in backends + -- - ImGuiViewportFlags.TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost" -- if bit32.band(window_flags, ImGuiWindowFlags.Modal) ~= 0 then -- viewport_flags = bit32.bor(viewport_flags, ImGuiViewportFlags.TopMost) -- end @@ -16040,6 +18592,8 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) end end +-- Called by user at the end of the main loop, after EndFrame() +-- This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api. function ImGui.UpdatePlatformWindows() local g = GImGui IM_ASSERT(g.FrameCountEnded == g.FrameCount, "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?") @@ -16201,6 +18755,9 @@ function ImGui.FindPlatformMonitorForPos(pos) return -1 end +-- Search for the monitor with the largest intersection area with the given rectangle +-- We generally try to avoid searching loops but the monitor count should be very small here +-- FIXME-OPT: We could test the last monitor used for that viewport first, and early --- @param rect ImRect --- @return int function ImGui.FindPlatformMonitorForRect(rect) @@ -16242,11 +18799,13 @@ function ImGui.FindPlatformMonitorForRect(rect) return best_monitor_n end +-- Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor) --- @param viewport ImGuiViewportP function ImGui.UpdateViewportPlatformMonitor(viewport) viewport.PlatformMonitor = ImGui.FindPlatformMonitorForRect(viewport:GetMainRect()) end +-- Return value is always ~= nil, but don't hold on it across frames. --- @param viewport_p ImGuiViewport --- @return ImGuiPlatformMonitor function ImGui.GetViewportPlatformMonitor(viewport_p) @@ -16288,15 +18847,24 @@ function ImGui.DestroyPlatformWindow(viewport) end function ImGui.DestroyPlatformWindows() + -- We call the destroy window on every viewport (including the main viewport, index 1) to give a chance to the backend + -- to clear any data they may have stored in e.g. PlatformUserData, RendererUserData. + -- It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling + -- code to operator a consistent manner. + -- It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without + -- crashing if it doesn't have data stored. local g = GImGui for _, viewport in g.Viewports:iter() do ImGui.DestroyPlatformWindow(viewport) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] METRICS/DEBUGGER WINDOW ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DebugRenderViewportThumbnail() [Internal] +-- - RenderViewportsThumbnails() [Internal] +------------------------------------------------------------------------------- --- @param draw_list ImDrawList --- @param viewport ImGuiViewport @@ -16322,7 +18890,7 @@ function ImGui.DebugRenderViewportThumbnail(draw_list, viewport, bb) local thumb_r = thumb_window:Rect() local title_r = thumb_window:TitleBarRect() thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off + thumb_r.Max * scale)) - title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r:GetHeight() * 3.0) * scale)) + title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r:GetHeight() * 3.0) * scale)) -- Exaggerate title bar height thumb_r:ClipWithFull(bb) title_r:ClipWithFull(bb) local window_is_focused = g.NavWindow and thumb_window.RootWindowForTitleBarHighlight == g.NavWindow.RootWindowForTitleBarHighlight @@ -16344,6 +18912,7 @@ function ImGui.RenderViewportsThumbnails() local g = GImGui local window = g.CurrentWindow + -- Draw monitor and calculate their boundaries local SCALE = 1.0 / 8.0 local bb_full = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX) for _, monitor in g.PlatformIO.Monitors:iter() do @@ -16358,6 +18927,7 @@ function ImGui.RenderViewportsThumbnails() window.DrawList:AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui.GetColorU32(ImGuiCol.Border, 0.10), 4.0) end + -- Draw viewports for _, viewport in g.Viewports:iter() do local viewport_draw_bb = ImRect(off + viewport.Pos * SCALE, off + (viewport.Pos + viewport.Size) * SCALE) ImGui.DebugRenderViewportThumbnail(window.DrawList, viewport, viewport_draw_bb) @@ -16374,6 +18944,19 @@ function ImGui.GetStyleColorVec4(idx) return GImGui.Style.Colors[idx] end +-- 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. +-- +-- 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. function ImGui.ErrorCheckUsingSetCursorPosToExtendParentBoundaries() local g = GImGui local window = g.CurrentWindow @@ -16386,9 +18969,9 @@ function ImGui.ErrorCheckUsingSetCursorPosToExtendParentBoundaries() window.DC.CursorMaxPos = ImMax(window.DC.CursorMaxPos, window.DC.CursorPos) end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] POPUPS: modals, context popups, dimming ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- local function GetWindowDisplayLayer(window) return (bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0) and 1 or 0 @@ -16426,6 +19009,7 @@ function ImGui.FindBottomMostVisibleWindowWithinBeginStack(parent_window) return bottom_most_visible_window end +-- See Demo->Stacked Modal to confirm what this is for. function ImGui.GetTopMostAndVisiblePopupModal() local g = GImGui for n = g.OpenPopupStack.Size, 1, -1 do @@ -16442,18 +19026,22 @@ function ImGui.RenderDimmedBackgroundBehindWindow(window, col) local viewport = window.Viewport local viewport_rect = viewport:GetMainRect() -- Draw behind window by moving the draw command at the FRONT of the draw list + -- Draw list have been trimmed already, hence the explicit recreation of a draw command if missing. + -- FIXME: This is a little bit complicated, solely to avoid creating/injecting an extra drawlist in drawdata. local draw_list = (window.RootWindowDockTree or window.RootWindow).DrawList draw_list:ChannelsMerge() if draw_list.CmdBuffer.Size == 0 then draw_list:AddDrawCmd() end - draw_list:PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false) + draw_list:PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false) -- FIXME: Need to strictly ensure ImDrawCmd are not merged draw_list:AddRectFilled(viewport_rect.Min, viewport_rect.Max, col) local cmd = draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size] draw_list.CmdBuffer:pop_back() draw_list.CmdBuffer:push_front(cmd) - draw_list:AddDrawCmd() + draw_list:AddDrawCmd() -- We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command. draw_list:PopClipRect() end +-- Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList:ChannelsMerge() before usage. +-- We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds(). function ImGui.RenderDimmedBackgrounds() local g = GImGui local modal_window = ImGui.GetTopMostAndVisiblePopupModal() @@ -16463,24 +19051,27 @@ function ImGui.RenderDimmedBackgrounds() if not dim_bg_for_modal and not dim_bg_for_window_list then return end if dim_bg_for_modal then + -- Draw dimming behind modal or a begin stack child, whichever comes first in draw order. local dim_behind_window = ImGui.FindBottomMostVisibleWindowWithinBeginStack(modal_window) ImGui.RenderDimmedBackgroundBehindWindow(dim_behind_window, ImGui.GetColorU32(modal_window.DC.ModalDimBgColor, g.DimBgRatio, true)) elseif dim_bg_for_window_list then + -- Draw dimming behind Ctrl+Tab target window and behind Ctrl+Tab UI window ImGui.RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, ImGui.GetColorU32(ImGuiCol.NavWindowingDimBg, g.DimBgRatio)) if g.NavWindowingListWindow ~= nil and g.NavWindowingListWindow.Active and g.NavWindowingListWindow.Viewport and g.NavWindowingListWindow.Viewport ~= g.NavWindowingTargetAnim.Viewport then ImGui.RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, ImGui.GetColorU32(ImGuiCol.NavWindowingDimBg, g.DimBgRatio)) end + -- Draw border around Ctrl+Tab target window local window = g.NavWindowingTargetAnim local viewport = window.Viewport local distance = g.FontSize local bb = window:Rect() bb:Expand(distance) - if bb:GetWidth() >= viewport.Size.x and bb:GetHeight() >= viewport.Size.y then bb:Expand(-distance - 1.0) end + if bb:GetWidth() >= viewport.Size.x and bb:GetHeight() >= viewport.Size.y then bb:Expand(-distance - 1.0) end -- If a window fits the entire viewport, adjust its highlight inward window.DrawList:ChannelsMerge() if window.DrawList.CmdBuffer.Size == 0 then window.DrawList:AddDrawCmd() end window.DrawList:PushClipRect(viewport.Pos, viewport.Pos + viewport.Size) - window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.NavWindowingHighlight, g.NavWindowingHighlightAlpha), window.WindowRounding, 0, 3.0) + window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.NavWindowingHighlight, g.NavWindowingHighlightAlpha), window.WindowRounding, 0, 3.0) -- FIXME-DPI window.DrawList:PopClipRect() end end @@ -16493,11 +19084,15 @@ function ImGui.ClosePopupsExceptModals() if not window or bit32.band(window.Flags, ImGuiWindowFlags.Modal) ~= 0 then break end popup_count_to_keep = popup_count_to_keep - 1 end - if popup_count_to_keep < g.OpenPopupStack.Size then + if popup_count_to_keep < g.OpenPopupStack.Size then -- This test is not required but it allows to set a convenient breakpoint on the statement below ImGui.ClosePopupToLevel(popup_count_to_keep, true) end end +-- If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup. +-- Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup). +-- - p_open is returned set back to false by BeginPopupModal() when popup is not open. +-- - if you set p_open to false before calling BeginPopupModal(), it will close the popup. --- @return bool visible, bool? p_open # p_open is the updated value of the optional close button flag function ImGui.BeginPopupModal(name, p_open, flags) if flags == nil then flags = 0 end @@ -16505,20 +19100,23 @@ function ImGui.BeginPopupModal(name, p_open, flags) local window = g.CurrentWindow local id = window:GetID(name) if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values if p_open then p_open = false end return false, p_open end + -- 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 bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) == 0 then - local viewport = window.WasActive and window.Viewport or ImGui.GetMainViewport() + local viewport = window.WasActive and window.Viewport or ImGui.GetMainViewport() -- FIXME-VIEWPORT: What may be our reference viewport? ImGui.SetNextWindowPos(viewport:GetCenter(), ImGuiCond.FirstUseEver, ImVec2(0.5, 0.5)) end flags = bit32.bor(flags, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Modal, ImGuiWindowFlags.NoCollapse, ImGuiWindowFlags.NoDocking) local is_open p_open, is_open = ImGui.Begin(name, p_open, flags) - if not is_open or (p_open ~= nil and not p_open) then + if not is_open or (p_open ~= nil and not p_open) then -- NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) ImGui.EndPopup() if is_open then ImGui.ClosePopupToLevel(g.BeginPopupStack.Size, true) end return false, p_open @@ -16535,7 +19133,7 @@ function ImGui.IsPopupOpenRequestForWindow(popup_flags) end end if g.NavOpenContextMenuWindowId and g.NavOpenContextMenuWindowId ~= 0 and g.CurrentWindow.ID ~= 0 then - if ImGui.IsWindowChildOf(g.NavWindow, g.CurrentWindow, false, false) then return true end + if ImGui.IsWindowChildOf(g.NavWindow, g.CurrentWindow, false, false) then return true end -- This enable ordering to be used to disambiguate item vs window (#8803) end return false end @@ -16555,7 +19153,7 @@ function ImGui.BeginPopupContextVoid(str_id, popup_flags) local g = GImGui local window = g.CurrentWindow if not str_id then str_id = "void_context" end - local id = window:GetID(str_id) + local id = window:GetID(str_id) -- FIXME: Use a global ID? local mouse_button = ImGui.GetMouseButtonFromPopupFlags(popup_flags) if ImGui.IsMouseReleased(mouse_button, id) and not ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) then if ImGui.GetTopMostPopupModal() == nil then ImGui.OpenPopupEx(id, popup_flags) end @@ -16571,7 +19169,9 @@ function ImGui.BeginTooltipHidden() return ret end +------------------------------------------------------------------------------- -- [SECTION] MISC GETTERS/SETTERS, FOCUS +------------------------------------------------------------------------------- function ImGui.NavMoveRequestResolveWithLastItem(result) local g = GImGui @@ -16580,12 +19180,18 @@ function ImGui.NavMoveRequestResolveWithLastItem(result) ImGui.NavUpdateAnyRequestFlag() end +-- Note: this will likely be called ActivateItem() once we rework our Focus/Activation system! +-- But ActivateItem() should function without altering scroll/focus? function ImGui.SetKeyboardFocusHere(offset) if offset == nil then offset = 0 end local g = GImGui local window = g.CurrentWindow IM_ASSERT(offset >= -1) -- -1 is allowed but not below + -- It makes sense in the vast majority of cases to never interrupt a drag and drop. + -- When we refactor this function into ActivateItem() we may want to make this an option. + -- MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but + -- is also automatically dropped in the event g.ActiveId is stolen. if g.DragDropActive or g.MovingWindow ~= nil then return end @@ -16594,7 +19200,7 @@ function ImGui.SetKeyboardFocusHere(offset) local move_flags = bit32.bor(ImGuiNavMoveFlags.IsTabbing, ImGuiNavMoveFlags.Activate, ImGuiNavMoveFlags.FocusApi, ImGuiNavMoveFlags.NoSetNavCursorVisible) local scroll_flags = window.Appearing and bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.AlwaysCenterY) or bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleEdgeY) - ImGui.NavMoveRequestSubmit(ImGuiDir.None, (offset < 0) and ImGuiDir.Up or ImGuiDir.Down, move_flags, scroll_flags) + ImGui.NavMoveRequestSubmit(ImGuiDir.None, (offset < 0) and ImGuiDir.Up or ImGuiDir.Down, move_flags, scroll_flags) -- FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable. if offset == -1 then ImGui.NavMoveRequestResolveWithLastItem(g.NavMoveResultLocal) else @@ -16603,10 +19209,11 @@ function ImGui.SetKeyboardFocusHere(offset) end end +-- Focus = move navigation cursor, set scrolling, set focus window. function ImGui.FocusItem() local g = GImGui local window = g.CurrentWindow - if g.DragDropActive or g.MovingWindow ~= nil then + if g.DragDropActive or g.MovingWindow ~= nil then -- FIXME: Opt-in flags for this? return end local move_flags = bit32.bor(ImGuiNavMoveFlags.IsTabbing, ImGuiNavMoveFlags.FocusApi, ImGuiNavMoveFlags.NoSetNavCursorVisible, ImGuiNavMoveFlags.NoSelect) @@ -16651,10 +19258,13 @@ function ImGui.GetStyleColorName(idx) return StyleColorNames[idx] or "Unknown" end +------------------------------------------------------------------------------- -- [SECTION] NAV END FRAME +------------------------------------------------------------------------------- local NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15 +-- Window has already passed the IsWindowNavFocusable() local function GetFallbackWindowNameForWindowingList(window) if bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then return "(Popup)" @@ -16663,11 +19273,12 @@ local function GetFallbackWindowNameForWindowingList(window) return "(Main menu bar)" end if window.DockNodeAsHost then - return "(Dock node)" + return "(Dock node)" -- Not normally shown to user. end return "(Untitled)" end +-- Overlay displayed when using Ctrl+Tab. Called by EndFrame(). function ImGui.NavUpdateWindowingOverlay() local g = GImGui IM_ASSERT(g.NavWindowingTarget ~= nil) @@ -16684,7 +19295,7 @@ function ImGui.NavUpdateWindowingOverlay() g.NavWindowingListWindow = g.CurrentWindow for n = g.WindowsFocusOrder.Size, 1, -1 do local window = g.WindowsFocusOrder.Data[n] - IM_ASSERT(window ~= nil) + IM_ASSERT(window ~= nil) -- Fix static analyzers if ImGui.IsWindowNavFocusable(window) then local label = window.Name if ImGui.FindRenderedTextEnd(label) == 1 then @@ -16707,12 +19318,15 @@ local function NavUpdateCreateWrappingRequest() local clip_dir = g.NavMoveDir local move_flags = g.NavMoveFlags + -- local move_axis = (g.NavMoveDir == ImGuiDir.Up or g.NavMoveDir == ImGuiDir.Down) and ImGuiAxis.Y or ImGuiAxis.X + + -- Menu layer does not maintain scrolling / content size (#9178) local wrap_size = (g.NavLayer == ImGuiNavLayer.Menu) and window.Size or (window.ContentSize + window.WindowPadding) if g.NavMoveDir == ImGuiDir.Left and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapX, ImGuiNavMoveFlags.LoopX)) ~= 0 then bb_rel.Min.x = wrap_size.x; bb_rel.Max.x = wrap_size.x if bit32.band(move_flags, ImGuiNavMoveFlags.WrapX) ~= 0 then - bb_rel:TranslateY(-bb_rel:GetHeight()) + bb_rel:TranslateY(-bb_rel:GetHeight()) -- Previous row clip_dir = ImGuiDir.Up end do_forward = true @@ -16720,7 +19334,7 @@ local function NavUpdateCreateWrappingRequest() if g.NavMoveDir == ImGuiDir.Right and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapX, ImGuiNavMoveFlags.LoopX)) ~= 0 then bb_rel.Min.x = -window.WindowPadding.x; bb_rel.Max.x = -window.WindowPadding.x if bit32.band(move_flags, ImGuiNavMoveFlags.WrapX) ~= 0 then - bb_rel:TranslateY(bb_rel:GetHeight()) + bb_rel:TranslateY(bb_rel:GetHeight()) -- Next row clip_dir = ImGuiDir.Down end do_forward = true @@ -16728,7 +19342,7 @@ local function NavUpdateCreateWrappingRequest() if g.NavMoveDir == ImGuiDir.Up and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapY, ImGuiNavMoveFlags.LoopY)) ~= 0 then bb_rel.Min.y = wrap_size.y; bb_rel.Max.y = wrap_size.y if bit32.band(move_flags, ImGuiNavMoveFlags.WrapY) ~= 0 then - bb_rel:TranslateX(-bb_rel:GetWidth()) + bb_rel:TranslateX(-bb_rel:GetWidth()) -- Previous column clip_dir = ImGuiDir.Left end do_forward = true @@ -16736,7 +19350,7 @@ local function NavUpdateCreateWrappingRequest() if g.NavMoveDir == ImGuiDir.Down and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapY, ImGuiNavMoveFlags.LoopY)) ~= 0 then bb_rel.Min.y = -window.WindowPadding.y; bb_rel.Max.y = -window.WindowPadding.y if bit32.band(move_flags, ImGuiNavMoveFlags.WrapY) ~= 0 then - bb_rel:TranslateX(bb_rel:GetWidth()) + bb_rel:TranslateX(bb_rel:GetWidth()) -- Next column clip_dir = ImGuiDir.Right end do_forward = true @@ -16753,21 +19367,28 @@ end function ImGui.NavEndFrame() local g = GImGui + -- Show Ctrl+Tab list window if g.NavWindowingTarget ~= nil then ImGui.NavUpdateWindowingOverlay() end + -- Perform wrap-around in menus + -- FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly. + -- FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame. if g.NavWindow and ImGui.NavMoveRequestButNoResultYet() and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.WrapMask_) ~= 0 and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) == 0 then NavUpdateCreateWrappingRequest() end end +------------------------------------------------------------------------------- -- [SECTION] ImGuiTextFilter +------------------------------------------------------------------------------- --- @class ImGuiTextFilter MT.ImGuiTextFilter = {} MT.ImGuiTextFilter.__index = MT.ImGuiTextFilter +-- Helper: Parse and apply text filters e.g. 'aaa bbb -ccc'. --- @param default_filter? string function ImGuiTextFilter(default_filter) local this = setmetatable({ InputBuf = {}, _CountExclude = 0, _Items = ImVector() }, MT.ImGuiTextFilter) @@ -16785,6 +19406,7 @@ function MT.ImGuiTextFilter:Draw(label, width) return self:DrawWithHint(label, "incl -excl") end +-- Use ImGui.SetNextItemWidth() manually if you want to use this. function MT.ImGuiTextFilter:DrawWithHint(label, hint) if label == nil then label = "Filter" end if hint == nil then hint = "incl -excl" end @@ -16798,6 +19420,7 @@ end function MT.ImGuiTextFilter:Clear() self.InputBuf[1] = 0; self:Build() end function MT.ImGuiTextFilter:IsActive() return self._Items.Size ~= 0 end +-- Parse filter and split into a format optimal for PassFilter() -- Items are { Text = string (lowercased), CountInclude = int } function MT.ImGuiTextFilter:Build() local items = self._Items @@ -16811,6 +19434,7 @@ function MT.ImGuiTextFilter:Build() local word_b = 1 local seq_start_idx = -1 -- 1-based index into items, -1 = none while word_b < buf_e do + -- Trim blanks while word_b < buf_e and ImCharIsBlankA(string.byte(buf, word_b)) do word_b = word_b + 1 end @@ -16819,10 +19443,12 @@ function MT.ImGuiTextFilter:Build() local is_quote = word_b < buf_e and string.byte(buf, word_b) == 34 -- '"' local word_e if is_quote then + -- Parsing quotes. Omit storing leading/trailing quotes. word_b = word_b + 1 word_e = string.find(buf, '"', word_b, true) or buf_e if word_e > buf_e then word_e = buf_e end else + -- Handle both ' ' and ',' separators. word_e = word_b while word_e < buf_e do local c = string.byte(buf, word_e) @@ -16831,7 +19457,9 @@ function MT.ImGuiTextFilter:Build() end end + -- Min length if word_e - word_b > 0 then + -- Add to list. The '-' is not stored in items but implicitly inferred using (n < CountExclude). local item = { Text = string.lower(string.sub(buf, word_b, word_e - 1)), CountInclude = 0 } if is_excl then items:insert(self._CountExclude + 1, item) @@ -16844,6 +19472,7 @@ function MT.ImGuiTextFilter:Build() end end + -- Next sequence if word_e < buf_e and string.byte(buf, word_e) == 44 then -- ',' seq_start_idx = -1 end @@ -16851,6 +19480,7 @@ function MT.ImGuiTextFilter:Build() end end +-- FIXME: Could use a specialized ImStristr() + pre-convert our filter to uppercase. --- @param text string? --- @param text_end? int # exclusive, 1-based function MT.ImGuiTextFilter:PassFilter(text, text_end) @@ -16860,6 +19490,7 @@ function MT.ImGuiTextFilter:PassFilter(text, text_end) if text_end ~= nil then text = string.sub(text, 1, text_end - 1) end text = string.lower(text) + -- Filters are sorted so that '-' ones are always leading. local seq = 1 local seq_excl_end = self._CountExclude + 1 while seq < seq_excl_end do @@ -16867,24 +19498,29 @@ function MT.ImGuiTextFilter:PassFilter(text, text_end) seq = seq + 1 end + -- Process includes local seq_end = items.Size + 1 - if seq == seq_end then return true end + if seq == seq_end then return true end -- When no inclusion are specified (only exclusions) we implicitly pass while seq < seq_end do local seq_incl_end = seq + items.Data[seq].CountInclude while seq < seq_incl_end do if not string.find(text, items.Data[seq].Text, 1, true) then break end seq = seq + 1 end - if seq == seq_incl_end then return true end - seq = seq_incl_end + if seq == seq_incl_end then return true end -- All matched + seq = seq_incl_end -- Try next end return false end +------------------------------------------------------------------------------- -- [SECTION] ImGuiListClipper +------------------------------------------------------------------------------- ImGuiListClipperFlags = ImGuiListClipperFlags or { None = 0, NoSetTableRowCounters = bit32.lshift(1, 0) } +-- FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell. +-- The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous. local function GetSkipItemForListClipping() local g = GImGui if g.CurrentTable then return g.CurrentTable.HostSkipItems end @@ -16899,11 +19535,13 @@ local function ImGuiListClipper_SortAndFuseRanges(ranges, offset) if offset == nil then offset = 0 end if ranges.Size - offset <= 1 then return end local d = ranges.Data + -- Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries) for sort_end = ranges.Size - offset - 1, 1, -1 do for i = offset + 1, sort_end + offset do if d[i].Min > d[i + 1].Min then d[i], d[i + 1] = d[i + 1], d[i] end end end + -- Now fuse ranges together as much as possible. local i = 2 + offset while i <= ranges.Size do IM_ASSERT(not d[i].PosToIndexConvert and not d[i - 1].PosToIndexConvert) @@ -16918,16 +19556,19 @@ local function ImGuiListClipper_SortAndFuseRanges(ranges, offset) end local function ImGuiListClipper_SeekCursorAndSetupPrevLine(clipper, pos_y, line_height) + -- Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. + -- FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. + -- The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek? local g = GImGui local window = g.CurrentWindow local off_y = pos_y - window.DC.CursorPos.y window.DC.CursorPos.y = pos_y window.DC.CursorMaxPos.y = ImMax(window.DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y) - window.DC.CursorPosPrevLine.y = window.DC.CursorPos.y - line_height - window.DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y) + window.DC.CursorPosPrevLine.y = window.DC.CursorPos.y - line_height -- Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. + window.DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y) -- If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. local columns = window.DC.CurrentColumns if columns then - columns.LineMinY = window.DC.CursorPos.y + columns.LineMinY = window.DC.CursorPos.y -- Setting this so that cell Y position are set properly end local tbl = g.CurrentTable if tbl then @@ -16935,7 +19576,7 @@ local function ImGuiListClipper_SeekCursorAndSetupPrevLine(clipper, pos_y, line_ ImGui.TableEndRow(tbl) end local row_increase = math.floor((off_y / line_height) + 0.5) - if row_increase > 0 and bit32.band(clipper.Flags, ImGuiListClipperFlags.NoSetTableRowCounters) == 0 then + if row_increase > 0 and bit32.band(clipper.Flags, ImGuiListClipperFlags.NoSetTableRowCounters) == 0 then -- If your clipper item height is ~= from actual table row height, consider using ImGuiListClipperFlags.NoSetTableRowCounters. See #8886. tbl.CurrentRow = tbl.CurrentRow + row_increase tbl.RowBgColorCounter = tbl.RowBgColorCounter + row_increase end @@ -16971,6 +19612,7 @@ function MT.ImGuiListClipper:Begin(items_count, items_height) self.DisplayStart = -1 self.DisplayEnd = 0 + -- Acquire temporary buffer g.ClipperTempDataStacked = g.ClipperTempDataStacked + 1 while g.ClipperTempDataStacked > g.ClipperTempData.Size do g.ClipperTempData:push_back({ ListClipper = nil, LossynessOffset = 0.0, StepNo = 0, ItemsFrozen = 0, Ranges = ImVector() }) @@ -16985,10 +19627,13 @@ end function MT.ImGuiListClipper:End() local data = self.TempData if data then + -- In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user. local g = self.Ctx if self.ItemsCount >= 0 and self.ItemsCount < INT_MAX and self.DisplayStart >= 0 then self:SeekCursorForItem(self.ItemsCount) end + + -- Restore temporary buffer and fix back pointers which may be invalidated when nesting IM_ASSERT(data.ListClipper == self) data.StepNo = data.Ranges.Size g.ClipperTempDataStacked = g.ClipperTempDataStacked - 1 @@ -16998,7 +19643,7 @@ function MT.ImGuiListClipper:End() end self.TempData = nil end - self.DisplayStart = self.ItemsCount + self.DisplayStart = self.ItemsCount -- Clear this so code which may be reused past last Step() won't trip on a non-empty range. self.DisplayEnd = self.ItemsCount self.ItemsCount = -1 end @@ -17007,14 +19652,18 @@ function MT.ImGuiListClipper:IncludeItemByIndex(item_index) self:IncludeItemsByI function MT.ImGuiListClipper:IncludeItemsByIndex(item_begin, item_end) local data = self.TempData - IM_ASSERT(self.DisplayStart < 0) + IM_ASSERT(self.DisplayStart < 0) -- Only allowed after Begin() and if there has not been a specified range yet. IM_ASSERT(item_begin <= item_end) if item_begin < item_end then data.Ranges:push_back(ClipperRangeFromIndices(item_begin, item_end)) end end +-- This is already called while stepping. +-- The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper:Begin() because you couldn't step item count beforehand. function MT.ImGuiListClipper:SeekCursorForItem(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. local pos_y = self.StartPosY + self.StartSeekOffsetY + item_n * self.ItemsHeight ImGuiListClipper_SeekCursorAndSetupPrevLine(self, pos_y, self.ItemsHeight) end @@ -17030,10 +19679,13 @@ local function ImGuiListClipper_StepInternal(clipper) ImGui.TableEndRow(tbl) end + -- No items if clipper.ItemsCount == 0 or GetSkipItemForListClipping() then return false end + -- While we are in frozen row state, keep displaying items one by one, unclipped + -- FIXME: Could be stored as a table-agnostic state. if data.StepNo == 0 and tbl ~= nil and not tbl.IsUnfrozenRows then clipper.DisplayStart = data.ItemsFrozen clipper.DisplayEnd = ImMin(data.ItemsFrozen + 1, clipper.ItemsCount) @@ -17043,40 +19695,47 @@ local function ImGuiListClipper_StepInternal(clipper) return true end + -- Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height) local calc_clipping = false if data.StepNo == 0 then clipper.StartPosY = window.DC.CursorPos.y if clipper.ItemsHeight <= 0.0 then + -- Submit the first item (or range) so we can measure its height (generally the first range is 0..1) data.Ranges:push_front(ClipperRangeFromIndices(data.ItemsFrozen, data.ItemsFrozen + 1)) clipper.DisplayStart = ImMax(data.Ranges.Data[1].Min, data.ItemsFrozen) clipper.DisplayEnd = ImMin(data.Ranges.Data[1].Max, clipper.ItemsCount) data.StepNo = 1 return true end - calc_clipping = true + calc_clipping = true -- If on the first step with known item height, calculate clipping. end + -- Step 1: Let the clipper infer height from first range if clipper.ItemsHeight <= 0.0 then IM_ASSERT(data.StepNo == 1) -- (no float precision mitigation needed: Luau numbers are doubles) clipper.ItemsHeight = (window.DC.CursorPos.y - clipper.StartPosY) / (clipper.DisplayEnd - clipper.DisplayStart) - if clipper.ItemsHeight == 0.0 and clipper.ItemsCount == INT_MAX then + if clipper.ItemsHeight == 0.0 and clipper.ItemsCount == INT_MAX then -- Accept that no item have been submitted if in indeterminate mode. return false end if clipper.ItemsHeight <= 0.0 then IM_ASSERT_USER_ERROR(clipper.ItemsHeight > 0.0, "ImGuiListClipper: Failed to calculate item height! First item hasn't been submitted by user code, or has not moved the cursor vertically!") return false end - calc_clipping = true + calc_clipping = true -- If item height had to be calculated, calculate clipping afterwards. end + -- Step 0 or 1: Calculate the actual ranges of visible elements. local already_submitted = clipper.DisplayEnd if calc_clipping then + -- Record seek offset, this is so ImGuiListClipper:Seek() can be called after ImGuiListClipperData is done clipper.StartSeekOffsetY = data.LossynessOffset - data.ItemsFrozen * clipper.ItemsHeight if g.LogEnabled then + -- If logging is active, do not perform any clipping data.Ranges:push_back(ClipperRangeFromIndices(0, clipper.ItemsCount)) else + -- Add range selected to be included for navigation local is_nav_request = (g.NavMoveScoringItems and g.NavWindow and g.NavWindow.RootWindowForNav == window.RootWindowForNav) and true or false local nav_off_min = (is_nav_request and g.NavMoveClipDir == ImGuiDir.Up) and -1 or 0 local nav_off_max = (is_nav_request and g.NavMoveClipDir == ImGuiDir.Down) and 1 or 0 @@ -17090,6 +19749,7 @@ local function ImGuiListClipper_StepInternal(clipper) data.Ranges:push_back(ClipperRangeFromIndices(clipper.ItemsCount - 1, clipper.ItemsCount)) end + -- Add focused/active item local nav_rect_abs = ImGui.WindowRectRelToAbs(window, window.NavRectRel[0]) if g.NavId ~= 0 and window.NavLastIds[0] == g.NavId then data.Ranges:push_back(ClipperRangeFromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0)) @@ -17098,19 +19758,31 @@ local function ImGuiListClipper_StepInternal(clipper) local min_y = window.ClipRect.Min.y local max_y = window.ClipRect.Max.y + -- Add box selection range local bs = g.BoxSelectState if bs and bs.IsActive and bs.Window == window then + -- FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos. + -- RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that. + -- As a workaround we currently half ItemSpacing worth on each side. local pad_y = g.Style.ItemSpacing.y min_y = min_y - pad_y max_y = max_y + pad_y + + -- Box-select on 2D area requires different clipping. + -- (best adding pad_y here than in BeginBoxSelect() as we are closer to current state) if bs.UnclipMode then data.Ranges:push_back(ClipperRangeFromPositions(bs.UnclipRect.Min.y - pad_y, bs.UnclipRect.Max.y + pad_y, 0, 0)) end end + -- Add main visible range data.Ranges:push_back(ClipperRangeFromPositions(min_y, max_y, nav_off_min, nav_off_max)) end + -- Convert position ranges to item index ranges + -- - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping. + -- - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list, + -- which with the flooring/ceiling tend to lead to 2 items instead of one being submitted. for _, range in data.Ranges:iter() do if range.PosToIndexConvert then local m1 = ImTrunc((range.Min - window.DC.CursorPos.y - data.LossynessOffset) / clipper.ItemsHeight) @@ -17123,6 +19795,7 @@ local function ImGuiListClipper_StepInternal(clipper) ImGuiListClipper_SortAndFuseRanges(data.Ranges, data.StepNo) end + -- Step 0+ (if item height is given in advance) or 1+: Display the next range in line. while data.StepNo < data.Ranges.Size do local r = data.Ranges.Data[data.StepNo + 1] clipper.DisplayStart = ImMax(r.Min, already_submitted) @@ -17136,6 +19809,8 @@ local function ImGuiListClipper_StepInternal(clipper) end end + -- After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), + -- Advance the cursor to the end of the list and then returns 'false' to end the loop. if clipper.ItemsCount < INT_MAX then clipper:SeekCursorForItem(clipper.ItemsCount) end @@ -17153,13 +19828,22 @@ function MT.ImGuiListClipper:Step() return ret end +-- Generic helper, equivalent to old ImGui.CalcListClipping() but stateless +-- Returns (out_visible_start, out_visible_end) function ImGui.CalcClipRectVisibleItemsY(clip_rect, pos, items_height) local out_visible_start = ImMax(ImTrunc((clip_rect.Min.y - pos.y) / items_height), 0) local out_visible_end = ImMax(ImTrunc(ImCeil((clip_rect.Max.y - pos.y) / items_height)), out_visible_start) return out_visible_start, out_visible_end end +------------------------------------------------------------------------------- -- [SECTION] ERROR CHECKING, STATE RECOVERY +------------------------------------------------------------------------------- +-- - ErrorRecoveryStoreState() +-- - ErrorRecoveryTryToRecoverState() +-- - ErrorRecoveryTryToRecoverWindowState() +-- - ErrorLog() +------------------------------------------------------------------------------- function ImGuiErrorRecoveryState() return { SizeOfWindowStack = 0, SizeOfIDStack = 0, SizeOfTreeStack = 0, SizeOfColorStack = 0, SizeOfStyleVarStack = 0, @@ -17167,6 +19851,7 @@ function ImGuiErrorRecoveryState() SizeOfBeginPopupStack = 0, SizeOfDisabledStack = 0 } end +-- Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery. function ImGui.ErrorRecoveryStoreState(state_out) local g = GImGui state_out.SizeOfWindowStack = g.CurrentWindowStack.Size @@ -17182,9 +19867,17 @@ function ImGui.ErrorRecoveryStoreState(state_out) state_out.SizeOfDisabledStack = g.DisabledStackSize end +-- Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery. +-- Called by e.g. EndFrame() but may be called for manual recovery. +-- Attempt to recover full window stack. function ImGui.ErrorRecoveryTryToRecoverState(state_in) local g = GImGui while g.CurrentWindowStack.Size > state_in.SizeOfWindowStack do + -- Recap: + -- - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped. + -- - Always call a matching End() for each Begin() call, regardless of its return value! + -- - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS. + -- - We will fix that in a future major update. local window = g.CurrentWindow if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then if g.CurrentTable ~= nil and g.CurrentTable.InnerWindow == g.CurrentWindow then @@ -17204,6 +19897,8 @@ function ImGui.ErrorRecoveryTryToRecoverState(state_in) end end +-- Called by e.g. End() but may be called for manual recovery. +-- Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls. function ImGui.ErrorRecoveryTryToRecoverWindowState(state_in) local g = GImGui @@ -17270,6 +19965,7 @@ function ImGui.ErrorRecoveryTryToRecoverWindowState(state_in) IM_ASSERT_USER_ERROR(false, "Missing PopFocusScope()") ImGui.PopFocusScope() end + -- IM_ASSERT(g.FocusScopeStack.Size == state_in.SizeOfFocusScopeStack) end -- Lines are stored in g.DebugLogBuf (one chunk per call) @@ -17295,6 +19991,7 @@ end function ImGui.ErrorLog(msg) local g = GImGui if g == nil then return true end + -- Output to debug log local window = g.CurrentWindow if g.IO.ConfigErrorRecoveryEnableDebugLog then @@ -17306,6 +20003,7 @@ function ImGui.ErrorLog(msg) end g.ErrorFirst = false + -- Output to tooltip if g.IO.ConfigErrorRecoveryEnableTooltip then if g.WithinFrameScope and ImGui.BeginErrorTooltip() then if g.ErrorCountCurrentFrame < 20 then @@ -17317,18 +20015,23 @@ function ImGui.ErrorLog(msg) if g.ErrorCountCurrentFrame == 20 then ImGui.Text("(and more errors)") end + -- EndFrame() will amend debug buttons to this window, after all errors have been submitted. ImGui.EndErrorTooltip() end g.ErrorCountCurrentFrame = g.ErrorCountCurrentFrame + 1 end + -- Output to callback if g.ErrorCallback ~= nil then g.ErrorCallback(g, g.ErrorCallbackUserData, msg) end + -- Return whether we should assert return g.IO.ConfigErrorRecoveryEnableAssert end +-- Display an error tooltip when same ID as HoveredId was submitted multiple times. +-- See code in ItemHoverable() for an explanation of why we associate this error to HoveredId + code drawing of rectangles over individual items instances. function ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() local g = GImGui if g.DebugDrawIdConflictsId ~= 0 and g.IO.KeyCtrl == false then @@ -17338,6 +20041,7 @@ function ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() ImGui.Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount) ImGui.BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!") ImGui.BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!") + -- ImGui.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. ImGui.BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.") ImGui.Separator() ImGui.Text("(Hold Ctrl to: ") @@ -17348,19 +20052,24 @@ function ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() ImGui.EndErrorTooltip() end - if g.ErrorCountCurrentFrame > 0 and ImGui.BeginErrorTooltip() then + if g.ErrorCountCurrentFrame > 0 and ImGui.BeginErrorTooltip() then -- Amend at end of frame ImGui.Separator() ImGui.Text("(Hold Ctrl to: ") ImGui.SameLine(0.0, 0.0) if ImGui.SmallButton("Enable Asserts") then g.IO.ConfigErrorRecoveryEnableAssert = true end + -- ImGui.SameLine() + -- if ImGui.SmallButton("Hide Error Tooltips") then + -- g.IO.ConfigErrorRecoveryEnableTooltip = false -- Too dangerous + -- end ImGui.SameLine(0, 0) ImGui.Text(")") ImGui.EndErrorTooltip() end end +-- Pseudo-tooltip. Follow mouse until Ctrl is held. When Ctrl is held we lock position, allowing to click it. function ImGui.BeginErrorTooltip() local g = GImGui local window = ImGui.FindWindowByName("##Tooltip_Error") @@ -17390,9 +20099,9 @@ end do --[[ [SECTION] METRICS/DEBUGGER WINDOW, DEBUG LOG, ID STACK TOOL, FONT DEBUG ]] ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Font atlas / font debugging ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- byte buffers for InputText (same as the demo's DemoBuf/DemoBufStr; kept here so the library doesn't need the demo) local function DemoBuf(str, size) @@ -17409,6 +20118,7 @@ local function DemoBufStr(buf) return ImGui._ByteArrayToString(buf, 1, n + 1) end +-- Avoid naming collision with imgui_demo's HelpMarker() for unity builds. local function MetricsHelpMarker(desc) ImGui.TextDisabled("(?)") if ImGui.BeginItemTooltip() then @@ -17422,6 +20132,8 @@ ImGui.MetricsHelpMarker = MetricsHelpMarker local function U8(c) return (c and c > 0) and utf8.char(c) or "" end +-- Demo helper function to select among loaded fonts. +-- Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one. function ImGui.ShowFontSelector(label) local io = ImGui.GetIO() local font_current = ImGui.GetFont() @@ -17470,9 +20182,12 @@ function ImGui.DebugNodeFontGlyphsForSrcMask(font, baked, src_mask) end end if count > 0 and ImGui.TreeNode(base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, (count > 1) and "glyphs" or "glyph") then + -- Draw a 16x16 grid of glyphs local base_pos = ImGui.GetCursorScreenPos() for n = 0, 255 do local c = base + 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. local cell_p1 = ImVec2(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + math.floor(n / 16) * (cell_size + cell_spacing)) local cell_p2 = ImVec2(cell_p1.x + cell_size, cell_p1.y + cell_size) local glyph = baked:IsGlyphLoaded(c) and baked:FindGlyphNoFallback(c) or nil @@ -17492,11 +20207,14 @@ function ImGui.DebugNodeFontGlyphsForSrcMask(font, baked, src_mask) end end +-- [DEBUG] Display details for a single font, called by ShowStyleEditor(). function ImGui.DebugNodeFont(font) local g = ImGui.GetCurrentContext() local cfg = g.DebugMetricsConfig local atlas = font.OwnerAtlas local opened = ImGui.TreeNode(tostring(font), "Font: \"%s\": %d sources(s)", font:GetDebugName(), font.Sources.Size) + + -- Display preview text if not opened then ImGui.Indent() end ImGui.Indent() if cfg.ShowFontPreview then @@ -17519,6 +20237,7 @@ function ImGui.DebugNodeFont(font) ImGui.SameLine() if ImGui.SmallButton("Clear unused") then ImFontAtlasFontDiscardBakes(atlas, font, 2) end + -- Display details ImGui.Text("Fallback character: '%s' (U+%04X)", U8(font.FallbackChar), font.FallbackChar or 0) ImGui.Text("Ellipsis character: '%s' (U+%04X)", U8(font.EllipsisChar), font.EllipsisChar or 0) for src_n, src in font.Sources:iter() do @@ -17526,10 +20245,15 @@ function ImGui.DebugNodeFont(font) src_n - 1, src.Name or "", src.FontNo or 0, src.OversampleH or 0, src.OversampleV or 0, src.PixelSnapH and 1 or 0, src.GlyphOffset.x, src.GlyphOffset.y) then local loader = src.FontLoader or atlas.FontLoader ImGui.Text("Loader: '%s'", (loader and loader.Name) or "N/A") + + -- if ImGui.DragFloat("ExtraSizeScale", src.ExtraSizeScale, 0.01, 0.10, 2.0) then + -- ImFontAtlasFontRebuildOutput(atlas, font) + -- end ImGui.TreePop() end end + -- Display all glyphs of the fonts in separate pages of 256 characters local builder = atlas.Builder if builder then for _, baked in builder.BakedPool:iter() do @@ -17593,6 +20317,7 @@ function ImGui.DebugNodeTexture(tex, int_id, highlight_rect) ImGui.PopID() end +-- [DEBUG] List fonts in a font atlas and display its texture function ImGui.ShowFontAtlas(atlas) local g = ImGui.GetCurrentContext() local io = g.IO @@ -17603,7 +20328,7 @@ function ImGui.ShowFontAtlas(atlas) ImGui.ShowFontSelector("Font") local changed style.FontSizeBase, changed = ImGui.DragFloat("FontSizeBase", style.FontSizeBase, 0.20, 5.0, 100.0, "%.0f") - if changed then style._NextFrameFontSizeBase = style.FontSizeBase end + if changed then style._NextFrameFontSizeBase = style.FontSizeBase end -- FIXME: Temporary hack until we finish remaining work. ImGui.SameLine(0.0, 0.0); ImGui.Text(" (out %.2f)", ImGui.GetFontSize()) ImGui.SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later.") style.FontScaleMain = ImGui.DragFloat("FontScaleMain", style.FontScaleMain, 0.02, 0.5, 4.0) @@ -17617,6 +20342,7 @@ function ImGui.ShowFontAtlas(atlas) ImGui.SeparatorText("Font List") local cfg = g.DebugMetricsConfig _, cfg.ShowFontPreview = ImGui.Checkbox("Show font preview", cfg.ShowFontPreview == true) + -- Font loaders if ImGui.TreeNode("Loader", "Loader: '%s'", atlas.FontLoaderName or "NULL") then ImGui.BeginDisabled() ImGui.RadioButtonEx("stb_truetype", true) @@ -17626,6 +20352,7 @@ function ImGui.ShowFontAtlas(atlas) ImGui.EndDisabled() ImGui.TreePop() end + -- Font list for i, font in atlas.Fonts:iter() do ImGui.PushID(i) ImGui.DebugNodeFont(font) @@ -17650,16 +20377,19 @@ function ImGui.ShowFontAtlas(atlas) ImGui.Text("Packed rects: %d, area: about %d px ~%dx%d px", b.RectsPackedCount or 0, b.RectsPackedSurface or 0, packed_sqrt, packed_sqrt) ImGui.Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", b.RectsDiscardedCount or 0, b.RectsDiscardedSurface or 0, discarded_sqrt, discarded_sqrt) end + -- Texture list + -- (ensure the last texture always use the same ID, so we can keep it open neatly) for tex_n, tex in atlas.TexList:iter() do if tex_n == atlas.TexList.Size then ImGui.SetNextItemOpen(true, ImGuiCond.Once) end ImGui.DebugNodeTexture(tex, atlas.TexList.Size - tex_n, nil) end end ----------------------------------------------------------------- --- [SECTION] Debug Log window ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] DEBUG LOG WINDOW +------------------------------------------------------------------------------- +-- FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout. local function SameLineOrWrap(size) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow @@ -17670,7 +20400,7 @@ end local function ShowDebugLogFlag(name, flags) local g = ImGui.GetCurrentContext() local size = ImVec2(ImGui.GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui.CalcTextSize(name).x, ImGui.GetFrameHeight()) - SameLineOrWrap(size) + SameLineOrWrap(size) -- FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout. local pressed pressed, g.DebugLogFlags = ImGui.CheckboxFlags(name, g.DebugLogFlags, flags) if pressed and g.IO.KeyShift and bit32.band(g.DebugLogFlags, flags) ~= 0 then @@ -17735,9 +20465,9 @@ function ImGui.ShowDebugLogWindow(p_open) return p_open end ----------------------------------------------------------------- --- [SECTION] ID Stack Tool ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL) +------------------------------------------------------------------------------- local function PathQuery(g) local q = g.DebugItemPathQuery @@ -17750,7 +20480,9 @@ local function PathQuery(g) end -- 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 local function DebugItemPathQuery_UpdateAndGetHookId(query, id) + -- Update query. Clear hook when no active query if query.MainID ~= id then query.MainID = id query.Step = -1 @@ -17760,9 +20492,11 @@ local function DebugItemPathQuery_UpdateAndGetHookId(query, id) query.Active = false if id == 0 then return 0 end local res = query.Results + -- Advance to next stack level when we got our result, or after 2 frames (in case we never get a result) if query.Step >= 0 and query.Step < #res then if res[query.Step + 1].QuerySuccess or res[query.Step + 1].QueryFrameCount > 2 then query.Step = query.Step + 1 end end + -- Update status and hook query.Complete = (query.Step == #res) if query.Step == -1 then query.Active = true @@ -17775,6 +20509,7 @@ local function DebugItemPathQuery_UpdateAndGetHookId(query, id) return 0 end +-- [DEBUG] ID Stack Tool: update query. Called by NewFrame() function ImGui.UpdateDebugToolItemPathQuery() local g = ImGui.GetCurrentContext() local q = PathQuery(g) @@ -17785,12 +20520,16 @@ function ImGui.UpdateDebugToolItemPathQuery() g.DebugHookIdInfoId = DebugItemPathQuery_UpdateAndGetHookId(q, id) end --- Hooks called by GetID() family functions. `data_id` is the string/number that was hashed. +-- [DEBUG] ID Stack tool: hooks called by GetID() family functions +-- `data_id` is the string/number that was hashed. function ImGui.DebugHookIdInfo(id, data_type, data_id) local g = ImGui.GetCurrentContext() local query = PathQuery(g) if not query.Active then return end local window = g.CurrentWindow + + -- Step -1: stack query + -- This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget. if query.Step == -1 then query.Step = 0 query.Results = {} @@ -17799,13 +20538,14 @@ function ImGui.DebugHookIdInfo(id, data_type, data_id) end return end + -- Step 0+: query for individual level if query.Step ~= window.IDStack.Size then return end local info = query.Results[query.Step + 1] if info == nil or info.ID ~= id then return end if info.Desc == nil then if data_type == ImGuiDataType.S32 then info.Desc = string.format("%d", data_id) elseif data_type == ImGuiDataType.String then info.Desc = tostring(data_id) - else info.Desc = string.format("0x%08X [override]", id) end + else info.Desc = string.format("0x%08X [override]", id) end -- PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one. end info.QuerySuccess = true if info.DataType == -1 then info.DataType = data_type end @@ -17820,9 +20560,9 @@ end local function FormatLevelInfo(g, query, n, format_for_ui) local info = query.Results[n + 1] local window = (info.Desc == nil and n == 0) and ImGui.FindWindowByID(info.ID) or nil - if window then return string.format(format_for_ui and "\"%s\" [window]" or "%s", SkipUncontributingPrefix(window.Name)) end - if info.QuerySuccess then return string.format((format_for_ui and info.DataType == ImGuiDataType.String) and "\"%s\"" or "%s", SkipUncontributingPrefix(info.Desc)) end - if query.Step < #query.Results then return "" end + if window then return string.format(format_for_ui and "\"%s\" [window]" or "%s", SkipUncontributingPrefix(window.Name)) end -- Source: window name (because the root ID don't call GetID() and so doesn't get hooked) + if info.QuerySuccess then return string.format((format_for_ui and info.DataType == ImGuiDataType.String) and "\"%s\"" or "%s", SkipUncontributingPrefix(info.Desc)) end -- Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id) + if query.Step < #query.Results then return "" end -- Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. return "???" end @@ -17840,6 +20580,7 @@ local function GetResultAsPath(g, query, hex_encode_non_ascii_chars) return table.concat(out) end +-- ID Stack Tool: Display UI function ImGui.ShowIDStackToolWindow(p_open) local g = ImGui.GetCurrentContext() if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 then @@ -17858,6 +20599,8 @@ function ImGui.ShowIDStackToolWindow(p_open) ImGui.Text("0x%08X", query.MainID) ImGui.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 local time_since_copy = g.Time - tool.CopyToClipboardLastTime ImGui.PushStyleVarY(ImGuiStyleVar.FramePadding, 0.0) _, tool.OptHexEncodeNonAsciiChars = ImGui.Checkbox("Hex-encode non-ASCII", tool.OptHexEncodeNonAsciiChars) @@ -17872,6 +20615,8 @@ function ImGui.ShowIDStackToolWindow(p_open) end ImGui.Text("- Path \"%s\"", query.Complete and result_path or "") ImGui.Separator() + + -- Display decorated stack if #query.Results > 0 and ImGui.BeginTable("##table", 3, ImGuiTableFlags.Borders) then local id_width = ImGui.CalcTextSize("0xDDDDDDDD").x ImGui.TableSetupColumn("Seed", ImGuiTableColumnFlags.WidthFixed, id_width) @@ -17894,14 +20639,30 @@ function ImGui.ShowIDStackToolWindow(p_open) return p_open end ----------------------------------------------------------------- --- [SECTION] Metrics/Debugger window ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] METRICS/DEBUGGER WINDOW +------------------------------------------------------------------------------- +-- - DebugTextEncoding() +-- - ShowMetricsWindow() +-- - DebugNodeColumns() [Internal] +-- - DebugNodeDockNode() [Internal] +-- - DebugNodeDrawList() [Internal] +-- - DebugNodeStorage() [Internal] +-- - DebugNodeTabBar() [Internal] +-- - DebugNodeTable() [Internal] +-- - DebugNodeTableSettings() [Internal] +-- - DebugNodeViewport() [Internal] +-- - DebugNodeWindow() [Internal] +-- - DebugNodeWindowSettings() [Internal] +-- - DebugNodeWindowsList() [Internal] +-- - DebugNodeWindowsListByBeginStackParent() [Internal] +------------------------------------------------------------------------------- local function B(v) return v and 1 or 0 end local function FG(window) return ImGui.GetForegroundDrawList(window and window.Viewport or ImGui.GetMainViewport()) end local function YellowRect(window, min, max) FG(window):AddRect(min, max, IM_COL32(255, 255, 0, 255)) end +-- [DEBUG] Display contents of Columns function ImGui.DebugNodeColumns(columns) if not ImGui.TreeNode(columns.ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns.ID, columns.Count, columns.Flags) then return end ImGui.BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns.OffMaxX - columns.OffMinX, columns.OffMinX, columns.OffMaxX) @@ -17911,6 +20672,7 @@ function ImGui.DebugNodeColumns(columns) ImGui.TreePop() end +-- [DEBUG] Display contents of ImGuiStorage function ImGui.DebugNodeStorage(storage, label) local n = 0 for _ in pairs(storage) do n = n + 1 end @@ -17921,6 +20683,8 @@ function ImGui.DebugNodeStorage(storage, label) ImGui.TreePop() end +-- [DEBUG] Display contents of ImDrawList +-- Note that both 'window' and 'viewport' may be nil here. Viewport is generally nil of destroyed popups which previously owned a viewport. function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) local g = ImGui.GetCurrentContext() local cfg = g.DebugMetricsConfig @@ -17931,11 +20695,11 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) local node_open = ImGui.TreeNode(tostring(draw_list), "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list._OwnerName or "", draw_list.VtxBuffer.Size, draw_list.IdxBuffer.Size, cmd_count) if draw_list == ImGui.GetWindowDrawList() then ImGui.SameLine() - ImGui.TextColored(ImVec4(1.0, 0.4, 0.4, 1.0), "CURRENTLY APPENDING") + ImGui.TextColored(ImVec4(1.0, 0.4, 0.4, 1.0), "CURRENTLY APPENDING") -- Can't display stats for active draw list! (we don't have the data double-buffered) if node_open then ImGui.TreePop() end return end - local fg_draw_list = viewport and ImGui.GetForegroundDrawList(viewport) or nil + local fg_draw_list = viewport and ImGui.GetForegroundDrawList(viewport) or nil -- Render additional visuals into the top-most draw list if window and ImGui.IsItemHovered() and fg_draw_list then fg_draw_list:AddRect(window.Pos, window.Pos + window.Size, IM_COL32(255, 255, 0, 255)) end @@ -17963,11 +20727,11 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) tri[n + 1] = ImVec2(ImDrawVtx_Pos(vtx, vi)) vtxs_rect:Add(tri[n + 1]) end - if show_mesh then fg_draw_list:AddPolyline(tri, 3, IM_COL32(255, 255, 0, 255), 1.0, ImDrawFlags.Closed) end + if show_mesh then fg_draw_list:AddPolyline(tri, 3, IM_COL32(255, 255, 0, 255), 1.0, ImDrawFlags.Closed) end -- In yellow: mesh triangles end if show_aabb then - fg_draw_list:AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)) - fg_draw_list:AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)) + fg_draw_list:AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)) -- In pink: clipping rectangle submitted to GPU + fg_draw_list:AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)) -- In cyan: bounding box of triangles end end if ImGui.IsItemHovered() and (cfg.ShowDrawCmdMesh or cfg.ShowDrawCmdBoundingBoxes) then ShowMesh(cfg.ShowDrawCmdMesh, cfg.ShowDrawCmdBoundingBoxes) end @@ -17981,7 +20745,9 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) ImGui.TreePop() end +-- [DEBUG] Display contents of ImGuiTabBar function ImGui.DebugNodeTabBar(tab_bar, label) + -- Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. local g = ImGui.GetCurrentContext() local is_active = (tab_bar.PrevFrameVisible >= ImGui.GetFrameCount() - 2) local names = {} @@ -18040,7 +20806,7 @@ end function ImGui.DebugNodeTable(tbl) local g = ImGui.GetCurrentContext() - local is_active = (tbl.LastFrameActive >= g.FrameCount - 2) + local is_active = (tbl.LastFrameActive >= g.FrameCount - 2) -- Note that fully clipped early out scrolling tables will appear as inactive here. if not is_active then ImGui.PushStyleColor(ImGuiCol.Text, g.Style.Colors[ImGuiCol.TextDisabled]) end local open = ImGui.TreeNode(tostring(tbl), "Table 0x%08X (%d columns, in '%s')%s", tbl.ID, tbl.ColumnsCount, tbl.OuterWindow and tbl.OuterWindow.Name or "?", is_active and "" or " *Inactive*") if not is_active then ImGui.PopStyleColor() end @@ -18081,7 +20847,7 @@ function ImGui.DebugNodeTable(tbl) end local settings = ImGui.TableGetBoundSettings(tbl) if settings then ImGui.DebugNodeTableSettings(settings, tbl) end - if clear_settings then tbl.IsResetAllRequest = true end + if clear_settings then tbl.IsResetAllRequest = true end -- Queue a call to TableResetSettings() ImGui.TreePop() end @@ -18101,10 +20867,11 @@ local function DebugNodeDockNodeFlags(flags, label, enabled) return flags end +-- [DEBUG] Display contents of ImDockNode function ImGui.DebugNodeDockNode(node, label) local g = ImGui.GetCurrentContext() - local is_alive = (g.FrameCount - node.LastFrameAlive < 2) - local is_active = (g.FrameCount - node.LastFrameActive < 2) + local is_alive = (g.FrameCount - node.LastFrameAlive < 2) -- Submitted with ImGuiDockNodeFlags.KeepAliveOnly + local is_active = (g.FrameCount - node.LastFrameActive < 2) -- Submitted if not is_alive then ImGui.PushStyleColor(ImGuiCol.Text, g.Style.Colors[ImGuiCol.TextDisabled]) end local tree_node_flags = node.IsFocused and ImGuiTreeNodeFlags.Selected or ImGuiTreeNodeFlags.None local open @@ -18211,7 +20978,7 @@ end function ImGui.DebugNodeWindowsList(windows, label) if not ImGui.TreeNode(label, "%s (%d)", label, windows.Size) then return end - for i = windows.Size, 1, -1 do + for i = windows.Size, 1, -1 do -- Iterate front to back ImGui.PushID(tostring(windows.Data[i])) ImGui.DebugNodeWindow(windows.Data[i], "Window") ImGui.PopID() @@ -18219,11 +20986,13 @@ function ImGui.DebugNodeWindowsList(windows, label) ImGui.TreePop() end +-- FIXME-OPT: This is technically suboptimal, but it is simpler this way. function ImGui.DebugNodeWindowsListByBeginStackParent(windows, first, last, parent_in_begin_stack) for i = first, last do local window = windows[i] if window.ParentWindowInBeginStack == parent_in_begin_stack then local buf = string.format("[%04d] Window", window.BeginOrderWithinContext) + -- ImGui.BulletText("[%04d] Window '%s'", window.BeginOrderWithinContext, window.Name) ImGui.DebugNodeWindow(window, buf) ImGui.TreePush(buf) ImGui.DebugNodeWindowsListByBeginStackParent(windows, i + 1, last, window) @@ -18249,6 +21018,7 @@ function ImGui.DebugNodeViewport(viewport) end end +-- Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct. function ImGui.DebugTextEncoding(str) ImGui.Text("Text: \"%s\"", str) if not ImGui.BeginTable("##DebugTextEncoding", 4, bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg, ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.Resizable)) then return end @@ -18274,6 +21044,7 @@ function ImGui.DebugTextEncoding(str) ImGui.EndTable() end +-- Debugging enums local WRT_Names = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" } local TRT_Names = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" } @@ -18291,14 +21062,14 @@ local function GetWindowRect(window, t) end local function GetTableRect(tbl, t, n) - local inst = ImGui.TableGetInstanceData(tbl, tbl.InstanceCurrent) + local inst = ImGui.TableGetInstanceData(tbl, tbl.InstanceCurrent) -- Always using last submitted instance if t == 0 then return tbl.OuterRect elseif t == 1 then return tbl.InnerRect elseif t == 2 then return tbl.WorkRect elseif t == 3 then return tbl.HostClipRect elseif t == 4 then return tbl.InnerClipRect elseif t == 5 then return tbl.BgClipRect end local c = tbl.Columns[n] if t == 6 then return ImRect(c.MinX, tbl.InnerClipRect.Min.y, c.MaxX, tbl.InnerClipRect.Min.y + inst.LastOuterHeight) elseif t == 7 then return ImRect(c.WorkMinX, tbl.WorkRect.Min.y, c.WorkMaxX, tbl.WorkRect.Max.y) elseif t == 8 then return c.ClipRect - elseif t == 9 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXHeadersUsed, tbl.InnerClipRect.Min.y + inst.LastTopHeadersRowHeight) + elseif t == 9 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXHeadersUsed, tbl.InnerClipRect.Min.y + inst.LastTopHeadersRowHeight) -- Note: y1/y2 not always accurate elseif t == 10 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXHeadersIdeal, tbl.InnerClipRect.Min.y + inst.LastTopHeadersRowHeight) elseif t == 11 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXFrozen, tbl.InnerClipRect.Min.y + inst.LastFrozenHeight) else return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y + inst.LastFrozenHeight, c.ContentMaxXUnfrozen, tbl.InnerClipRect.Max.y) end @@ -18327,6 +21098,7 @@ function ImGui.ShowMetricsWindow(p_open) return p_open end + -- Basic info ImGui.Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM) ImGui.Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0 / math.max(io.Framerate, 0.0001), io.Framerate) ImGui.Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, math.floor(io.MetricsRenderIndices / 3)) @@ -18364,7 +21136,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.SetNextItemWidth(ImGui.GetFontSize() * 12) cfg.ShowTablesRectsType, changed = ImGui.Combo("##show_table_rects_type", cfg.ShowTablesRectsType, TRT_Names, #TRT_Names, #TRT_Names) cfg.ShowTablesRects = cfg.ShowTablesRects or changed - _, g.DebugShowGroupRects = ImGui.Checkbox("Show groups rectangles", g.DebugShowGroupRects == true) + _, g.DebugShowGroupRects = ImGui.Checkbox("Show groups rectangles", g.DebugShowGroupRects == true) -- Storing in context as this is used by group code and prefers to be in hot-data ImGui.SeparatorText("Validate") _, io.ConfigDebugBeginReturnValueLoop = ImGui.Checkbox("Debug Begin/BeginChild return value", io.ConfigDebugBeginReturnValueLoop == true) @@ -18383,9 +21155,11 @@ function ImGui.ShowMetricsWindow(p_open) -- Windows if ImGui.TreeNode("Windows", "Windows (%d)", g.Windows.Size) then + -- ImGui.SetNextItemOpen(true, ImGuiCond.Once) ImGui.DebugNodeWindowsList(g.Windows, "By display order") ImGui.DebugNodeWindowsList(g.WindowsFocusOrder, "By focus order (root windows)") if ImGui.TreeNode("By submission order (begin stack)") then + -- Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship! local tmp = {} for _, window in g.Windows:iter() do if window.LastFrameActive + 1 >= g.FrameCount then tmp[#tmp + 1] = window end @@ -18426,7 +21200,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- Fonts + -- Details for Fonts for i, atlas in g.FontAtlases:iter() do if ImGui.TreeNode(tostring(atlas), "Fonts (%d), Textures (%d)", atlas.Fonts.Size, atlas.TexList.Size) then ImGui.ShowFontAtlas(atlas) @@ -18434,9 +21208,10 @@ function ImGui.ShowMetricsWindow(p_open) end end - -- Popups + -- Details for Popups if ImGui.TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size) then for _, popup_data in g.OpenPopupStack:iter() do + -- As it's difficult to interact with tree nodes while popups are open, we display everything inline. local window = popup_data.Window local W = ImGuiWindowFlags ImGui.BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'", popup_data.PopupId, window and window.Name or "NULL", @@ -18446,7 +21221,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- TabBars + -- Details for TabBars if ImGui.TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.AliveCount) then for n = 0, g.TabBars:GetMapSize() - 1 do local tab_bar = g.TabBars:GetByIndex(n) @@ -18459,13 +21234,13 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- Tables + -- Details for Tables if ImGui.TreeNode("Tables", "Tables (%d)", g.Tables.AliveCount) then ForEachTable(g, ImGui.DebugNodeTable) ImGui.TreePop() end - -- Docking + -- Details for Docking if ImGui.TreeNode("Docking") then local dc = g.DockContext _, MetricsDockRootOnly = ImGui.Checkbox("List root nodes", MetricsDockRootOnly) @@ -18531,6 +21306,7 @@ function ImGui.ShowMetricsWindow(p_open) -- Inputs if ImGui.TreeNode("Inputs") then ImGui.Text("KEYBOARD/GAMEPAD/MOUSE KEYS") + -- User code should never have to go through such hoops! You can generally iterate between ImGuiKey.NamedKey_BEGIN and ImGuiKey.NamedKey_END. ImGui.Indent() ImGui.Text("Keys down:") for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do @@ -18583,7 +21359,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.Indent() ImGui.Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, B(g.ActiveIdAllowOverlap)) ImGui.Text("ActiveIdWindow: '%s'", N(g.ActiveIdWindow)) - ImGui.Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, B(g.HoveredIdAllowOverlap)) + ImGui.Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, B(g.HoveredIdAllowOverlap)) -- Not displaying g.HoveredId as it is update mid-frame ImGui.Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId or 0, g.HoverItemDelayTimer or 0, g.HoverItemDelayClearTimer or 0) ImGui.Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\"", B(g.DragDropActive), g.DragDropPayload.SourceId or 0, tostring(g.DragDropPayload.DataType or "")) ImGui.Unindent() @@ -18601,7 +21377,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- Overlays + -- Overlay: Display windows Rectangles and Begin Order if cfg.ShowWindowsRects or cfg.ShowWindowsBeginOrder then for _, window in g.Windows:iter() do if window.WasActive then @@ -18618,6 +21394,8 @@ function ImGui.ShowMetricsWindow(p_open) end end end + + -- Overlay: Display Tables Rectangles if cfg.ShowTablesRects then ForEachTable(g, function(tbl) if tbl.LastFrameActive < g.FrameCount - 1 then return end @@ -18647,20 +21425,127 @@ __FILES['imgui_demo.lua'] = function() -- dear imgui demo (Luau port of imgui_demo.cpp). Optional: the library never calls into this file. do --[[ imgui_demo.lua ]] ---- Dear ImGui WIP --- (Demo Code) Port of imgui_demo.cpp (docking branch) +-- dear imgui, v1.93.0 WIP +-- (demo code) Port of imgui_demo.cpp (docking branch) -- This file: shared demo helpers, ShowDemoWindow(), DemoWindowMenuBar(), DemoWindowWidgets() dispatcher, example tree/image viewer helpers. -- Other parts (all global functions, loaded from the same bundle): +-- Help: +-- - Read FAQ at http://dearimgui.com/faq +-- - Call and read ImGui.ShowDemoWindow() in imgui_demo.lua. +-- - Need help integrating Dear ImGui in your codebase? +-- - Read Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started +-- Read top of imgui.cpp and imgui.h for many details, documentation, comments, links. +-- Get the latest version at https://github.com/ocornut/imgui + +-- How to easily locate code? +-- - Use Tools->Item Picker to debug break in code by clicking any widgets: https://github.com/ocornut/imgui/wiki/Debug-Tools +-- - Browse pthom's online imgui_explorer: web version the demo w/ source code browser: https://pthom.github.io/imgui_explorer +-- - Find a visible string and search for it in the code! + +----------------------------------------------------- +-- PLEASE DO NOT REMOVE THIS FILE FROM YOUR PROJECT! +----------------------------------------------------- +-- Message to the person tempted to delete this file when integrating Dear ImGui into their codebase: +-- Think again! It is the most useful reference code that you and other coders will want to refer to and call. +-- Have the ImGui.ShowDemoWindow() function wired in an always-available debug menu of your game/app! +-- Also include Metrics! ItemPicker! DebugLog! and other debug features. +-- Removing this file from your project is hindering access to documentation for everyone in your team, +-- likely leading you to poorer usage of the library. +-- Whenever you have Dear ImGui available you probably want this to be available for reference. +-- Thank you, +-- -Your beloved friend, imgui_demo.cpp (which you won't delete) + +---------------------------------------------- +-- ABOUT THE MEANING OF THE 'static' KEYWORD: +---------------------------------------------- +-- In the upstream C++ demo code, 'static' variables inside functions are frequently used. +-- A static variable persists across calls. It is essentially a global variable but declared inside the scope of the function. +-- Think of "static int n = 0;" as "global int n = 0;" ! +-- (PORT: Lua has no function-local statics; this port keeps them as fields of file-level tables, e.g. `S`, `SL`, `ST`.) +-- We do this IN THE DEMO because we want: +-- - to gather code and data in the same place. +-- - to make the demo source code faster to read, faster to change, smaller in size. +-- - it is also a convenient way of storing simple UI related information as long as your function +-- doesn't need to be reentrant or used in multiple threads. +-- This might be a pattern you will want to use in your code, but most of the data you would be working +-- with in a complex codebase is likely going to be stored outside your functions. + +------------------------------------------- +-- ABOUT THE CODING STYLE OF OUR DEMO CODE +------------------------------------------- +-- The Demo code in this file is designed to be easy to copy-and-paste into your application! +-- Because of this: +-- - We never omit the ImGui. prefix when calling functions. + +-- Navigating this file: +-- - You can search/grep for all sections listed in the index to find the section. + +-- Index of this file: +-- +-- [SECTION] Helpers +-- [SECTION] Demo Window / ShowDemoWindow() +-- [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) +-- [SECTION] Helpers: ExampleImageViewer +-- [SECTION] DemoWindowWidgetsBasic() +-- [SECTION] DemoWindowWidgetsBullets() +-- [SECTION] DemoWindowWidgetsCollapsingHeaders() +-- [SECTION] DemoWindowWidgetsComboBoxes() +-- [SECTION] DemoWindowWidgetsColorAndPickers() +-- [SECTION] DemoWindowWidgetsDataTypes() +-- [SECTION] DemoWindowWidgetsDisableBlocks() +-- [SECTION] DemoWindowWidgetsDragAndDrop() +-- [SECTION] DemoWindowWidgetsDragsAndSliders() +-- [SECTION] DemoWindowWidgetsFonts() +-- [SECTION] DemoWindowWidgetsImages() +-- [SECTION] DemoWindowWidgetsListBoxes() +-- [SECTION] DemoWindowWidgetsLiveEdit() +-- [SECTION] DemoWindowWidgetsMixedValues() +-- [SECTION] DemoWindowWidgetsMultiComponents() +-- [SECTION] DemoWindowWidgetsPlotting() +-- [SECTION] DemoWindowWidgetsProgressBars() +-- [SECTION] DemoWindowWidgetsQueryingStatuses() +-- [SECTION] DemoWindowWidgetsSelectables() +-- [SECTION] DemoWindowWidgetsTabs() +-- [SECTION] DemoWindowWidgetsText() +-- [SECTION] DemoWindowWidgetsTextFilter() +-- [SECTION] DemoWindowWidgetsTextInput() +-- [SECTION] DemoWindowWidgetsTooltips() +-- [SECTION] DemoWindowWidgetsTreeNodes() +-- [SECTION] DemoWindowWidgetsVerticalSliders() +-- [SECTION] DemoWindowWidgets() +-- [SECTION] DemoWindowLayout() +-- [SECTION] DemoWindowPopups() +-- [SECTION] DemoWindowTables() +-- [SECTION] About Window / ShowAboutWindow() +-- [SECTION] Style Editor / ShowStyleEditor() +-- [SECTION] User Guide / ShowUserGuide() +-- [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() +-- [SECTION] Example App: Debug Console / ShowExampleAppConsole() +-- [SECTION] Example App: Debug Log / ShowExampleAppLog() +-- [SECTION] Example App: Simple Layout / ShowExampleAppLayout() +-- [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() +-- [SECTION] Example App: Long Text / ShowExampleAppLongText() +-- [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() +-- [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize() +-- [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() +-- [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() +-- [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles() +-- [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() +-- [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() +-- [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() + local _ ----------------------------------------------------------------- --- Shared helpers (globals) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Helpers +------------------------------------------------------------------------------- +-- Helper to wire demo markers located in code to an interactive browser (e.g. https://pthom.github.io/imgui_explorer) function IMGUI_DEMO_MARKER(_) end -- upstream hook, no-op here ---- Helper to display a little (?) mark which shows a tooltip when hovered. +-- Helper to display a little (?) mark which shows a tooltip when hovered. +-- In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md) function HelpMarker(desc) ImGui.TextDisabled("(?)") if ImGui.BeginItemTooltip() then @@ -18808,9 +21693,9 @@ function DemoTextFilter() return f end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Demo Window data ----------------------------------------------------------------- +------------------------------------------------------------------------------- --- Data to be shared across different functions of the demo. function ImGuiDemoWindowData() @@ -18848,10 +21733,12 @@ function ImGuiDemoWindowData() } end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Simple representation for a tree +-- (this is designed to be simple to understand for our demos, not to be fancy or efficient etc.) function ExampleTreeNode() return { -- Tree structure @@ -18859,7 +21746,7 @@ function ExampleTreeNode() UID = 0, Parent = nil, Childs = {}, -- 1-based - IndexInParent = 0, -- 0-based + IndexInParent = 0, -- 0-based. Maintaining this allows us to implement linear traversal more easily -- Leaf Data HasData = false, -- All leaves have data @@ -18883,8 +21770,14 @@ end function ExampleTree_DestroyNode(node) end -- GC ---- Create example tree data +-- Create example tree data +-- (warning: this can allocates MANY MANY more times than other code in all of Dear ImGui + demo combined) +-- (a real application managing one million nodes would likely store its tree data differently) function ExampleTree_CreateDemoTree() + -- 20 root nodes -> 211 total nodes, ~261 allocs. + -- 1000 root nodes -> ~11K total nodes, ~14K allocs. + -- 10000 root nodes -> ~123K total nodes, ~154K allocs. + -- 100000 root nodes -> ~1338K total nodes, ~1666K allocs. local ROOT_ITEMS_COUNT = 20 local category_names = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pear", "Pineapple", "Strawberry", "Watermelon" } local category_count = #category_names @@ -18910,9 +21803,9 @@ function ExampleTree_CreateDemoTree() return node_L0 end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Helpers: ExampleImageViewer ----------------------------------------------------------------- +------------------------------------------------------------------------------- function ExampleImageViewerData() return { @@ -18928,7 +21821,7 @@ function ExampleImageViewerData() end function ExampleImageViewer_DrawOptions(data) - ImGui.SetNextItemShortcut(ImGuiKey.G, ImGuiInputFlags.Tooltip) + ImGui.SetNextItemShortcut(ImGuiKey.G, ImGuiInputFlags.Tooltip) -- | ImGuiInputFlags.RouteGlobal _, data.GridEnabled = ImGui.Checkbox("Grid", data.GridEnabled) ImGui.SameLine() ImGui.SetNextItemWidth(ImGui.GetFontSize() * 10.0) @@ -18962,7 +21855,7 @@ function ExampleImageViewer_DrawCanvas(data, canvas_size, image_tex_ref, image_w data.Zoom = DemoClamp(data.Zoom * (1.0 + io.MouseWheel * 0.10), data.ZoomMin, data.ZoomMax) end end - local zoom = data.Zoom + local zoom = data.Zoom -- (float)(int)ViewZoom; if ImGui.IsItemActive() and ImGui.IsMouseDragging(0) then data.ViewOffset.x = data.ViewOffset.x - io.MouseDelta.x / zoom data.ViewOffset.y = data.ViewOffset.y - io.MouseDelta.y / zoom @@ -18998,10 +21891,11 @@ function ExampleImageViewer_DrawCanvas(data, canvas_size, image_tex_ref, image_w draw_list:PopClipRect() end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Demo Window / ShowDemoWindow() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Stored data local demo_data = ImGuiDemoWindowData() local no_titlebar = false @@ -19059,6 +21953,7 @@ local function DemoWindowMenuBar(data) ImGui.EndMenu() end + -- if ImGui.MenuItem("MenuItem") then end -- You can also use MenuItem() inside a menu bar! if ImGui.BeginMenu("Tools") then IMGUI_DEMO_MARKER("Menu/Tools") local io = ImGui.GetIO() @@ -19075,7 +21970,7 @@ local function DemoWindowMenuBar(data) _, data.ShowDebugLog = ImGui.MenuItem("Debug Log", nil, data.ShowDebugLog, has_debug_tools and ImGui.ShowDebugLogWindow ~= nil) _, data.ShowIDStackTool = ImGui.MenuItem("ID Stack Tool", nil, data.ShowIDStackTool, has_debug_tools and ImGui.ShowIDStackToolWindow ~= nil) local is_debugger_present = io.ConfigDebugIsDebuggerPresent - if ImGui.MenuItem("Item Picker", nil, false, has_debug_tools and ImGui.DebugStartItemPicker ~= nil) then + if ImGui.MenuItem("Item Picker", nil, false, has_debug_tools and ImGui.DebugStartItemPicker ~= nil) then -- and is_debugger_present ImGui.DebugStartItemPicker() end if not is_debugger_present then @@ -19183,6 +22078,12 @@ local function DemoWindowConfiguration(io) ImGui.Unindent() end + -- ImGui.SeparatorText("DPI/Scaling") + -- CB("io.ConfigDpiScaleFonts", "ConfigDpiScaleFonts") + -- HM("Experimental: Automatically update style.FontScaleDpi when Monitor DPI changes. This will scale fonts but NOT style sizes/padding for now.") + -- CB("io.ConfigDpiScaleViewports", "ConfigDpiScaleViewports") + -- HM("Experimental: Scale Dear ImGui and Platform Windows when Monitor DPI changes.") + ImGui.SeparatorText("Windows") CB("io.ConfigWindowsResizeFromEdges", "ConfigWindowsResizeFromEdges") HM("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback.") @@ -19256,6 +22157,7 @@ local function DemoWindowConfiguration(io) "Here we expose them as read-only fields to avoid breaking interactions with your backend.") -- Make a local copy to avoid modifying actual backend flags. + -- FIXME: Maybe we need a BeginReadonly() equivalent to keep label bright? local B = ImGuiBackendFlags local backend_flags = io.BackendFlags ImGui.BeginDisabled() @@ -19309,10 +22211,14 @@ local function DemoWindowConfiguration(io) end end ---- Demonstrate most Dear ImGui features (this is big function!) +-- Demonstrate most Dear ImGui features (this is big function!) +-- You may execute this function to experiment with the UI and understand what it does. +-- You may then search for keywords in the code when you are interested by a specific feature. --- @param p_open? bool --- @return bool? p_open function ImGui.ShowDemoWindow(p_open) + -- Exceptionally add an extra assert here for people confused about initial Dear ImGui setup + -- Most functions would normally just assert/crash if the context is missing. IM_ASSERT(ImGui.GetCurrentContext() ~= nil, "Missing Dear ImGui context. Refer to examples app!") local data = demo_data @@ -19368,6 +22274,7 @@ function ImGui.ShowDemoWindow(p_open) if no_close then p_open = nil end -- Don't pass our bool* to Begin -- We specify a default position/size in case there's no data in the .ini file. + -- We only do it to make the demo applications a little more welcoming, but typically this isn't required. local main_viewport = ImGui.GetMainViewport() ImGui.SetNextWindowPos(ImVec2(main_viewport.WorkPos.x + 650, main_viewport.WorkPos.y + 20), ImGuiCond.FirstUseEver) ImGui.SetNextWindowSize(ImVec2(550, 680), ImGuiCond.FirstUseEver) @@ -19383,10 +22290,18 @@ function ImGui.ShowDemoWindow(p_open) end -- Most framed widgets share a common width settings. Remaining width is used for the label. + -- The width of the frame may be changed with PushItemWidth() or SetNextItemWidth(). + -- - Positive value for absolute size, negative value for right-alignment. + -- - The default value is about GetWindowWidth() * 0.65f. + -- - See 'Demo->Layout->Widgets Width' for details. + -- Here we change the frame width based on how much width we want to give to the label. local label_width_base = ImGui.GetFontSize() * 12 -- Some amount of width for label, based on font size. local label_width_max = ImGui.GetContentRegionAvail().x * 0.40 -- ...but always leave some room for framed widgets. local label_width = math.min(label_width_base, label_width_max) ImGui.PushItemWidth(-label_width) -- Right-align: framed items will leave 'label_width' available for the label. + -- ImGui.PushItemWidth(ImGui.GetContentRegionAvail().x * 0.40) -- e.g. Use 40% width for framed widgets, leaving 60% width for labels. + -- ImGui.PushItemWidth(-ImGui.GetContentRegionAvail().x * 0.40) -- e.g. Use 40% width for labels, leaving 60% width for framed widgets. + -- ImGui.PushItemWidth(ImGui.GetFontSize() * -12) -- e.g. Use XXX width for labels, leaving the rest for framed widgets. -- Menu Bar DemoWindowMenuBar(data) @@ -19455,9 +22370,9 @@ function ImGui.ShowDemoWindow(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] DemoWindowWidgets() ----------------------------------------------------------------- +------------------------------------------------------------------------------- --- Calls a (global) demo section if it exists, otherwise shows a placeholder local function Sub(fn, title, ...) @@ -19467,6 +22382,7 @@ local function Sub(fn, title, ...) end function DemoWindowWidgets(data) + -- ImGui.SetNextItemOpen(true, ImGuiCond.Once) if not ImGui.CollapsingHeader("Widgets") then return end @@ -19527,9 +22443,9 @@ function DemoWindowWidgets(data) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] User Guide / ShowUserGuide() ----------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.ShowUserGuide() local io = ImGui.GetIO() @@ -19578,6 +22494,10 @@ do --[[ imgui_demo_2.lua ]] -- DemoWindowInputs() and all ShowExampleAppXXX() example apps. -- Port of imgui_demo.cpp (docking branch). Globals are shared with imgui_demo.lua (HelpMarker, ShowExampleMenuFile, ...) +-- Helpers macros +-- We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste, +-- but making an exception here as those are largely simplifying code... +-- In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo. local IM_MIN = math.min local IM_MAX = math.max local function IM_CLAMP(V, MN, MX) return (V < MN) and MN or (V > MX) and MX or V end @@ -19766,6 +22686,10 @@ local function DemoWindowLayout_ChildWindows() ImGui.SeparatorText("Manual-resize") do DemoHelpMarker("Drag bottom border to resize. Double-click bottom border to auto-fit to vertical contents.") + -- if ImGui.Button("Set Height to 200") then + -- ImGui.SetNextWindowSize(ImVec2(-FLT_MIN, 200.0)) + -- end + ImGui.PushStyleColor(ImGuiCol.ChildBg, ImGui.GetStyleColorVec4(ImGuiCol.FrameBg)) if BeginChild("ResizableChild", ImVec2(-FLT_MIN, ImGui.GetTextLineHeightWithSpacing() * 8), bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.ResizeY)) then for n = 0, 9 do @@ -19795,6 +22719,13 @@ local function DemoWindowLayout_ChildWindows() ImGui.SeparatorText("Misc/Advanced") + -- Demonstrate a few extra things + -- - Changing ImGuiCol.ChildBg (which is transparent black in default styles) + -- - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window) + -- You can also call SetNextWindowPos() to position the child window. The parent window will effectively + -- layout from this position. + -- - Using ImGui.GetItemRectMin/Max() to query the "item" state (because the child window is an item from + -- the POV of the parent window). See 'Demo->Querying Status (Edited/Active/Hovered etc.)' for details. do if SL.child_flags == nil then SL.child_flags = bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY) end ImGui.SetNextItemWidth(ImGui.GetFontSize() * 8) @@ -19835,6 +22766,11 @@ local function DemoWindowLayout_WidgetsWidth() IMGUI_DEMO_MARKER("Layout/Widgets Width") _, SL.show_indented_items = ImGui.Checkbox("Show indented items", SL.show_indented_items) + -- Use SetNextItemWidth() to set the width of a single upcoming item. + -- Use PushItemWidth()/PopItemWidth() to set the width of a group of items. + -- In real code use you'll probably want to choose width values that are proportional to your font size + -- e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc. + local function block(text, help, width, l1, l2) ImGui.Text(text) if help then ImGui.SameLine(); DemoHelpMarker(help) end @@ -19853,6 +22789,7 @@ local function DemoWindowLayout_WidgetsWidth() block("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)", "Align to right edge minus half", -ImGui.GetContentRegionAvail().x * 0.5, "float##4a", "float (indented)##4b") block("SetNextItemWidth/PushItemWidth(-Min(GetContentRegionAvail().x * 0.40f, GetFontSize() * 12))", nil, -IM_MIN(ImGui.GetFontSize() * 12, ImGui.GetContentRegionAvail().x * 0.40), "float##5a", "float (indented)##5b") -- Demonstrate using PushItemWidth to surround three items. + -- Calling SetNextItemWidth() before each of them would have the same effect. block("SetNextItemWidth/PushItemWidth(-FLT_MIN)", "Align to right edge", -FLT_MIN, "##float6a", "float (indented)##6b") end @@ -19920,6 +22857,7 @@ local function DemoWindowLayout_BasicHorizontal() NotPorted("ListBox") end ImGui.PopID() + -- ImGui.SetItemTooltip("ListBox %d hovered", i) end ImGui.PopItemWidth() @@ -19931,6 +22869,7 @@ local function DemoWindowLayout_BasicHorizontal() ImGui.Button("B", button_sz) -- Manually wrapping + -- (we should eventually provide this as an automatic layout feature, but for now you can do it manually) IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Manual wrapping") ImGui.Text("Manual wrapping:") local style = ImGui.GetStyle() @@ -20004,6 +22943,9 @@ local function DemoWindowLayout_TextBaseline() ImGui.Button("Some framed item"); ImGui.SameLine() DemoHelpMarker("Baseline of button will look misaligned with text..") + -- If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. + -- (because we don't know what's coming after the Text() statement, we need to move the text baseline + -- down by FramePadding.y ahead of time) ImGui.AlignTextToFramePadding() ImGui.Text("OK Blahblah"); ImGui.SameLine() ImGui.Button("Some framed item##2"); ImGui.SameLine() @@ -20014,6 +22956,7 @@ local function DemoWindowLayout_TextBaseline() ImGui.Text("TEST"); ImGui.SameLine() ImGui.SmallButton("TEST##2") + -- If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. ImGui.AlignTextToFramePadding() ImGui.Text("Text aligned to framed item"); ImGui.SameLine() ImGui.Button("Item##1"); ImGui.SameLine() @@ -20054,6 +22997,7 @@ local function DemoWindowLayout_TextBaseline() ImGui.BulletText("Misc items:") ImGui.Indent() + -- SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. ImGui.Button("80x80", ImVec2(80, 80)) ImGui.SameLine() ImGui.Button("50x50", ImVec2(50, 50)) @@ -20063,10 +23007,12 @@ local function DemoWindowLayout_TextBaseline() ImGui.SmallButton("SmallButton()") -- Tree + -- (here the node appears after a button and has odd intent, so we use ImGuiTreeNodeFlags.DrawLinesNone to disable hierarchy outline) local spacing = ImGui.GetStyle().ItemInnerSpacing.x ImGui.Button("Button##1") -- Will make line higher ImGui.SameLine(0.0, spacing) if ImGui.TreeNodeEx("Node##1", ImGuiTreeNodeFlags.DrawLinesNone) then + -- Placeholder tree data for i = 0, 5 do ImGui.BulletText("Item %d..", i) end @@ -20082,11 +23028,16 @@ local function DemoWindowLayout_TextBaseline() ImGui.TreePop() end + -- Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. + -- Otherwise you can use SmallButton() (smaller fit). ImGui.AlignTextToFramePadding() + -- Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add + -- other contents "inside" the node. local node_open = ImGui.TreeNode("Node##3") ImGui.SameLine(0.0, spacing); ImGui.Button("Button##3") if node_open then + -- Placeholder tree data for i = 0, 5 do ImGui.BulletText("Item %d..", i) end @@ -20117,12 +23068,12 @@ local function DemoWindowLayout_HorizontalContentsSizeWindow() "Test how different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\n" .. "Use 'Metrics->Tools->Show windows rectangles' to visualize rectangles.") _, SL.show_h_scrollbar = ImGui.Checkbox("H-scrollbar", SL.show_h_scrollbar) - _, SL.show_button = ImGui.Checkbox("Button", SL.show_button) - _, SL.show_tree_nodes = ImGui.Checkbox("Tree nodes", SL.show_tree_nodes) - _, SL.show_text_wrapped = ImGui.Checkbox("Text wrapped", SL.show_text_wrapped) - _, SL.show_columns = ImGui.Checkbox("Columns", SL.show_columns) - _, SL.show_tab_bar = ImGui.Checkbox("Tab bar", SL.show_tab_bar) - _, SL.show_child = ImGui.Checkbox("Child", SL.show_child) + _, SL.show_button = ImGui.Checkbox("Button", SL.show_button) -- Will grow contents size (unless explicitly overwritten) + _, SL.show_tree_nodes = ImGui.Checkbox("Tree nodes", SL.show_tree_nodes) -- Will grow contents size and display highlight over full width + _, SL.show_text_wrapped = ImGui.Checkbox("Text wrapped", SL.show_text_wrapped) -- Will grow and use contents size + _, SL.show_columns = ImGui.Checkbox("Columns", SL.show_columns) -- Will use contents size + _, SL.show_tab_bar = ImGui.Checkbox("Tab bar", SL.show_tab_bar) -- Will use contents size + _, SL.show_child = ImGui.Checkbox("Child", SL.show_child) -- Will grow and use contents size _, SL.explicit_content_size = ImGui.Checkbox("Explicit content size", SL.explicit_content_size) ImGui.Text("Scroll %.1f/%.1f %.1f/%.1f", ImGui.GetScrollX(), ImGui.GetScrollMaxX(), ImGui.GetScrollY(), ImGui.GetScrollMaxY()) if SL.explicit_content_size then @@ -20190,6 +23141,7 @@ end local function DemoWindowLayout_Scrolling() IMGUI_DEMO_MARKER("Layout/Scrolling/Vertical") + -- Vertical scroll functions DemoHelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position.") _, SL.enable_extra_decorations = ImGui.Checkbox("Decoration", SL.enable_extra_decorations) @@ -20280,7 +23232,7 @@ local function DemoWindowLayout_Scrolling() if scroll_to_pos then ImGui.SetScrollFromPosX(ImGui.GetCursorStartPos().x + SL.scroll_to_pos_px, i * 0.25) end - if child_is_visible then + if child_is_visible then -- Avoid calling SetScrollHereY when running with culled items for item = 0, 99 do if item > 0 then ImGui.SameLine() @@ -20313,6 +23265,10 @@ local function DemoWindowLayout_Scrolling() local scrolling_child_size = ImVec2(0, ImGui.GetFrameHeightWithSpacing() * 7 + 30) BeginChild("scrolling", scrolling_child_size, ImGuiChildFlags.Borders, ImGuiWindowFlags.HorizontalScrollbar) for line = 0, SL.lines - 1 do + -- Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine() + -- If you want to create your own time line for a real application you may be better off manipulating + -- the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets + -- yourself. You may also want to use the lower-level ImDrawList API. local num_buttons = 10 + ((line % 2 == 1) and line * 9 or line * 3) local base_w = ImGui.GetFontSize() * 3 for n = 0, num_buttons - 1 do @@ -20347,6 +23303,7 @@ local function DemoWindowLayout_Scrolling() ImGui.Text("%.0f/%.0f", scroll_x, scroll_max_x) if scroll_x_delta ~= 0.0 then -- Demonstrate a trick: you can use Begin to set yourself in the context of another window + -- (here we are already out of your child window) BeginChild("scrolling") ImGui.SetScrollX(ImGui.GetScrollX() + scroll_x_delta) ImGui.EndChild() @@ -20411,7 +23368,7 @@ local function DemoWindowLayout_TextClipping() draw_list:AddText(text_pos, IM_COL32_WHITE, text_str) draw_list:PopClipRect() else - local clip_rect = ImVec4(p0.x, p0.y, p1.x, p1.y) + local clip_rect = ImVec4(p0.x, p0.y, p1.x, p1.y) -- AddText() takes a ImVec4 here so let's convert. draw_list:AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)) draw_list:AddText(ImGui.GetFont(), ImGui.GetFontSize(), text_pos, IM_COL32_WHITE, text_str, 1, #text_str + 1, 0.0, clip_rect) end @@ -20435,6 +23392,9 @@ local function DemoWindowLayout_OverlapMode() ImGui.SetCursorScreenPos(button2_pos) ImGui.Button("Button 2", ImVec2(80, 80)) + -- This is typically used with width-spanning items. + -- (note that Selectable() has a dedicated flag ImGuiSelectableFlags.AllowOverlap, which is a shortcut + -- for using SetNextItemAllowOverlap(). For demo purpose we use SetNextItemAllowOverlap() here.) if SL.enable_allow_overlap then ImGui.SetNextItemAllowOverlap() end @@ -20476,6 +23436,8 @@ local function DemoWindowPopups_Popups() local names = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" } local toggles = SP.toggles + -- Simple selection popup (if you want to show the current selection inside the Button itself, + -- you may want to build a string using the "###" operator to preserve a constant ID with a variable label) if ImGui.Button("Select..") then ImGui.OpenPopup("my_select_popup") end @@ -20557,7 +23519,20 @@ local function DemoWindowPopups_ContextMenus() IMGUI_DEMO_MARKER("Popups/Context menus") DemoHelpMarker("\"Context\" functions are simple helpers to associate a Popup to a given Item or Window identifier.") + -- BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing: + -- if id == 0 then + -- id = GetItemID() -- Use last item id + -- end + -- if IsItemHovered() and IsMouseReleased(ImGuiMouseButton.Right) then + -- OpenPopup(id) + -- end + -- return BeginPopup(id) + -- For advanced uses you may want to replicate and customize this code. + -- See more details in BeginPopupContextItem(). + -- Example 1 + -- When used after an item that has an ID (e.g. Button), we can skip providing an ID to BeginPopupContextItem(), + -- and BeginPopupContextItem() will use the last item ID as the popup ID. do local names = { "Label1", "Label2", "Label3", "Label4", "Label5" } for n = 0, 4 do @@ -20577,6 +23552,8 @@ local function DemoWindowPopups_ContextMenus() end -- Example 2 + -- Popup on a Text() element which doesn't have an identifier: we need to provide an identifier to BeginPopupContextItem(). + -- Using an explicit identifier is also convenient if you want to activate the popups from different locations. do DemoHelpMarker("Text() elements don't have stable identifiers so we need to provide one.") ImGui.Text("Value = %.3f <-- (1) right-click this text", SP.value) @@ -20588,15 +23565,22 @@ local function DemoWindowPopups_ContextMenus() ImGui.EndPopup() end + -- We can also use OpenPopupOnItemClick() to toggle the visibility of a given popup. + -- Here we make it that right-clicking this other text element opens the same popup as above. + -- The popup itself will be submitted by the code above. ImGui.Text("(2) Or right-click this text") ImGui.OpenPopupOnItemClick("my popup", ImGuiPopupFlags.MouseButtonRight) + -- Back to square one: manually open the same popup. if ImGui.Button("(3) Or click this button") then ImGui.OpenPopup("my popup") end end -- Example 3 + -- When using BeginPopupContextItem() with an implicit identifier (nil == use last item ID), + -- we need to make sure your item identifier is stable. + -- In this example we showcase altering the item label while preserving its identifier, using the ### operator (see FAQ). do DemoHelpMarker("Showcase using a popup ID linked to item ID, with the item having a changing label + stable ID using the ### operator.") if SP.name == nil then SP.name = Buf("Label1", 32) end @@ -20630,6 +23614,9 @@ local function DemoWindowPopups_Modals() ImGui.Text("All those beautiful files will be deleted.\nThis operation cannot be undone!") ImGui.Separator() + -- local unused_i = 0 + -- unused_i = ImGui.Combo("Combo", unused_i, "Delete\0Delete harder\0") + ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, ImVec2(0, 0)) _, SP.dont_ask_me_next_time = ImGui.Checkbox("Don't ask me next time", SP.dont_ask_me_next_time) ImGui.PopStyleVar() @@ -20666,6 +23653,9 @@ local function DemoWindowPopups_Modals() ImGui.OpenPopup("Stacked 2") end + -- Also demonstrate passing a p_open bool to BeginPopupModal(), this will create a regular close button which + -- will close the popup. Note that the visibility state of popups is owned by imgui, so the input value + -- of the bool actually doesn't matter here. local unused_open = true if ImGui.BeginPopupModal("Stacked 2", unused_open) then ImGui.Text("Hello from Stacked The Second!") @@ -20688,6 +23678,24 @@ function DemoWindowPopups() return end + -- The properties of popups windows are: + -- - They block normal mouse hovering detection outside them. (*) + -- - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + -- - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as + -- we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup(). + -- (*) One can use IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByPopup) to bypass it and detect hovering even + -- when normally blocked by a popup. + -- Those three properties are connected. The library needs to hold their visibility state BECAUSE it can close + -- popups at any time. + + -- Typical use for regular windows: + -- local my_tool_is_active = false; if ImGui.Button("Open") then my_tool_is_active = true end; [...] if my_tool_is_active then my_tool_is_active, visible = ImGui.Begin("My Tool", my_tool_is_active); [...] ImGui.End() end + -- Typical use for popups: + -- if ImGui.Button("Open") then ImGui.OpenPopup("MyPopup") end; if ImGui.BeginPopup("MyPopup") then [...] ImGui.EndPopup() end + + -- With popups we have to go through a library call (here OpenPopup) to manipulate the visibility state. + -- This may be a bit confusing at first but it should quickly make sense. Follow on the examples below. + if ImGui.TreeNode("Popups") then DemoWindowPopups_Popups(); ImGui.TreePop() end if ImGui.TreeNode("Context menus") then DemoWindowPopups_ContextMenus(); ImGui.TreePop() end if ImGui.TreeNode("Modals") then @@ -20714,6 +23722,11 @@ end -- [SECTION] DemoWindowTables() ------------------------------------------------------------------------------- +-- Dummy data structure that we use for the Table demo. +-- We are passing our own identifier to TableSetupColumn() to facilitate identifying columns in the sorting code. +-- This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID. +-- But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex) +-- If you don't use sorting, you will generally never care about giving column an ID! -- MyItemColumnID local MyItemColumnID_ID, MyItemColumnID_Name, MyItemColumnID_Action, MyItemColumnID_Quantity, MyItemColumnID_Description = 0, 1, 2, 3, 4 @@ -20729,6 +23742,8 @@ local function MyItem_SortWithSortSpecs(sort_specs, items, items_count) end local function cmp(a, b) -- returns <0, 0, >0 for n = 0, sort_specs.SpecsCount - 1 do + -- Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn() + -- We could also choose to identify columns based on their index (sort_spec.ColumnIndex), which is simpler! local sort_spec = get_spec(n) local delta = 0 local uid = sort_spec.ColumnUserID @@ -20744,6 +23759,10 @@ local function MyItem_SortWithSortSpecs(sort_specs, items, items_count) return (sort_spec.SortDirection == ImGuiSortDirection.Ascending) and -1 or 1 end end + + -- table.sort() is instable so always return a way to differentiate items. + -- Your own compare function may want to avoid fallback on implicit sort specs. + -- e.g. a Name compare if it wasn't already part of the sort specs. return a.ID - b.ID end local arr = items.Data or items @@ -20851,11 +23870,16 @@ local function bor(...) return bit32.bor(...) end local TF = setmetatable({}, { __index = function(_, k) return ImGuiTableFlags[k] end }) local ST = {} -- statics for DemoWindowTables (one sub-table per section) +-- Using those as a base value to create width/height that are factor of the size of our font local TEXT_BASE_WIDTH, TEXT_BASE_HEIGHT = 0, 0 local function Tables_Basic() IMGUI_DEMO_MARKER("Tables/Basic") + -- Here we will showcase three different ways to output a table. + -- They are very simple variations of a same thing! + -- [Method 1] Using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column. + -- In many situations, this is the most flexible and easy to use pattern. DemoHelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop.") if ImGui.BeginTable("table1", 3) then for row = 0, 3 do @@ -20869,6 +23893,7 @@ local function Tables_Basic() end -- [Method 2] Using TableNextColumn() called multiple times, instead of using a for loop + TableSetColumnIndex(). + -- This is generally more convenient when you have code manually submitting the contents of each column. DemoHelpMarker("Using TableNextRow() + calling TableNextColumn() _before_ each cell, manually.") if ImGui.BeginTable("table2", 3) then for row = 0, 3 do @@ -20884,6 +23909,8 @@ local function Tables_Basic() end -- [Method 3] We call TableNextColumn() _before_ each cell. We never call TableNextRow(), + -- as TableNextColumn() will automatically wrap around and create new rows as needed. + -- This is generally more convenient when your cells all contains the same type of data. DemoHelpMarker( "Only using TableNextColumn(), which tends to be convenient for tables where every cell contains " .. "the same type of contents.\n This is also more similar to the old NextColumn() function of the " .. @@ -20899,6 +23926,7 @@ end local function Tables_BordersBackground() IMGUI_DEMO_MARKER("Tables/Borders, background") + -- Expose a few Borders related flags interactively local CT_Text, CT_FillButton = 0, 1 local s = ST.borders if s == nil then s = { flags = bor(TF.Borders, TF.RowBg), display_headers = false, contents_type = CT_Text }; ST.borders = s end @@ -20933,6 +23961,8 @@ local function Tables_BordersBackground() PopStyleCompact() if ImGui.BeginTable("table1", 3, s.flags) then + -- Display headers so we can inspect their interaction with borders + -- (Headers are not the main purpose of this section of the demo, so we are not elaborating on them now. See other sections for details) if s.display_headers then ImGui.TableSetupColumn("One") ImGui.TableSetupColumn("Two") @@ -20971,6 +24001,8 @@ end local function Tables_ResizableStretch() IMGUI_DEMO_MARKER("Tables/Resizable, stretch") + -- By default, if we don't enable ScrollX the sizing policy for each column is "Stretch" + -- All columns maintain a sizing weight, and they will occupy all available width. local s = ST.rstretch if s == nil then s = { flags = bor(TF.SizingStretchSame, TF.Resizable, TF.BordersOuter, TF.BordersV, TF.ContextMenuInBody) }; ST.rstretch = s end PushStyleCompact() @@ -20986,6 +24018,10 @@ end local function Tables_ResizableFixed() IMGUI_DEMO_MARKER("Tables/Resizable, fixed") + -- Here we use ImGuiTableFlags.SizingFixedFit (even though _ScrollX is not set) + -- So columns will adopt the "Fixed" policy and will maintain a fixed width regardless of the whole available width (unless table is small) + -- If there is not enough available width to fit all columns, they will however be resized down. + -- FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings DemoHelpMarker( "Using _Resizable + _SizingFixedFit flags.\n" .. "Fixed-width columns generally makes more sense if you want to use horizontal scrolling.\n\n" .. @@ -21057,6 +24093,8 @@ local function Tables_Reorderable() PopStyleCompact() if ImGui.BeginTable("table1", 3, s.flags) then + -- Submit columns name with TableSetupColumn() and call TableHeadersRow() to create a row with a header in each column. + -- (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.) ImGui.TableSetupColumn("One") ImGui.TableSetupColumn("Two") ImGui.TableSetupColumn("Three") @@ -21072,6 +24110,7 @@ local function Tables_Reorderable() end -- Use outer_size.x == 0.0f instead of default to make the table as tight as possible + -- (only valid when no scrolling and no stretch column) if ImGui.BeginTable("table2", 3, bor(s.flags, TF.SizingFixedFit), ImVec2(0.0, 0.0)) then ImGui.TableSetupColumn("One") ImGui.TableSetupColumn("Two") @@ -21090,6 +24129,8 @@ end local function Tables_Padding() IMGUI_DEMO_MARKER("Tables/Padding") + -- First example: showcase use of padding flags and effect of BorderOuterV/BorderInnerV on X padding. + -- We don't expose BorderOuterH/BorderInnerH here because they have no effect on X padding. DemoHelpMarker( "We often want outer padding activated when any using features which makes the edges of a column visible:\n" .. "e.g.:\n" .. @@ -21103,7 +24144,7 @@ local function Tables_Padding() local s = ST.padding if s == nil then s = { flags1 = TF.BordersV, show_headers = false, flags2 = bor(TF.Borders, TF.RowBg), cell_padding = ImVec2(0.0, 0.0), - show_widget_frame_bg = true, text_bufs = {}, init = true } + show_widget_frame_bg = true, text_bufs = {}, init = true } -- text_bufs: Mini text storage for 3x5 cells ST.padding = s end PushStyleCompact() @@ -21136,12 +24177,16 @@ local function Tables_Padding() local buf = string.format("Hello %d,%d", column, row) ImGui.Button(buf, ImVec2(-FLT_MIN, 0.0)) end + -- if bit32.band(ImGui.TableGetColumnFlags(), ImGuiTableColumnFlags.IsHovered) ~= 0 then + -- ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, IM_COL32(0, 100, 0, 255)) + -- end end end ImGui.EndTable() end -- Second example: set style.CellPadding to (0.0) or a custom value. + -- FIXME-TABLE: Vertical border effectively not displayed the same way as horizontal one... DemoHelpMarker("Setting style.CellPadding to (0,0) or a custom value.") PushStyleCompact() @@ -21199,6 +24244,9 @@ local function Tables_SizingPolicies() ImGui.SetNextItemWidth(TEXT_BASE_WIDTH * 30) s.sizing_policy_flags[table_n + 1] = EditTableSizingFlags(s.sizing_policy_flags[table_n + 1]) + -- To make it easier to understand the different sizing policy, + -- For each policy: we display one table where the columns have equal contents width, + -- and one where the columns have different contents width. if ImGui.BeginTable("table1", 3, bor(s.sizing_policy_flags[table_n + 1], s.flags1)) then for row = 0, 2 do ImGui.TableNextRow() @@ -21289,6 +24337,8 @@ local function Tables_VerticalScrolling() _, s.flags = ImGui.CheckboxFlags("ImGuiTableFlags_ScrollY", s.flags, TF.ScrollY) PopStyleCompact() + -- When using ScrollX or ScrollY we need to specify a size for our table container! + -- Otherwise by default the table will fit all available space, like a BeginChild() call. local outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 8) if ImGui.BeginTable("table_scrolly", 3, s.flags, outer_size) then ImGui.TableSetupScrollFreeze(0, 1) -- Make top row always visible @@ -21339,6 +24389,8 @@ local function Tables_HorizontalScrolling() s.freeze_rows = ImGui.DragInt("freeze_rows", s.freeze_rows, 0.2, 0, 9, nil, ImGuiSliderFlags.NoInput) PopStyleCompact() + -- When using ScrollX or ScrollY we need to specify a size for our table container! + -- Otherwise by default the table will fit all available space, like a BeginChild() call. local outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 8) if ImGui.BeginTable("table_scrollx", 7, s.flags, outer_size) then ImGui.TableSetupScrollFreeze(s.freeze_cols, s.freeze_rows) @@ -21353,6 +24405,12 @@ local function Tables_HorizontalScrolling() for row = 0, 19 do ImGui.TableNextRow() for column = 0, 6 do repeat + -- Both TableNextColumn() and TableSetColumnIndex() return true when a column is visible or performing width measurement. + -- Because here we know that: + -- - A) all our columns are contributing the same to row height + -- - B) column 0 is always visible, + -- We only always submit this one column and can skip others. + -- More advanced per-column clipping behaviors may benefit from polling the status flags via TableGetColumnFlags(). if not ImGui.TableSetColumnIndex(column) and column > 0 then break -- continue end @@ -21393,11 +24451,12 @@ end local function Tables_ColumnsFlags() IMGUI_DEMO_MARKER("Tables/Columns flags") + -- Create a first table just to show all the options/flags we want to make visible in our example! local column_count = 3 local column_names = { "One", "Two", "Three" } local s = ST.colflags if s == nil then - s = { column_flags = { ImGuiTableColumnFlags.DefaultSort, ImGuiTableColumnFlags.None, ImGuiTableColumnFlags.DefaultHide }, column_flags_out = { 0, 0, 0 } } + s = { column_flags = { ImGuiTableColumnFlags.DefaultSort, ImGuiTableColumnFlags.None, ImGuiTableColumnFlags.DefaultHide }, column_flags_out = { 0, 0, 0 } } -- column_flags_out: Output from TableGetColumnFlags() ST.colflags = s end @@ -21422,6 +24481,10 @@ local function Tables_ColumnsFlags() ImGui.EndTable() end + -- Create the real table we care about for the example! + -- We use a scrolling table to be able to showcase the difference between the _IsEnabled and _IsVisible flags above, + -- otherwise in a non-scrolling table columns are always visible (unless using ImGuiTableFlags_NoKeepColumnsVisible + -- + resizing the parent window down). local flags = bor(TF.SizingFixedFit, TF.ScrollX, TF.ScrollY, TF.RowBg, TF.BordersOuter, TF.BordersV, TF.Resizable, TF.Reorderable, TF.Hideable, TF.Sortable) local outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 9) if ImGui.BeginTable("table_columns_flags", column_count, flags, outer_size) then @@ -21465,6 +24528,7 @@ local function Tables_ColumnsWidths() _, s.flags1 = ImGui.CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", s.flags1, TF.NoBordersInBodyUntilResize) PopStyleCompact() if ImGui.BeginTable("table1", 3, s.flags1) then + -- We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. ImGui.TableSetupColumn("one", CF.WidthFixed, 100.0) -- Default to 100.0f ImGui.TableSetupColumn("two", CF.WidthFixed, 200.0) -- Default to 200.0f ImGui.TableSetupColumn("three", CF.WidthFixed) -- Default to auto @@ -21493,6 +24557,8 @@ local function Tables_ColumnsWidths() _, s.flags2 = ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuterV", s.flags2, TF.BordersOuterV) PopStyleCompact() if ImGui.BeginTable("table2", 4, s.flags2) then + -- We could also set ImGuiTableFlags_SizingFixedFit on the table and then all columns + -- will default to ImGuiTableColumnFlags_WidthFixed. ImGui.TableSetupColumn("", CF.WidthFixed, 100.0) ImGui.TableSetupColumn("", CF.WidthFixed, TEXT_BASE_WIDTH * 15.0) ImGui.TableSetupColumn("", CF.WidthFixed, TEXT_BASE_WIDTH * 30.0) @@ -21610,6 +24676,8 @@ end local function Tables_OuterSize() IMGUI_DEMO_MARKER("Tables/Outer size") + -- Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY + -- Important to that note how the two flags have slightly different behaviors! ImGui.Text("Using NoHostExtendX and NoHostExtendY:") PushStyleCompact() local s = ST.outer @@ -21686,6 +24754,8 @@ local function Tables_BackgroundColor() for row = 0, 5 do ImGui.TableNextRow() + -- Demonstrate setting a row background color with 'ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBgX, ...)' + -- We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag. if s.row_bg_type ~= 0 then local row_bg_color = ImGui.GetColorU32(s.row_bg_type == 1 and ImVec4(0.7, 0.3, 0.3, 0.65) or ImVec4(0.2 + row * 0.1, 0.2, 0.2, 0.65)) -- Flat or Gradient? ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBg0 + s.row_bg_target, row_bg_color) @@ -21696,6 +24766,10 @@ local function Tables_BackgroundColor() ImGui.TableSetColumnIndex(column) ImGui.Text("%s%s", string.char(65 + row), string.char(48 + column)) + -- Change background of Cells B1->C2 + -- Demonstrate setting a cell background color with 'ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, ...)' + -- (the CellBg color will be blended over the RowBg and ColumnBg colors) + -- We can also pass a column number as a third parameter to TableSetBgColor() and do this outside the column loop. if row >= 1 and row <= 2 and column >= 1 and column <= 2 and s.cell_bg_type == 1 then local cell_bg_color = ImGui.GetColorU32(ImVec4(0.3, 0.3, 0.7, 0.65)) ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, cell_bg_color) @@ -21706,6 +24780,7 @@ local function Tables_BackgroundColor() end end +-- Simple storage to output a dummy file-system. local tree_view_nodes = { { Name = "Root with Long Name", Type = "Folder", Size = -1, ChildIdx = 1, ChildCount = 3 }, -- 0 { Name = "Music", Type = "Folder", Size = -1, ChildIdx = 4, ChildCount = 2 }, -- 1 @@ -21767,6 +24842,7 @@ local function Tables_TreeView() DemoHelpMarker("See \"Columns flags\" section to configure how indentation is applied to individual columns.") if ImGui.BeginTable("3ways", 3, s.table_flags) then + -- The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.NoHide) ImGui.TableSetupColumn("Size", ImGuiTableColumnFlags.WidthFixed, TEXT_BASE_WIDTH * 12.0) ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthFixed, TEXT_BASE_WIDTH * 18.0) @@ -21816,6 +24892,7 @@ local function Tables_ItemWidth() end end +-- Demonstrate using TableHeader() calls instead of TableHeadersRow() local function Tables_CustomHeaders() IMGUI_DEMO_MARKER("Tables/Custom headers") local COLUMNS_COUNT = 3 @@ -21825,9 +24902,15 @@ local function Tables_CustomHeaders() ImGui.TableSetupColumn("Cherry") -- Dummy entire-column selection storage + -- FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox. if ST.column_selected == nil then ST.column_selected = { false, false, false } end local column_selected = ST.column_selected + -- Instead of calling TableHeadersRow() we'll submit custom headers ourselves. + -- (A different approach is also possible: + -- - Specify ImGuiTableColumnFlags_NoHeaderLabel in some TableSetupColumn() call. + -- - Call TableHeadersRow() normally. This will submit TableHeader() with no name. + -- - Then call TableSetColumnIndex() to position yourself in the column and submit your stuff e.g. Checkbox().) ImGui.TableNextRow(ImGuiTableRowFlags.Headers) for column = 0, COLUMNS_COUNT - 1 do ImGui.TableSetColumnIndex(column) @@ -21854,6 +24937,7 @@ local function Tables_CustomHeaders() end end +-- Demonstrate using ImGuiTableColumnFlags_AngledHeader flag to create angled headers local function Tables_AngledHeaders() IMGUI_DEMO_MARKER("Tables/Angled headers") local column_names = { "Track", "cabasa", "ride", "smash", "tom-hi", "tom-mid", "tom-low", "hihat-o", "hihat-c", "snare-s", "snare-c", "clap", "rim", "kick" } @@ -21864,7 +24948,7 @@ local function Tables_AngledHeaders() if s == nil then s = { table_flags = bor(TF.SizingFixedFit, TF.ScrollX, TF.ScrollY, TF.BordersOuter, TF.BordersInnerH, TF.Hideable, TF.Resizable, TF.Reorderable, TF.HighlightHoveredColumn), column_flags = bor(ImGuiTableColumnFlags.AngledHeader, ImGuiTableColumnFlags.WidthFixed), - bools = {}, frozen_cols = 1, frozen_rows = 2 } + bools = {}, frozen_cols = 1, frozen_rows = 2 } -- bools: Dummy storage selection storage for i = 1, columns_count * rows_count do s.bools[i] = false end ST.angled = s end @@ -21920,6 +25004,8 @@ local function Tables_AngledHeaders() end end +-- Demonstrate creating custom context menus inside columns, +-- while playing it nice with context menus provided by TableHeadersRow()/TableHeader() local function Tables_ContextMenus() IMGUI_DEMO_MARKER("Tables/Context menus") DemoHelpMarker( @@ -21932,6 +25018,9 @@ local function Tables_ContextMenus() _, s.flags1 = ImGui.CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", s.flags1, TF.ContextMenuInBody) PopStyleCompact() + -- Context Menus: first example + -- [1.1] Right-click on the TableHeadersRow() line to open the default table context menu. + -- [1.2] Right-click in columns also open the default table context menu (if ImGuiTableFlags_ContextMenuInBody is set) local COLUMNS_COUNT = 3 if ImGui.BeginTable("table_context_menu", COLUMNS_COUNT, s.flags1) then ImGui.TableSetupColumn("One") @@ -21952,6 +25041,10 @@ local function Tables_ContextMenus() ImGui.EndTable() end + -- Context Menus: second example + -- [2.1] Right-click on the TableHeadersRow() line to open the default table context menu. + -- [2.2] Right-click on the ".." to open a custom popup + -- [2.3] Right-click in columns to open another custom popup DemoHelpMarker( "Demonstrate mixing table context menu (over header), item context button (over button) " .. "and custom per-column context menu (over column body).") @@ -21986,6 +25079,8 @@ local function Tables_ContextMenus() end -- [2.3] Right-click anywhere in columns to open another custom popup + -- (instead of testing for not IsAnyItemHovered() we could also call OpenPopup() with ImGuiPopupFlags_NoOpenOverExistingPopup + -- to manage popup priority as the popups triggers, here "are we hovering a column" are overlapping) local hovered_column = -1 for column = 0, COLUMNS_COUNT do ImGui.PushID(column) @@ -22014,6 +25109,7 @@ local function Tables_ContextMenus() end end +-- Demonstrate creating multiple tables with the same ID local function Tables_SyncedInstances() IMGUI_DEMO_MARKER("Tables/Synced instances") DemoHelpMarker("Multiple tables with the same identifier will share their settings, width, visibility, order etc.") @@ -22042,6 +25138,9 @@ local function Tables_SyncedInstances() end end +-- Demonstrate using Sorting facilities +-- This is a simplified version of the "Advanced" example, where we mostly focus on the code necessary to handle sorting. +-- Note that the "Advanced" example also showcase manually triggering a sort (e.g. if item quantities have been modified) local template_items_names = { "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango", "Kiwi", "Orange", "Pineapple", "Blueberry", "Plum", "Coconut", "Pear", "Apricot" @@ -22049,6 +25148,7 @@ local template_items_names = { local function Tables_Sorting() IMGUI_DEMO_MARKER("Tables/Sorting") + -- Create item list local s = ST.sorting if s == nil then s = { items = {}, @@ -22061,6 +25161,7 @@ local function Tables_Sorting() end local items = s.items + -- Options PushStyleCompact() _, s.flags = ImGui.CheckboxFlags("ImGuiTableFlags_SortMulti", s.flags, TF.SortMulti) ImGui.SameLine(); DemoHelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).") @@ -22070,6 +25171,13 @@ local function Tables_Sorting() if ImGui.BeginTable("table_sorting", 4, s.flags, ImVec2(0.0, TEXT_BASE_HEIGHT * 15), 0.0) then local CF = ImGuiTableColumnFlags + -- Declare columns + -- We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + -- This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! + -- Demonstrate using a mixture of flags among available sort-related flags: + -- - ImGuiTableColumnFlags_DefaultSort + -- - ImGuiTableColumnFlags_NoSort / ImGuiTableColumnFlags_NoSortAscending / ImGuiTableColumnFlags_NoSortDescending + -- - ImGuiTableColumnFlags_PreferSortAscending / ImGuiTableColumnFlags_PreferSortDescending ImGui.TableSetupColumn("ID", bor(CF.DefaultSort, CF.WidthFixed), 0.0, MyItemColumnID_ID) ImGui.TableSetupColumn("Name", CF.WidthFixed, 0.0, MyItemColumnID_Name) ImGui.TableSetupColumn("Action", bor(CF.NoSort, CF.WidthFixed), 0.0, MyItemColumnID_Action) @@ -22200,6 +25308,8 @@ local function Tables_AdvancedOptions(s) "- OuterSize.x = 0.0f will narrow fit the table unless there are any Stretch columns.\n" .. "- OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendY is set).") + -- From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling. + -- To facilitate toying with this demo we will actually pass 0.0f to the BeginTable() when ScrollX is disabled. s.inner_width_with_scroll = ImGui.DragFloat("inner_width (when ScrollX active)", s.inner_width_with_scroll, 1.0, 0.0, FLT_MAX) s.row_min_height = ImGui.DragFloat("row_min_height", s.row_min_height, 1.0, 0.0, FLT_MAX) @@ -22220,6 +25330,9 @@ local function Tables_AdvancedOptions(s) ImGui.Spacing() end +-- In this example we'll expose most table flags and settings. +-- For specific flags and settings refer to the corresponding section for more detailed explanation. +-- This section is mostly useful to experiment with combining certain flags or settings with each others. local function Tables_Advanced() IMGUI_DEMO_MARKER("Tables/Advanced") local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 @@ -22233,6 +25346,7 @@ local function Tables_Advanced() items = {}, selection = {}, items_need_sort = false, show_debug_details = false } ST.advanced = s end + --ImGui.SetNextItemOpen(true, ImGuiCond.Once) -- FIXME-TABLE: Enabling this results in initial clipped first pass on table which tend to affect column sizing if ImGui.TreeNode("Options") then Tables_AdvancedOptions(s) ImGui.TreePop() @@ -22252,7 +25366,7 @@ local function Tables_Advanced() local parent_draw_list = ImGui.GetWindowDrawList() local parent_draw_list_draw_cmd_count = parent_draw_list.CmdBuffer.Size local table_scroll_cur, table_scroll_max -- For debug display - local table_draw_list = nil + local table_draw_list = nil -- " -- Submit table local flags = s.flags @@ -22260,6 +25374,9 @@ local function Tables_Advanced() local inner_width_to_use = Has(flags, TF.ScrollX) and s.inner_width_with_scroll or 0.0 local CF = ImGuiTableColumnFlags if ImGui.BeginTable("table_advanced", 6, flags, s.outer_size_enabled and s.outer_size_value or ImVec2(0, 0), inner_width_to_use) then + -- Declare columns + -- We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + -- This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! ImGui.TableSetupColumn("ID", bor(columns_base_flags, CF.DefaultSort, CF.WidthFixed, CF.NoHide), 0.0, MyItemColumnID_ID) ImGui.TableSetupColumn("Name", bor(columns_base_flags, CF.WidthFixed), 0.0, MyItemColumnID_Name) ImGui.TableSetupColumn("Action", bor(columns_base_flags, CF.NoSort, CF.WidthFixed), 0.0, MyItemColumnID_Action) @@ -22279,6 +25396,8 @@ local function Tables_Advanced() end s.items_need_sort = false + -- Take note of whether we are currently sorting based on the Quantity field, + -- we will use this to trigger sorting when we know the data of this column has been modified. local sorts_specs_using_quantity = Has(ImGui.TableGetColumnFlags(3), CF.IsSorted) -- Show headers @@ -22289,6 +25408,8 @@ local function Tables_Advanced() ImGui.TableHeadersRow() end + -- Show data + -- FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here? -- Demonstrate using clipper for large vertical lists local clipper = ImGuiListClipper() clipper:Begin(#items) @@ -22332,6 +25453,10 @@ local function Tables_Advanced() ImGui.TextUnformatted(item.Name) end + -- Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity, + -- and we are currently sorting on the column showing the Quantity. + -- To avoid triggering a sort while holding the button, we only trigger it when the button has been released. + -- You will probably need some extra logic if you want to automatically sort when a specific entry changes. if ImGui.TableSetColumnIndex(2) then if ImGui.SmallButton("Chop") then item.Quantity = item.Quantity + 1 end if sorts_specs_using_quantity and ImGui.IsItemDeactivated() then s.items_need_sort = true end @@ -22381,6 +25506,8 @@ end local DCS = { selected = -1, h_borders = true, v_borders = true, columns_count = 4, foo = 1.0, bar = 1.0 } +-- Demonstrate old/legacy Columns API! +-- [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!] local function DemoWindowColumns() local open = ImGui.TreeNode("Legacy Columns API") ImGui.SameLine() @@ -22398,6 +25525,7 @@ local function DemoWindowColumns() for n = 0, 13 do local label = string.format("Item %d", n) if ImGui.Selectable(label) then end + --if ImGui.Button(label, ImVec2(-FLT_MIN,0.0)) then end ImGui.NextColumn() end ImGui.Columns(1) @@ -22596,6 +25724,7 @@ local tables_sections = { } function DemoWindowTables() + --ImGui.SetNextItemOpen(true, ImGuiCond.Once) if not ImGui.CollapsingHeader("Tables & Columns") then return end @@ -22626,6 +25755,16 @@ function DemoWindowTables() ImGui.PushStyleVar(ImGuiStyleVar.IndentSpacing, 0.0) end + -- About Styling of tables + -- Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs. + -- There are however a few settings that a shared and part of the ImGuiStyle structure: + -- style.CellPadding -- Padding within each cell + -- style.Colors[ImGuiCol.TableHeaderBg] -- Table header background + -- style.Colors[ImGuiCol.TableBorderStrong] -- Table outer and header borders + -- style.Colors[ImGuiCol.TableBorderLight] -- Table inner borders + -- style.Colors[ImGuiCol.TableRowBg] -- Table row background when ImGuiTableFlags_RowBg is enabled (even rows) + -- style.Colors[ImGuiCol.TableRowBgAlt] -- Table row background when ImGuiTableFlags_RowBg is enabled (odds rows) + -- Demos for _, sec in ipairs(tables_sections) do if open_action ~= -1 then @@ -22657,26 +25796,36 @@ local function BufSet(buf, str) buf[#str + 1] = 0 end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Debug Console / ShowExampleAppConsole() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a simple console window, with scrolling, filtering, completion and history. +-- For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions. local Console = nil local function ConsoleNew() + -- HistoryPos: -1: new line, 0..#History-1 browsing history. + -- "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. local c = { InputBuf = Buf("", 256), Items = {}, Commands = { "HELP", "HISTORY", "CLEAR", "CLASSIFY" }, History = {}, HistoryPos = -1, Filter = ImGuiTextFilter(), AutoScroll = true, ScrollToBottom = false } function c:ClearLog() self.Items = {} end function c:AddLog(fmt, ...) + -- FIXME-OPT local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt self.Items[#self.Items + 1] = s end function c:ExecCommand(command_line) self:AddLog("# %s\n", command_line) + + -- Insert into history. First find match and delete it so it can be pushed to the back. + -- This isn't trying to be smart or optimal. self.HistoryPos = -1 for i = #self.History, 1, -1 do if string.upper(self.History[i]) == string.upper(command_line) then table.remove(self.History, i); break end end self.History[#self.History + 1] = command_line + + -- Process command local cmd = string.upper(command_line) if cmd == "CLEAR" then self:ClearLog() @@ -22689,10 +25838,15 @@ local function ConsoleNew() else self:AddLog("Unknown command: '%s'\n", command_line) end + + -- On command input, we scroll to bottom even if AutoScroll==false self.ScrollToBottom = true end function c:TextEditCallback(data) + --self:AddLog("cursor: %d, selection: %d-%d", data.CursorPos, data.SelectionStart, data.SelectionEnd) if data.EventFlag == ImGuiInputTextFlags.CallbackCompletion then + -- Example of TEXT COMPLETION + -- Locate beginning of current word (positions are 0-based offsets into data.Buf) local word_end = data.CursorPos local word_start = word_end @@ -22703,17 +25857,23 @@ local function ConsoleNew() end local word = "" for i = word_start + 1, word_end do word = word .. string.char(data.Buf[i]) end + + -- Build a list of candidates local candidates = {} for i = 1, #self.Commands do if string.upper(string.sub(self.Commands[i], 1, #word)) == string.upper(word) then candidates[#candidates + 1] = self.Commands[i] end end if #candidates == 0 then + -- No match self:AddLog("No match for \"%s\"!\n", word) elseif #candidates == 1 then + -- Single match. Delete the beginning of the word and replace it entirely so we've got nice casing. data:DeleteChars(word_start, word_end - word_start) data:InsertChars(data.CursorPos, candidates[1]) data:InsertChars(data.CursorPos, " ") else + -- Multiple matches. Complete as much as we can.. + -- So inputting "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches. local match_len = word_end - word_start while true do local ch, all_match = nil, true @@ -22728,10 +25888,13 @@ local function ConsoleNew() data:DeleteChars(word_start, word_end - word_start) data:InsertChars(data.CursorPos, string.sub(candidates[1], 1, match_len)) end + + -- List matches self:AddLog("Possible matches:\n") for i = 1, #candidates do self:AddLog("- %s\n", candidates[i]) end end elseif data.EventFlag == ImGuiInputTextFlags.CallbackHistory then + -- Example of HISTORY local prev_history_pos = self.HistoryPos if data.EventKey == ImGuiKey.UpArrow then if self.HistoryPos == -1 then self.HistoryPos = #self.History - 1 @@ -22742,6 +25905,8 @@ local function ConsoleNew() if self.HistoryPos >= #self.History then self.HistoryPos = -1 end end end + + -- A better implementation would preserve the data on the current input line along with cursor position. if prev_history_pos ~= self.HistoryPos then local history_str = (self.HistoryPos >= 0) and self.History[self.HistoryPos + 1] or "" data:DeleteChars(0, data.BufTextLen) @@ -22756,12 +25921,18 @@ local function ConsoleNew() p_open, visible = ImGui.Begin(title, p_open) if not visible then ImGui.End(); return p_open end + -- As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. + -- So e.g. IsItemHovered() will return true when hovering the title bar. + -- Here we create a context menu only available from the title bar. if ImGui.BeginPopupContextItem() then if ImGui.MenuItem("Close Console") then p_open = false end ImGui.EndPopup() end ImGui.TextWrapped("This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc.") ImGui.TextWrapped("Enter 'HELP' for help.") + + -- TODO: display items starting from the bottom + if ImGui.SmallButton("Add Debug Text") then self:AddLog("%d some text", #self.Items); self:AddLog("some more text"); self:AddLog("display very important message here!") end ImGui.SameLine() if ImGui.SmallButton("Add Debug Error") then self:AddLog("[error] something went wrong") end @@ -22769,12 +25940,17 @@ local function ConsoleNew() if ImGui.SmallButton("Clear") then self:ClearLog() end ImGui.SameLine() local copy_to_clipboard = ImGui.SmallButton("Copy") + --local t = 0.0; if ImGui.GetTime() - t > 0.02 then t = ImGui.GetTime(); self:AddLog("Spam %f", t) end + ImGui.Separator() + -- Options menu if ImGui.BeginPopup("Options") then _, self.AutoScroll = ImGui.Checkbox("Auto-scroll", self.AutoScroll) ImGui.EndPopup() end + + -- Options, Filter ImGui.SetNextItemShortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.O), ImGuiInputFlags.Tooltip) if ImGui.Button("Options") then ImGui.OpenPopup("Options") end ImGui.SameLine() @@ -22783,6 +25959,7 @@ local function ConsoleNew() self.Filter:DrawWithHint("##Filter", "Filter (incl -excl)") ImGui.Separator() + -- Reserve enough left-over height for 1 separator + 1 input text local style = ImGui.GetStyle() local footer_height_to_reserve = (style.SeparatorSize or 1.0) + style.ItemSpacing.y + ImGui.GetFrameHeightWithSpacing() if ImGui.BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), ImGuiChildFlags.NavFlattened, ImGuiWindowFlags.HorizontalScrollbar) then @@ -22790,10 +25967,37 @@ local function ConsoleNew() if ImGui.Selectable("Clear") then self:ClearLog() end ImGui.EndPopup() end - ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(4, 1)) + + -- Display every line as a separate entry so we can change their color or add custom widgets. + -- If you only want raw text you can use ImGui.TextUnformatted(log.begin(), log.end()) + -- NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping + -- to only process visible items. The clipper will automatically measure the height of your first item and then + -- "seek" to display only items in the visible area. + -- To use the clipper we can replace your standard loop: + -- for i = 1, #Items do + -- With: + -- local clipper = ImGuiListClipper() + -- clipper:Begin(#Items) + -- while clipper:Step() do + -- for i = clipper.DisplayStart, clipper.DisplayEnd - 1 do + -- - That your items are evenly spaced (same height) + -- - That you have cheap random access to your elements (you can access them given their index, + -- without processing all the ones before) + -- You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property. + -- We would need random-access on the post-filtered list. + -- A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices + -- or offsets of items that passed the filtering test, recomputing this array when user changes the filter, + -- and appending newly elements as they are inserted. This is left as a task to the user until we can manage + -- to improve this example code! + -- If your items are of variable height: + -- - Split them into same height items would be simpler and facilitate random-seeking into your list. + -- - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items. + ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(4, 1)) -- Tighten spacing if copy_to_clipboard then ImGui.LogToClipboard() end for _, item in ipairs(self.Items) do if self.Filter:PassFilter(item) then + -- Normally you would store more information in your item than just a string. + -- (e.g. make Items[] an array of structure, store color/type etc.) local color if string.find(item, "[error]", 1, true) then color = ImVec4(1.0, 0.4, 0.4, 1.0) elseif string.sub(item, 1, 2) == "# " then color = ImVec4(1.0, 0.8, 0.6, 1.0) end @@ -22803,6 +26007,9 @@ local function ConsoleNew() end end if copy_to_clipboard then ImGui.LogFinish() end + + -- Keep up at the bottom of the scroll region if we were already at the bottom at the beginning of the frame. + -- Using a scrollbar or mouse-wheel will take away from the bottom edge. if self.ScrollToBottom or (self.AutoScroll and ImGui.GetScrollY() >= ImGui.GetScrollMaxY()) then ImGui.SetScrollHereY(1.0) end self.ScrollToBottom = false ImGui.PopStyleVar() @@ -22810,6 +26017,7 @@ local function ConsoleNew() ImGui.EndChild() ImGui.Separator() + -- Command-line local reclaim_focus = false local IT = ImGuiInputTextFlags local input_text_flags = bit32.bor(IT.EnterReturnsTrue, IT.EscapeClearsAll, IT.CallbackCompletion, IT.CallbackHistory) @@ -22819,8 +26027,10 @@ local function ConsoleNew() self.InputBuf[1] = 0 reclaim_focus = true end + + -- Auto-focus on window apparition ImGui.SetItemDefaultFocus() - if reclaim_focus then ImGui.SetKeyboardFocusHere(-1) end + if reclaim_focus then ImGui.SetKeyboardFocusHere(-1) end -- Auto focus previous widget ImGui.End() return p_open end @@ -22833,13 +26043,17 @@ function ShowExampleAppConsole(p_open) return Console:Draw("Example: Console", p_open) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Debug Log / ShowExampleAppLog() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Usage: +-- local my_log = ExampleAppLog() +-- my_log:AddLog("Hello %d world\n", 123) +-- my_log:Draw("title") -- Lines are stored as a Lua array (equivalent of Buf + LineOffsets) local function ExampleAppLog() - local l = { Lines = { "" }, Filter = ImGuiTextFilter(), AutoScroll = true } + local l = { Lines = { "" }, Filter = ImGuiTextFilter(), AutoScroll = true } -- AutoScroll: Keep scrolling if already at the bottom. function l:Clear() self.Lines = { "" } end function l:AddLog(fmt, ...) local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt @@ -22854,10 +26068,14 @@ local function ExampleAppLog() local visible p_open, visible = ImGui.Begin(title, p_open) if not visible then ImGui.End(); return p_open end + + -- Options menu if ImGui.BeginPopup("Options") then _, self.AutoScroll = ImGui.Checkbox("Auto-scroll", self.AutoScroll) ImGui.EndPopup() end + + -- Main window if ImGui.Button("Options") then ImGui.OpenPopup("Options") end ImGui.SameLine() local clear = ImGui.Button("Clear") @@ -22873,10 +26091,27 @@ local function ExampleAppLog() ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0)) local lines = self.Lines if self.Filter:IsActive() then + -- In this example we don't use the clipper when Filter is enabled. + -- This is because we don't have random access to the result of our filter. + -- A real application processing logs with ten of thousands of entries may want to store the result of + -- search/filter.. especially if the filtering function is not trivial (e.g. reg-exp). for line_no = 1, #lines do if self.Filter:PassFilter(lines[line_no]) then ImGui.TextUnformatted(lines[line_no]) end end else + -- The simplest and easy way to display the entire buffer: + -- ImGui.TextUnformatted(buf_begin, buf_end) + -- And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward + -- to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are + -- within the visible area. + -- If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them + -- on your side is recommended. Using ImGuiListClipper requires + -- - A) random access into your data + -- - B) items all being the same height, + -- both of which we can handle since we have an array pointing to the beginning of each line of text. + -- When using the filter (in the block of code above) we don't have random access into the data to display + -- anymore, which is why we don't use the clipper. Storing or skimming through the search result would make + -- it possible (and would be recommended if you want to search through tens of thousands of entries). local clipper = ImGuiListClipper() clipper:Begin(#lines) while clipper:Step() do @@ -22886,6 +26121,9 @@ local function ExampleAppLog() end ImGui.PopStyleVar() if copy then ImGui.LogFinish() end + + -- Keep up at the bottom of the scroll region if we were already at the bottom at the beginning of the frame. + -- Using a scrollbar or mouse-wheel will take away from the bottom edge. if self.AutoScroll and ImGui.GetScrollY() >= ImGui.GetScrollMaxY() then ImGui.SetScrollHereY(1.0) end end ImGui.EndChild() @@ -22895,9 +26133,14 @@ local function ExampleAppLog() return l end +-- Demonstrate creating a simple log window with basic filtering. local AppLog, AppLogCounter = nil, 0 function ShowExampleAppLog(p_open) AppLog = AppLog or ExampleAppLog() + + -- For the demo: add a debug button _BEFORE_ the normal log window contents + -- We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window. + -- Most of the contents of the window will be added by the log:Draw() call. ImGui.SetNextWindowSize(ImVec2(500, 400), ImGuiCond.FirstUseEver) p_open = ImGui.Begin("Example: Log", p_open) if ImGui.SmallButton("[Debug] Add 5 entries") then @@ -22911,13 +26154,16 @@ function ShowExampleAppLog(p_open) end end ImGui.End() + + -- Actually call in the regular Log helper (which will Begin() into the same window as we just did) return AppLog:Draw("Example: Log", p_open) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Simple Layout / ShowExampleAppLayout() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate create a window with multiple child windows. local LayoutSelected = 0 function ShowExampleAppLayout(p_open) ImGui.SetNextWindowSize(ImVec2(500, 440), ImGuiCond.FirstUseEver) @@ -22931,14 +26177,18 @@ function ShowExampleAppLayout(p_open) end ImGui.EndMenuBar() end + + -- Left ImGui.BeginChild("left pane", ImVec2(150, 0), bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.ResizeX)) for i = 0, 99 do if ImGui.Selectable(string.format("MyObject %d", i), LayoutSelected == i, ImGuiSelectableFlags.SelectOnNav) then LayoutSelected = i end end ImGui.EndChild() ImGui.SameLine() + + -- Right ImGui.BeginGroup() - ImGui.BeginChild("item view", ImVec2(0, -ImGui.GetFrameHeightWithSpacing())) + ImGui.BeginChild("item view", ImVec2(0, -ImGui.GetFrameHeightWithSpacing())) -- Leave room for 1 line below us ImGui.Text("MyObject: %d", LayoutSelected) ImGui.Separator() if ImGui.BeginTabBar("##Tabs", ImGuiTabBarFlags.None) then @@ -22962,9 +26212,14 @@ function ShowExampleAppLayout(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Some of the interactions are a bit lack-luster: +-- - We would want pressing validating or leaving the filter to somehow restore focus. +-- - We may want more advanced filtering (child nodes) and clipper support: both will need extra work. +-- - We would want to customize some keyboard interactions to easily keyboard navigate between the tree and the properties. +------------------------------------------------------------------------------- -- ExampleMemberInfo equivalent: field name, data type, component count local ExampleTreeNodeMemberInfos = { @@ -22976,19 +26231,30 @@ local ExampleTreeNodeMemberInfos = { local PropEd = { Filter = nil, SelectedNode = nil, UseClipper = false, NameBufs = setmetatable({}, { __mode = "k" }) } +-- Custom search filter +-- - Here we apply on root node only. +-- - This does a case insensitive stristr which is pretty heavy. In a real large-scale app you would likely store a filtered list which in turns would be trivial to linearize. function PropEd:IsNodePassingFilter(node) return node.Parent.Parent ~= nil or self.Filter:PassFilter(node.Name) end +-- To support node with same name we incorporate node.UID into the item ID. +-- (this would more naturally be done using PushID(node.UID) + TreeNodeEx(node.Name, tree_flags), +-- but it would require in DrawClippedTreeNodeAndAdvanceToNext() to add PushID() before TreePush(), and PopID() after TreePop(), +-- so instead we use TreeNodeEx(node.UID, tree_flags, "%s", node.Name) here) function PropEd:DrawTreeNode(node) local TN = ImGuiTreeNodeFlags ImGui.TableNextRow() ImGui.TableNextColumn() + -- OpenOnArrow | OpenOnDoubleClick: Standard opening mode as we are likely to want to add selection afterwards + -- NavLeftJumpsToParent: Left arrow support + -- SpanFullWidth: Span full width for easier mouse reach + -- DrawLinesToNodes: Always draw hierarchy outlines local tree_flags = bit32.bor(TN.OpenOnArrow, TN.OpenOnDoubleClick, TN.NavLeftJumpsToParent, TN.SpanFullWidth, TN.DrawLinesToNodes) - if node == self.SelectedNode then tree_flags = bit32.bor(tree_flags, TN.Selected) end - if #node.Childs == 0 then tree_flags = bit32.bor(tree_flags, TN.Leaf, TN.Bullet, TN.NoTreePushOnOpen) end + if node == self.SelectedNode then tree_flags = bit32.bor(tree_flags, TN.Selected) end -- Draw selection highlight + if #node.Childs == 0 then tree_flags = bit32.bor(tree_flags, TN.Leaf, TN.Bullet, TN.NoTreePushOnOpen) end -- Use _NoTreePushOnOpen + set is_open=false to avoid unnecessarily push/pop on leaves. if node.DataMyBool == false then ImGui.PushStyleColor(ImGuiCol.Text, ImGui.GetStyle().Colors[ImGuiCol.TextDisabled]) end - ImGui.SetNextItemStorageID(node.UID) + ImGui.SetNextItemStorageID(node.UID) -- Use node.UID as storage id local is_open = ImGui.TreeNodeEx(node.UID, tree_flags, "%s", node.Name) if #node.Childs == 0 then is_open = false end if node.DataMyBool == false then ImGui.PopStyleColor() end @@ -22996,6 +26262,10 @@ function PropEd:DrawTreeNode(node) return is_open end +-- Basic version, recursive. This is how you would generally draw a tree. +-- - Simple but going to be noticeably costly if you have a large amount of nodes as DrawTreeNode() is called for all of them. +-- - On my desktop PC (2020), for 10K nodes in an optimized build this takes ~1.2 ms +-- - Unlike arrays or grids which are very easy to clip, trees are currently more difficult to clip. function PropEd:DrawTree(node) for _, child in ipairs(node.Childs) do if self:IsNodePassingFilter(child) and self:DrawTreeNode(child) then @@ -23007,6 +26277,7 @@ end function PropEd:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) if self:IsNodePassingFilter(node) then + -- Draw node if within visible range local is_open if clipper.UserIndex >= clipper.DisplayStart and clipper.UserIndex < clipper.DisplayEnd then is_open = self:DrawTreeNode(node) @@ -23015,8 +26286,12 @@ function PropEd:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) if is_open then ImGui.TreePush(node.Name) end end clipper.UserIndex = clipper.UserIndex + 1 + + -- Next node: recurse into childs if is_open then return node.Childs[1] end end + + -- Next node: next sibling, otherwise move back to parent while node ~= nil do if node.IndexInParent + 1 < #node.Parent.Childs then return node.Parent.Childs[node.IndexInParent + 2] @@ -23028,8 +26303,18 @@ function PropEd:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) return nil end +-- More advanced version. Use a alternative clipping technique: fast-forwarding through non-visible chunks. +-- - On my desktop PC (2020), for 10K nodes in an optimized build this takes ~0.1 ms +-- (in ExampleTree_CreateDemoTree(), change 'ROOT_ITEMS_COUNT = 10000' to try with this amount of root nodes). +-- - 1. Use clipper with indeterminate count (items_count = INT_MAX): we need to call SeekCursorForItem() at the end once we know the count. +-- - 2. Use SetNextItemStorageID() to specify ID used for open/close storage, making it easy to call TreeNodeGetOpen() on any arbitrary node. +-- - 3. Linearize tree during traversal: our tree data structure makes it easy to access sibling and parents. +-- - Unlike clipping for a regular array or grid which may be done using random access limited to visible areas, +-- this technique requires traversing most accessible nodes. This could be made more optimal with extra work, +-- but this is a decent simplicity<>speed trade-off. +-- See https://github.com/ocornut/imgui/issues/3823 for discussions about this. function PropEd:DrawClippedTree(root_node) - local node = root_node.Childs[1] + local node = root_node.Childs[1] -- First node local clipper = ImGuiListClipper() clipper:Begin(INT_MAX) while clipper:Step() do @@ -23037,14 +26322,23 @@ function PropEd:DrawClippedTree(root_node) node = self:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) end end + + -- Keep going to count nodes and submit final count so we have a reliable scrollbar. + -- - One could consider caching this value and only refreshing it occasionally e.g. window is focused and an action occurs. + -- - Incorrect but cheap approximation would be to use 'clipper_current_idx = IM_MAX(clipper_current_idx, #root_node.Childs)' instead. + -- - If either of those is implemented, the general cost will approach zero when scrolling is at the top of the tree. while node ~= nil do node = self:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) end + --clipper.UserIndex = math.max(clipper.UserIndex, #root_node.Childs) -- <-- Cheap approximation instead of while() loop above. clipper:SeekCursorForItem(clipper.UserIndex) end function PropEd:Draw(root_node) self.Filter = self.Filter or ImGuiTextFilter() + -- Left side: draw tree + -- - Currently using a table to benefit from RowBg feature + -- - Our tree node are all of equal height, facilitating the use of a clipper. if ImGui.BeginChild("##tree", ImVec2(300, 0), bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.Borders, ImGuiChildFlags.NavFlattened)) then ImGui.PushItemFlag(ImGuiItemFlags.NoNavDefaultFocus, true) _, self.UseClipper = ImGui.Checkbox("Use Clipper", self.UseClipper) @@ -23063,18 +26357,24 @@ function PropEd:Draw(root_node) end ImGui.EndChild() + -- Right side: draw properties ImGui.SameLine() - ImGui.BeginGroup() + + ImGui.BeginGroup() -- Lock X position local node = self.SelectedNode if node then ImGui.Text("%s", node.Name) ImGui.TextDisabled("UID: 0x%08X", node.UID) ImGui.Separator() if ImGui.BeginTable("##properties", 2, bit32.bor(ImGuiTableFlags.Resizable, ImGuiTableFlags.ScrollY)) then + -- Push object ID after we entered the table, so table is shared for all objects ImGui.PushID(node.UID) ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed) - ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthStretch, 2.0) + ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthStretch, 2.0) -- Default twice larger if node.HasData then + -- In a typical application, the structure description would be derived from a data-driven system. + -- - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array. + -- - Limits and some details are hard-coded to simplify the demo. for _, field_desc in ipairs(ExampleTreeNodeMemberInfos) do ImGui.TableNextRow() ImGui.PushID(field_desc.Name) @@ -23106,6 +26406,7 @@ function PropEd:Draw(root_node) ImGui.EndGroup() end +-- Demonstrate creating a simple property editor. local DemoTree = nil function ShowExampleAppPropertyEditor(p_open, demo_data) ImGui.SetNextWindowSize(ImVec2(430, 450), ImGuiCond.FirstUseEver) @@ -23119,10 +26420,11 @@ function ShowExampleAppPropertyEditor(p_open, demo_data) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Long Text / ShowExampleAppLongText() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate/test rendering huge amount of text, and the incidence of clipping. local LT = { test_type = 0, log = {}, lines = 0, bytes = 0 } function ShowExampleAppLongText(p_open) ImGui.SetNextWindowSize(ImVec2(520, 600), ImGuiCond.FirstUseEver) @@ -23145,9 +26447,11 @@ function ShowExampleAppLongText(p_open) end ImGui.BeginChild("Log") if LT.test_type == 0 then + -- Single call to TextUnformatted() with a big buffer LT.text = LT.text or table.concat(LT.log) ImGui.TextUnformatted(LT.text) elseif LT.test_type == 1 then + -- Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0)) local clipper = ImGuiListClipper() clipper:Begin(LT.lines) @@ -23156,6 +26460,7 @@ function ShowExampleAppLongText(p_open) end ImGui.PopStyleVar() else + -- Multiple calls to Text(), not clipped (slow) ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0)) for i = 0, LT.lines - 1 do ImGui.Text("%i The quick brown fox jumps over the lazy dog", i) end ImGui.PopStyleVar() @@ -23165,10 +26470,11 @@ function ShowExampleAppLongText(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a window which gets auto-resized according to its content. local AutoResizeLines = 10 function ShowExampleAppAutoResize(p_open) local visible @@ -23176,17 +26482,23 @@ function ShowExampleAppAutoResize(p_open) if not visible then ImGui.End(); return p_open end ImGui.TextUnformatted("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop.") AutoResizeLines = ImGui.SliderInt("Number of lines", AutoResizeLines, 1, 20) - for i = 0, AutoResizeLines - 1 do ImGui.Text("%sThis is line %d", string.rep(" ", i * 4), i) end + for i = 0, AutoResizeLines - 1 do ImGui.Text("%sThis is line %d", string.rep(" ", i * 4), i) end -- Pad with space to extend size horizontally ImGui.End() return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize() ----------------------------------------------------------------- +------------------------------------------------------------------------------- -local CR = { auto_resize = false, window_padding = true, type = 6, display_lines = 10 } +-- Demonstrate creating a window with custom resize constraints. +-- Note that size constraints currently don't work on a docked window (when in 'docking' branch) +-- Options +local CR = { auto_resize = false, window_padding = true, type = 6, display_lines = 10 } -- type 6: Aspect Ratio function ShowExampleAppConstrainedResize(p_open) + -- Helper functions to demonstrate programmatic constraints + -- FIXME: This doesn't take account of decoration size (e.g. title bar), library should make this easier. + -- FIXME: None of the three demos works consistently when resizing from borders. local function AspectRatio(data) data.DesiredSize.y = math.floor(data.DesiredSize.x / data.UserData) end local function Square(data) local m = math.max(data.DesiredSize.x, data.DesiredSize.y); data.DesiredSize.x = m; data.DesiredSize.y = m end local function Step(data) @@ -23195,17 +26507,19 @@ function ShowExampleAppConstrainedResize(p_open) end local test_desc = { "Between 100x100 and 500x500", "At least 100x100", "Resize vertical + lock current width", "Resize horizontal + lock current height", "Width Between 400 and 500", "Height at least 400", "Custom: Aspect Ratio 16:9", "Custom: Always Square", "Custom: Fixed Steps (100)" } + -- Submit constraint local t = CR.type - if t == 0 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(500, 500)) end - if t == 1 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)) end - if t == 2 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)) end - if t == 3 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)) end - if t == 4 then ImGui.SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)) end - if t == 5 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, FLT_MAX)) end - if t == 6 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), AspectRatio, 16.0 / 9.0) end - if t == 7 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Square) end - if t == 8 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Step, 100.0) end + if t == 0 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(500, 500)) end -- Between 100x100 and 500x500 + if t == 1 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)) end -- Width > 100, Height > 100 + if t == 2 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)) end -- Resize vertical + lock current width + if t == 3 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)) end -- Resize horizontal + lock current height + if t == 4 then ImGui.SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)) end -- Width Between and 400 and 500 + if t == 5 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, FLT_MAX)) end -- Height at least 400 + if t == 6 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), AspectRatio, 16.0 / 9.0) end -- Aspect ratio + if t == 7 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Square) end -- Always Square + if t == 8 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Step, 100.0) end -- Fixed Step + -- Submit window if not CR.window_padding then ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0.0, 0.0)) end local window_flags = CR.auto_resize and ImGuiWindowFlags.AlwaysAutoResize or 0 local window_open @@ -23213,6 +26527,7 @@ function ShowExampleAppConstrainedResize(p_open) if not CR.window_padding then ImGui.PopStyleVar() end if window_open then if ImGui.GetIO().KeyShift then + -- Display a dummy viewport (in your real app you would likely use ImageButton() to display a texture) local avail_size = ImGui.GetContentRegionAvail() local pos = ImGui.GetCursorScreenPos() ImGui.ColorButton("viewport", ImVec4(0.5, 0.2, 0.5, 1.0), bit32.bor(ImGuiColorEditFlags.NoTooltip, ImGuiColorEditFlags.NoDragDrop), avail_size) @@ -23237,10 +26552,12 @@ function ShowExampleAppConstrainedResize(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a simple static window with no decoration +-- + a context-menu to choose which corner of the screen to use. local OverlayLocation = 0 function ShowExampleAppSimpleOverlay(p_open) local io = ImGui.GetIO() @@ -23249,7 +26566,7 @@ function ShowExampleAppSimpleOverlay(p_open) if OverlayLocation >= 0 then local PAD = 10.0 local viewport = ImGui.GetMainViewport() - local work_pos, work_size = viewport.WorkPos, viewport.WorkSize + local work_pos, work_size = viewport.WorkPos, viewport.WorkSize -- Use work area to avoid menu-bar/task-bar, if any! local right, bottom = OverlayLocation % 2 == 1, OverlayLocation >= 2 local window_pos = ImVec2(right and (work_pos.x + work_size.x - PAD) or (work_pos.x + PAD), bottom and (work_pos.y + work_size.y - PAD) or (work_pos.y + PAD)) local window_pos_pivot = ImVec2(right and 1.0 or 0.0, bottom and 1.0 or 0.0) @@ -23257,10 +26574,11 @@ function ShowExampleAppSimpleOverlay(p_open) ImGui.SetNextWindowViewport(viewport.ID) window_flags = bit32.bor(window_flags, W.NoMove) elseif OverlayLocation == -2 then + -- Center window ImGui.SetNextWindowPos(ImGui.GetMainViewport():GetCenter(), ImGuiCond.Always, ImVec2(0.5, 0.5)) window_flags = bit32.bor(window_flags, W.NoMove) end - ImGui.SetNextWindowBgAlpha(0.35) + ImGui.SetNextWindowBgAlpha(0.35) -- Transparent background local visible p_open, visible = ImGui.Begin("Example: Simple overlay", p_open, window_flags) if visible then @@ -23282,12 +26600,15 @@ function ShowExampleAppSimpleOverlay(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a window covering the entire screen/viewport local FS = { use_work_area = true, flags = bit32.bor(ImGuiWindowFlags.NoDecoration, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoSavedSettings) } function ShowExampleAppFullscreen(p_open) + -- We demonstrate using the full viewport area or the work area (without menu-bars, task-bars etc.) + -- Based on your use case you may want one or the other. local viewport = ImGui.GetMainViewport() ImGui.SetNextWindowPos(FS.use_work_area and viewport.WorkPos or viewport.Pos) ImGui.SetNextWindowSize(FS.use_work_area and viewport.WorkSize or viewport.Size) @@ -23311,13 +26632,21 @@ function ShowExampleAppFullscreen(p_open) return p_open end ----------------------------------------------------------------- --- [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles() +------------------------------------------------------------------------------- +-- Demonstrate the use of "##" and "###" in identifiers to manipulate ID generation. +-- This applies to all regular items as well. +-- Read FAQ section "How can I have multiple widgets with the same label?" for details. function ShowExampleAppWindowTitles(p_open) local viewport = ImGui.GetMainViewport() local base_pos = viewport.Pos + + -- By default, Windows are uniquely identified by their title. + -- You can use the "##" and "###" markers to manipulate the display/ID. + + -- Using "##" to display same title but have unique identifier. ImGui.SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 100), ImGuiCond.FirstUseEver) ImGui.Begin("Same title as another window##1") ImGui.Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique.") @@ -23326,6 +26655,8 @@ function ShowExampleAppWindowTitles(p_open) ImGui.Begin("Same title as another window##2") ImGui.Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique.") ImGui.End() + + -- Using "###" to display a changing title but keep a static identifier "AnimatedTitle" local spin = "|/-\\" local k = math.floor(ImGui.GetTime() / 0.25) % 4 + 1 local buf = string.format("Animated title %s %d###AnimatedTitle", string.sub(spin, k, k), ImGui.GetFrameCount()) @@ -23336,9 +26667,14 @@ function ShowExampleAppWindowTitles(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() ----------------------------------------------------------------- +------------------------------------------------------------------------------- + +-- See our Wiki guides: +-- - ImDrawList Vector Rendering Reference: https://github.com/ocornut/imgui/wiki/Draw-List +-- - Pixel Perfect Anti-aliased Rendering: https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering +-- - How Anti-aliased Polyline Rendering is Implemented: https://github.com/ocornut/imgui/wiki/Polyline-Rendering local CRS = { sz = 42.0, base_rounding = 8.0, base_thickness = 3.0, animate_rounding = false, animate_thickness = false, ngon_segments = 6, circle_override = false, circle_override_v = 12, curve_override = false, curve_override_v = 8, @@ -23352,6 +26688,9 @@ local function CustomRenderingPrimitives() ImGui.PushItemFlag(ImGuiItemFlags.LiveEditOnInput, true) local draw_list = ImGui.GetWindowDrawList() + -- Draw gradients + -- (note that those are currently exacerbating our sRGB/Linear issues) + -- Calling ImGui.GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well.. ImGui.Text("Gradients") local gradient_size = ImVec2(ImGui.CalcItemWidth(), ImGui.GetFrameHeight()) ImGui.InvisibleButton("##gradient1", gradient_size) @@ -23361,11 +26700,12 @@ local function CustomRenderingPrimitives() col_a, col_b = ImGui.GetColorU32(IM_COL32(0, 255, 0, 255), nil, true), ImGui.GetColorU32(IM_COL32(255, 0, 0, 255), nil, true) draw_list:AddRectFilledMultiColor(ImGui.GetItemRectMin(), ImGui.GetItemRectMax(), col_a, col_b, col_b, col_a) + -- Draw a bunch of primitives ImGui.Text("All primitives") s.sz = ImGui.DragFloat("Size", s.sz, 0.2, 0.2, 100.0, "%.0f") local t = ImGui.GetTime() local rounding_wave = 1.0 - math.abs((t % 3.0) * (2.0 / 3.0) - 1.0) - local rounding = s.animate_rounding and (math.floor(rounding_wave * s.base_rounding * 10.0) / 10.0) or s.base_rounding + local rounding = s.animate_rounding and (math.floor(rounding_wave * s.base_rounding * 10.0) / 10.0) or s.base_rounding -- Sub-integer rounding works but has discontinuities in small values, so best disable we s.base_rounding = ImGui.DragFloat("Rounding", s.base_rounding, 0.02, 0.0, 32.0, "%.1f"); ImGui.SameLine() _, s.animate_rounding = ImGui.Checkbox("Animate##rounding", s.animate_rounding); ImGui.SameLine() ImGui.Text("%.2f", rounding) @@ -23398,9 +26738,9 @@ local function CustomRenderingPrimitives() local half_sz = sz * 0.5 local circle_segments = s.circle_override and s.circle_override_v or 0 local curve_segments = s.curve_override and s.curve_override_v or 0 - local cp3 = { ImVec2(0.0, sz * 0.6), ImVec2(sz * 0.5, -sz * 0.4), ImVec2(sz, sz) } + local cp3 = { ImVec2(0.0, sz * 0.6), ImVec2(sz * 0.5, -sz * 0.4), ImVec2(sz, sz) } -- Control points for curves local cp4 = { ImVec2(0.0, 0.0), ImVec2(sz * 1.3, sz * 0.3), ImVec2(sz - sz * 1.3, sz - sz * 0.3), ImVec2(sz, sz) } - local concave_shape = { { 0.0, 0.0 }, { 0.3, 0.0 }, { 0.3, 0.7 }, { 0.7, 0.7 }, { 0.7, 0.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 0.0, 1.0 } } + local concave_shape = { { 0.0, 0.0 }, { 0.3, 0.0 }, { 0.3, 0.7 }, { 0.7, 0.7 }, { 0.7, 0.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 0.0, 1.0 } } -- |_| looking shape. Normalized. local zigzag_shape = { { 0.0, 0.0 }, { 0.9, 0.0 }, { 1.0, 0.1 }, { 1.0, 0.9 }, { 0.9, 1.0 }, { 0.3, 1.0 }, { 0.3, 0.4 }, { 0.9, 0.4 } } local rotating_square = {} for side = 0, 3 do @@ -23417,17 +26757,25 @@ local function CustomRenderingPrimitives() local draw_fill = (row == 2 or row == 3) local draw_strokes = (row == 0 or row == 1 or row == 3) if draw_fill then + -- FILLED SHAPES local col = ImGui.ColorConvertFloat4ToU32(s.colf_fill) - draw_list:AddNgonFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments); x = x + step - draw_list:AddCircleFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments); x = x + step - draw_list:AddEllipseFilled(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments); x = x + step - draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x = x + step - draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding); x = x + step - draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br); x = x + step - draw_list:AddTriangleFilled(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col); x = x + step - draw_list:AddTriangleFilled(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col); x = x + step - math.floor(sz * 0.6) + draw_list:AddNgonFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments); x = x + step -- N-gon + draw_list:AddCircleFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments); x = x + step -- Circle + draw_list:AddEllipseFilled(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments); x = x + step -- Ellipse + draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x = x + step -- Square + draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding); x = x + step -- Square with all rounded corners + draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br); x = x + step -- Square with two rounded corners + draw_list:AddTriangleFilled(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col); x = x + step -- Triangle + draw_list:AddTriangleFilled(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col); x = x + step - math.floor(sz * 0.6) -- Thin triangle + + -- Concave shape: U Shape(concave_shape, x, y); draw_list:PathFillConcave(col); x = x + step + + -- Concave shape: Zig-Zag with sharp angles Shape(zigzag_shape, x, y); draw_list:PathFillConcave(col); x = x + step + + -- Horizontal/Vertical lines + -- (here for consistency with the strokes section. AddRectFilled() is roughly close to AddLineH(), AddLineV() draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x = x + step draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x = x + step - math.floor(half_sz) if not (draw_fill and draw_strokes) then @@ -23439,10 +26787,16 @@ local function CustomRenderingPrimitives() end end x = x + step - math.floor(half_sz) + + -- Rotating square for n = 1, 4 do draw_list:PathLineTo(ImVec2(x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y)) end draw_list:PathFillConvex(col); x = x + step + + -- Path draw_list:PathArcTo(ImVec2(x + half_sz, y + half_sz), half_sz, pi * -0.5, pi * 1.1) draw_list:PathFillConvex(col); x = x + step + + -- Quadratic Bezier Curve (3 control points) draw_list:PathLineTo(ImVec2(x + cp3[1].x, y + cp3[1].y)) draw_list:PathBezierQuadraticCurveTo(ImVec2(x + cp3[2].x, y + cp3[2].y), ImVec2(x + cp3[3].x, y + cp3[3].y), curve_segments) draw_list:PathFillConvex(col); x = x + step @@ -23453,18 +26807,26 @@ local function CustomRenderingPrimitives() end if draw_fill and draw_strokes then x = start_pos.x end if draw_strokes then + -- STROKES + -- First row uses a thickness of 1.0f, second row uses the configurable thickness local col = ImGui.ColorConvertFloat4ToU32(s.colf_stroke) local th = (row == 0) and 1.0 or thickness - draw_list:AddNgon(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments, th); x = x + step - draw_list:AddCircle(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments, th); x = x + step - draw_list:AddEllipse(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments, th); x = x + step - draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0, th); x = x + step - draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th); x = x + step - draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, corners_tl_br); x = x + step - draw_list:AddTriangle(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col, th); x = x + step - draw_list:AddTriangle(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col, th); x = x + step - math.floor(sz * 0.6) + draw_list:AddNgon(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments, th); x = x + step -- N-gon + draw_list:AddCircle(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments, th); x = x + step -- Circle + draw_list:AddEllipse(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments, th); x = x + step -- Ellipse + draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0, th); x = x + step -- Square + draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th); x = x + step -- Square with all rounded corners + draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, corners_tl_br); x = x + step -- Square with two rounded corners + draw_list:AddTriangle(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col, th); x = x + step -- Triangle + draw_list:AddTriangle(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col, th); x = x + step - math.floor(sz * 0.6) -- Thin triangle + + -- Concave shape: U Shape(concave_shape, x, y); draw_list:PathStroke(col, th, ImDrawFlags.Closed); x = x + step + + -- Concave shape: Zig-Zag with sharp angles Shape(zigzag_shape, x, y); draw_list:PathStroke(col, th, ImDrawFlags.Closed); x = x + step + + -- Horizontal/Vertical/Diagonal lines local off = math.floor(sz * 0.4) draw_list:AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th) draw_list:AddLine(ImVec2(x, y + off), ImVec2(x + sz, y + off), col, th); x = x + step @@ -23475,11 +26837,19 @@ local function CustomRenderingPrimitives() draw_list:AddLine(ImVec2(x, y + sz), ImVec2(x + half_sz, y), col, th) end x = x + step - math.floor(half_sz) + + -- Rotating square for n = 1, 4 do draw_list:PathLineTo(ImVec2(x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y)) end draw_list:PathStroke(col, th, ImDrawFlags.Closed); x = x + step + + -- Path draw_list:PathArcTo(ImVec2(x + half_sz, y + half_sz), half_sz, pi * -0.5, pi * 1.1) draw_list:PathStroke(col, th); x = x + step + + -- Quadratic Bezier Curve (3 control points) draw_list:AddBezierQuadratic(ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), ImVec2(x + cp3[3].x, y + cp3[3].y), col, th, curve_segments); x = x + step + + -- Cubic Bezier Curve (4 control points) if not (draw_fill and draw_strokes) then draw_list:AddBezierCubic(ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), ImVec2(x + cp4[4].x, y + cp4[4].y), col, th, curve_segments) x = x + step @@ -23499,22 +26869,40 @@ local function CustomRenderingCanvas() _, s.opt_enable_grid = ImGui.Checkbox("Enable grid", s.opt_enable_grid) _, s.opt_enable_context_menu = ImGui.Checkbox("Enable context menu", s.opt_enable_context_menu) ImGui.Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu.") - local canvas_p0 = ImGui.GetCursorScreenPos() - local canvas_sz = ImGui.GetContentRegionAvail() + + -- Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling. + -- Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls. + -- To use a child window instead we could use, e.g: + -- ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0, 0)) -- Disable padding + -- ImGui.PushStyleColor(ImGuiCol.ChildBg, IM_COL32(50, 50, 50, 255)) -- Set a background color + -- ImGui.BeginChild("canvas", ImVec2(0.0, 0.0), ImGuiChildFlags.Borders, ImGuiWindowFlags.NoMove) + -- ImGui.PopStyleColor() + -- ImGui.PopStyleVar() + -- [...] + -- ImGui.EndChild() + + -- Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive() + local canvas_p0 = ImGui.GetCursorScreenPos() -- ImDrawList API uses screen coordinates! + local canvas_sz = ImGui.GetContentRegionAvail() -- Resize canvas to what's available if canvas_sz.x < 50.0 then canvas_sz.x = 50.0 end if canvas_sz.y < 50.0 then canvas_sz.y = 50.0 end local canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y) + + -- Draw border and background color local io = ImGui.GetIO() local draw_list = ImGui.GetWindowDrawList() draw_list:AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255)) draw_list:AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255)) + -- This will catch our interactions ImGui.InvisibleButton("canvas", canvas_sz, bit32.bor(ImGuiButtonFlags.MouseButtonLeft, ImGuiButtonFlags.MouseButtonRight)) - local is_hovered = ImGui.IsItemHovered() - local is_active = ImGui.IsItemActive() - local origin = ImVec2(canvas_p0.x + s.scrolling.x, canvas_p0.y + s.scrolling.y) + local is_hovered = ImGui.IsItemHovered() -- Hovered + local is_active = ImGui.IsItemActive() -- Held + local origin = ImVec2(canvas_p0.x + s.scrolling.x, canvas_p0.y + s.scrolling.y) -- Lock scrolled origin local mouse_pos_in_canvas = ImVec2(io.MousePos.x - origin.x, io.MousePos.y - origin.y) local points = s.points + + -- Add first and second point if is_hovered and not s.adding_line and ImGui.IsMouseClicked(ImGuiMouseButton.Left) then points[#points + 1] = ImVec2(mouse_pos_in_canvas.x, mouse_pos_in_canvas.y) points[#points + 1] = ImVec2(mouse_pos_in_canvas.x, mouse_pos_in_canvas.y) @@ -23524,11 +26912,16 @@ local function CustomRenderingCanvas() points[#points] = ImVec2(mouse_pos_in_canvas.x, mouse_pos_in_canvas.y) if not ImGui.IsMouseDown(ImGuiMouseButton.Left) then s.adding_line = false end end + + -- Pan (we use a zero mouse threshold when there's no context menu) + -- You may decide to make that threshold dynamic based on whether the mouse is hovering something etc. local mouse_threshold_for_pan = s.opt_enable_context_menu and -1.0 or 0.0 if is_active and ImGui.IsMouseDragging(ImGuiMouseButton.Right, mouse_threshold_for_pan) then s.scrolling.x = s.scrolling.x + io.MouseDelta.x s.scrolling.y = s.scrolling.y + io.MouseDelta.y end + + -- Context menu (under default mouse threshold) local drag_delta = ImGui.GetMouseDragDelta(ImGuiMouseButton.Right) if s.opt_enable_context_menu and drag_delta.x == 0.0 and drag_delta.y == 0.0 then ImGui.OpenPopupOnItemClick("context", ImGuiPopupFlags.MouseButtonRight) @@ -23540,6 +26933,8 @@ local function CustomRenderingCanvas() if ImGui.MenuItem("Remove all", nil, false, #points > 0) then table.clear(points) end ImGui.EndPopup() end + + -- Draw grid + all lines in the canvas draw_list:PushClipRect(canvas_p0, canvas_p1, true) if s.opt_enable_grid then local GRID_STEP = 64.0 @@ -23554,6 +26949,7 @@ local function CustomRenderingCanvas() draw_list:PopClipRect() end +-- Demonstrate using the low-level ImDrawList to draw custom shapes. function ShowExampleAppCustomRendering(p_open) local visible p_open, visible = ImGui.Begin("Example: Custom rendering", p_open) @@ -23573,23 +26969,33 @@ function ShowExampleAppCustomRendering(p_open) if s.draw_fg then ImGui.GetForegroundDrawList():AddCircle(window_center, window_size.y * 0.6, IM_COL32(0, 255, 0, 200), 0, 10) end ImGui.EndTabItem() end + + -- Demonstrate out-of-order rendering via channels splitting + -- We use functions in ImDrawList as each draw list contains a convenience splitter, + -- but you can also instantiate your own ImDrawListSplitter if you need to nest them. if ImGui.BeginTabItem("Draw Channels") then local draw_list = ImGui.GetWindowDrawList() ImGui.Text("Blue shape is drawn first: appears in back") ImGui.Text("Red shape is drawn after: appears in front") local p0 = ImGui.GetCursorScreenPos() - draw_list:AddRectFilled(ImVec2(p0.x, p0.y), ImVec2(p0.x + 50, p0.y + 50), IM_COL32(0, 0, 255, 255)) - draw_list:AddRectFilled(ImVec2(p0.x + 25, p0.y + 25), ImVec2(p0.x + 75, p0.y + 75), IM_COL32(255, 0, 0, 255)) + draw_list:AddRectFilled(ImVec2(p0.x, p0.y), ImVec2(p0.x + 50, p0.y + 50), IM_COL32(0, 0, 255, 255)) -- Blue + draw_list:AddRectFilled(ImVec2(p0.x + 25, p0.y + 25), ImVec2(p0.x + 75, p0.y + 75), IM_COL32(255, 0, 0, 255)) -- Red ImGui.Dummy(ImVec2(75, 75)) ImGui.Separator() ImGui.Text("Blue shape is drawn first, into channel 1: appears in front") ImGui.Text("Red shape is drawn after, into channel 0: appears in back") local p1 = ImGui.GetCursorScreenPos() + + -- Create 2 channels and draw a Blue shape THEN a Red shape. + -- You can create any number of channels. Tables API use 1 channel per column in order to better batch draw calls. draw_list:ChannelsSplit(2) draw_list:ChannelsSetCurrent(1) - draw_list:AddRectFilled(ImVec2(p1.x, p1.y), ImVec2(p1.x + 50, p1.y + 50), IM_COL32(0, 0, 255, 255)) + draw_list:AddRectFilled(ImVec2(p1.x, p1.y), ImVec2(p1.x + 50, p1.y + 50), IM_COL32(0, 0, 255, 255)) -- Blue draw_list:ChannelsSetCurrent(0) - draw_list:AddRectFilled(ImVec2(p1.x + 25, p1.y + 25), ImVec2(p1.x + 75, p1.y + 75), IM_COL32(255, 0, 0, 255)) + draw_list:AddRectFilled(ImVec2(p1.x + 25, p1.y + 25), ImVec2(p1.x + 75, p1.y + 75), IM_COL32(255, 0, 0, 255)) -- Red + + -- Flatten/reorder channels. Red shape is in channel 0 and it appears below the Blue shape in channel 1. + -- This works by copying draw indices only (vertices are not copied). draw_list:ChannelsMerge() ImGui.Dummy(ImVec2(75, 75)) ImGui.Text("After reordering, contents of channel 0 appears below channel 1.") @@ -23601,17 +27007,35 @@ function ShowExampleAppCustomRendering(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- KeepWindowPadding: Keep WindowPadding to help understand that DockSpace() is a widget inside the window. local DSA = { IsFullscreen = true, KeepWindowPadding = false, DockSpaceFlags = 0, opt_demo_mode = 0, opt_demo_mode_changed = false } +-- THIS IS A DEMO FOR ADVANCED USAGE OF DockSpace(). +-- MOST REGULAR APPLICATIONS WANTING TO ALLOW DOCKING WINDOWS ON THE EDGE OF YOUR SCREEN CAN SIMPLY USE: +-- ImGui.NewFrame() + ImGui.DockSpaceOverViewport() -- Create a dockspace in main viewport +-- OR: +-- ImGui.NewFrame() + ImGui.DockSpaceOverViewport(0, nil, ImGuiDockNodeFlags.PassthruCentralNode) -- Create a dockspace in main viewport, where central node is transparent. +-- Demonstrate using DockSpace() to create an explicit docking node within an existing window, with various options. +-- Read https://github.com/ocornut/imgui/wiki/Docking for details. +-- The reasons we do not use DockSpaceOverViewport() in this demo is because: +-- - (1) we allow the host window to be floating/moveable instead of filling the viewport (when args.IsFullscreen == false) +-- which is mostly to showcase the idea that DockSpace() may be submitted anywhere. +-- Also see 'Demo->Examples->Documents' for a less abstract version of this. +-- - (2) we allow the host window to have padding (when args.UsePadding == true) +-- - (3) we expose variety of other flags. local function ShowExampleAppDockSpaceAdvanced(args, p_open) local dockspace_flags = args.DockSpaceFlags + + -- We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, + -- because it would be confusing to have two docking targets within each others. local W = ImGuiWindowFlags local window_flags = W.NoDocking if args.IsFullscreen then + -- Fullscreen dockspace: practically the same as calling DockSpaceOverViewport() local viewport = ImGui.GetMainViewport() ImGui.SetNextWindowPos(viewport.WorkPos) ImGui.SetNextWindowSize(viewport.WorkSize) @@ -23620,12 +27044,24 @@ local function ShowExampleAppDockSpaceAdvanced(args, p_open) ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0.0) window_flags = bit32.bor(window_flags, W.NoTitleBar, W.NoCollapse, W.NoResize, W.NoMove, W.NoBringToFrontOnFocus, W.NoNavFocus, W.NoBackground) else + -- Floating dockspace dockspace_flags = bit32.band(dockspace_flags, bit32.bnot(ImGuiDockNodeFlags.PassthruCentralNode)) end + + -- Important: note that we proceed even if Begin() returns false (aka window is collapsed). + -- This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, + -- all active windows docked into it will lose their parent and become undocked. + -- We cannot preserve the docking relationship between an active window and an inactive docking, otherwise + -- any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. if not args.KeepWindowPadding then ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0.0, 0.0)) end p_open = ImGui.Begin("Window with a DockSpace", p_open, window_flags) if not args.KeepWindowPadding then ImGui.PopStyleVar() end + if args.IsFullscreen then ImGui.PopStyleVar(2) end + + -- Submit the DockSpace widget inside our window + -- - Note that the id here is different from the one used by DockSpaceOverViewport(), so docking state won't get transfered between "Basic" and "Advanced" demos. + -- - If we made the ShowExampleAppDockSpaceBasic() calculate its own ID and pass it to DockSpaceOverViewport() the ID could easily match. local dockspace_id = ImGui.GetID("MyDockSpace") ImGui.DockSpace(dockspace_id, ImVec2(0.0, 0.0), dockspace_flags) ImGui.End() @@ -23635,10 +27071,20 @@ end function ShowExampleAppDockSpace(p_open) local args = DSA if args.opt_demo_mode == 0 then + -- Basic version which you can use in many apps: + -- e.g: + -- ImGui.DockSpaceOverViewport() + -- or: + -- ImGui.DockSpaceOverViewport(0, nil, ImGuiDockNodeFlags.PassthruCentralNode) -- Central node will be transparent + -- or: + -- local viewport = ImGui.GetMainViewport() + -- ImGui.DockSpaceOverViewport(0, viewport, ImGuiDockNodeFlags.None) ImGui.DockSpaceOverViewport(0, nil, args.DockSpaceFlags) else p_open = ShowExampleAppDockSpaceAdvanced(args, p_open) end + + -- Refocus our window to minimize perceived loss of focus when changing mode (caused by the fact that each use a different window, which would not happen in a real app) if args.opt_demo_mode_changed then ImGui.SetNextWindowFocus() end p_open = ImGui.Begin("Examples: Dockspace", p_open, ImGuiWindowFlags.MenuBar) local c1, c2 @@ -23650,7 +27096,7 @@ function ShowExampleAppDockSpace(p_open) if bit32.band(ImGui.GetIO().ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then ShowDockingDisabledMessage() elseif args.opt_demo_mode == 0 then - args.DockSpaceFlags = bit32.band(args.DockSpaceFlags, D.PassthruCentralNode) + args.DockSpaceFlags = bit32.band(args.DockSpaceFlags, D.PassthruCentralNode) -- Allowed flags _, args.DockSpaceFlags = ImGui.CheckboxFlags("Flag: PassthruCentralNode", args.DockSpaceFlags, D.PassthruCentralNode) else _, args.IsFullscreen = ImGui.Checkbox("Fullscreen", args.IsFullscreen) @@ -23664,6 +27110,8 @@ function ShowExampleAppDockSpace(p_open) if D[n] then _, args.DockSpaceFlags = ImGui.CheckboxFlags("Flag: " .. n, args.DockSpaceFlags, D[n]) end end end + + -- Show demo options and help if ImGui.BeginMenuBar() then if ImGui.BeginMenu("Help") then ImGui.TextUnformatted("This demonstrates the use of ImGui::DockSpace() which allows you to manually\ncreate a docking node _within_ another window.\nThe \"Basic\" version uses the ImGui::DockSpaceOverViewport() helper. Most applications can probably use this.") @@ -23680,10 +27128,17 @@ function ShowExampleAppDockSpace(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Simplified structure to mimic a Document model +-- NameBuf: Document title +-- UID: Unique ID (necessary as we can change title) +-- Open: Set when open (we keep an array of all available documents to simplify demo code!) +-- OpenPrev: Copy of Open from last update. +-- Dirty: Set when the document has been modified +-- Color: An arbitrary variable associated to the document local function MyDocument(uid, name, open, color) if open == nil then open = true end local d = { UID = uid, NameBuf = Buf(name, 32), Open = open, OpenPrev = open, Dirty = false, Color = color or ImVec4(1.0, 1.0, 1.0, 1.0) } @@ -23709,13 +27164,16 @@ local function DocsInit() for _, d in ipairs(self.CloseQueue) do if d == doc then return end end self.CloseQueue[#self.CloseQueue + 1] = doc end + -- As we allow to change document name, we append a never-changing document ID so tabs are stable function app:GetTabName(doc) return string.format("%s###doc%d", doc:Name(), doc.UID) end + -- Display placeholder contents for the Document function app:DisplayDocContents(doc) ImGui.PushID("doc" .. doc.UID) ImGui.Text("Document \"%s\"", doc:Name()) ImGui.PushStyleColor(ImGuiCol.Text, doc.Color) ImGui.TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.") ImGui.PopStyleColor() + ImGui.SetNextItemShortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.R), ImGuiInputFlags.Tooltip) if ImGui.Button("Rename..") then self.RenamingDoc = doc; self.RenamingStarted = true end ImGui.SameLine() @@ -23727,9 +27185,10 @@ local function DocsInit() ImGui.SameLine() ImGui.SetNextItemShortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.W), ImGuiInputFlags.Tooltip) if ImGui.Button("Close") then self:QueueClose(doc) end - ImGui.ColorEdit3("color", doc.Color) + ImGui.ColorEdit3("color", doc.Color) -- Useful to test drag and drop and hold-dragged-to-open-tab behavior. ImGui.PopID() end + -- Display context menu for the Document function app:DisplayDocContextMenu(doc) if not ImGui.BeginPopupContextItem() then return end if ImGui.MenuItem("Save " .. doc:Name(), "Ctrl+S", false, doc.Open) then doc:DoSave() end @@ -23737,6 +27196,14 @@ local function DocsInit() if ImGui.MenuItem("Close", "Ctrl+W", false, doc.Open) then self:QueueClose(doc) end ImGui.EndPopup() end + -- [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface. + -- If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, + -- as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for + -- the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has + -- disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively + -- give the impression of a flicker for one frame. + -- We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch. + -- Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags.Reorderable flag. function app:NotifyOfDocumentsClosedElsewhere() for _, doc in ipairs(self.Documents) do if not doc.Open and doc.OpenPrev then ImGui.SetTabItemClosed(doc:Name()) end @@ -23749,7 +27216,18 @@ end function ShowExampleAppDocuments(p_open) Docs = Docs or DocsInit() local app = Docs + -- Options + -- Target_Tab: Create documents as local tab into a local tab bar + -- Target_DockSpaceAndWindow: Create documents as regular windows, and create an embedded dockspace local Target_Tab, Target_DockSpaceAndWindow = 1, 2 + + -- When (opt_target == Target_DockSpaceAndWindow) there is the possibily that one of our child Document window (e.g. "Eggplant") + -- that we emit gets docked into the same spot as the parent window ("Example: Documents"). + -- This would create a problematic feedback loop because selecting the "Eggplant" tab would make the "Example: Documents" tab + -- not visible, which in turn would stop submitting the "Eggplant" window. + -- We avoid this problem by submitting our documents window even if our parent window is not currently visible. + -- Another solution may be to make the "Example: Documents" window use the ImGuiWindowFlags.NoDocking. + local window_contents_visible p_open, window_contents_visible = ImGui.Begin("Example: Documents", p_open, ImGuiWindowFlags.MenuBar) if not window_contents_visible and app.opt_target ~= Target_DockSpaceAndWindow then @@ -23757,6 +27235,7 @@ function ShowExampleAppDocuments(p_open) return p_open end + -- Menu if ImGui.BeginMenuBar() then if ImGui.BeginMenu("File") then local open_count = 0 @@ -23776,6 +27255,7 @@ function ShowExampleAppDocuments(p_open) ImGui.EndMenuBar() end + -- [Debug] List documents with one checkbox for each for doc_n, doc in ipairs(app.Documents) do if doc_n > 1 then ImGui.SameLine() end ImGui.PushID("doc" .. doc.UID) @@ -23792,15 +27272,31 @@ function ShowExampleAppDocuments(p_open) if app.opt_target == Target_DockSpaceAndWindow then ImGui.SameLine(); redock_all = ImGui.Button("Redock all") end ImGui.Separator() + -- About the ImGuiWindowFlags.UnsavedDocument / ImGuiTabItemFlags.UnsavedDocument flags. + -- They have multiple effects: + -- - Display a dot next to the title. + -- - Tab is selected when clicking the X close button. + -- - Closure is not assumed (will wait for user to stop submitting the tab). + -- Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + -- We need to assume closure by default otherwise waiting for "lack of submission" on the next frame would leave an empty + -- hole for one-frame, both in the tab-bar and in tab-contents when closing a tab/window. + -- The rarely used SetTabItemClosed() function is a way to notify of programmatic closure to avoid the one-frame hole. + + -- Tabs if app.opt_target == Target_Tab then local tab_bar_flags = bit32.bor(app.opt_fitting_flags, app.opt_reorderable and ImGuiTabBarFlags.Reorderable or 0, ImGuiTabBarFlags.DrawSelectedOverline) if ImGui.BeginTabBar("##tabs", tab_bar_flags) then if app.opt_reorderable then app:NotifyOfDocumentsClosedElsewhere() end + + -- Submit Tabs for _, doc in ipairs(app.Documents) do if doc.Open then + -- As we allow to change document name, we append a never-changing document id so tabs are stable local tab_flags = doc.Dirty and ImGuiTabItemFlags.UnsavedDocument or 0 local visible visible, doc.Open = ImGui.BeginTabItem(app:GetTabName(doc), doc.Open, tab_flags) + + -- Cancel attempt to close when unsaved add to save queue so we can display a popup. if not doc.Open and doc.Dirty then doc.Open = true app:QueueClose(doc) @@ -23817,14 +27313,20 @@ function ShowExampleAppDocuments(p_open) elseif app.opt_target == Target_DockSpaceAndWindow then if bit32.band(ImGui.GetIO().ConfigFlags, ImGuiConfigFlags.DockingEnable) ~= 0 then app:NotifyOfDocumentsClosedElsewhere() + + -- Create a DockSpace node where any window can be docked local dockspace_id = ImGui.GetID("MyDockSpace") ImGui.DockSpace(dockspace_id) + + -- Create Windows for _, doc in ipairs(app.Documents) do if doc.Open then ImGui.SetNextWindowDockID(dockspace_id, redock_all and ImGuiCond.Always or ImGuiCond.FirstUseEver) local window_flags = doc.Dirty and ImGuiWindowFlags.UnsavedDocument or 0 local visible doc.Open, visible = ImGui.Begin(doc:Name(), doc.Open, window_flags) + + -- Cancel attempt to close when unsaved add to save queue so we can display a popup. if not doc.Open and doc.Dirty then doc.Open = true app:QueueClose(doc) @@ -23839,11 +27341,13 @@ function ShowExampleAppDocuments(p_open) end end + -- Early out other contents if not window_contents_visible then ImGui.End() return p_open end + -- Display renaming UI if app.RenamingDoc ~= nil then if app.RenamingStarted then ImGui.OpenPopup("Rename") end if ImGui.BeginPopup("Rename") then @@ -23860,10 +27364,12 @@ function ShowExampleAppDocuments(p_open) app.RenamingStarted = false end + -- Display closing confirmation UI if #app.CloseQueue > 0 then local close_queue_unsaved_documents = 0 for _, doc in ipairs(app.CloseQueue) do if doc.Dirty then close_queue_unsaved_documents = close_queue_unsaved_documents + 1 end end if close_queue_unsaved_documents == 0 then + -- Close documents when all are unsaved for _, doc in ipairs(app.CloseQueue) do doc:DoForceClose() end app.CloseQueue = {} else @@ -23916,6 +27422,10 @@ local ExampleNames = { "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" } +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsBasic() +------------------------------------------------------------------------------- + S.basic = { clicked = 0, check = true, e = 0, counter = 0, str0 = Buf("Hello, world!", 128), str1 = Buf("", 128), i0 = 123, f0 = 0.001, d0 = 999999.00000001, f1 = 1.e10, vec4a = { 0.10, 0.20, 0.30, 0.44 }, di1 = 50, di2 = 42, di3 = 128, df1 = 1.0, df2 = 0.0067, si1 = 0, sf1 = 0.123, sf2 = 0.0, angle = 0.0, elem = 0, @@ -23933,6 +27443,8 @@ function DemoWindowWidgetsBasic() _, s.e = ImGui.RadioButton("radio c", s.e, 2) ImGui.AlignTextToFramePadding() ImGui.TextLinkOpenURL("Hyperlink", "https://github.com/ocornut/imgui/wiki/Error-Handling") + + -- Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. for i = 0, 6 do if i > 0 then ImGui.SameLine() end ImGui.PushID(i) @@ -23943,9 +27455,15 @@ function DemoWindowWidgetsBasic() ImGui.PopStyleColor(3) ImGui.PopID() end + + -- Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements + -- (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!) + -- See 'Demo->Layout->Text Baseline Alignment' for details. ImGui.AlignTextToFramePadding() ImGui.Text("Hold to repeat:") ImGui.SameLine() + + -- Arrow buttons with Repeater local spacing = ImGui.GetStyle().ItemInnerSpacing.x ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true) if ImGui.ArrowButton("##left", ImGuiDir.Left) then s.counter = s.counter - 1 end @@ -23976,6 +27494,7 @@ function DemoWindowWidgetsBasic() s.di3 = ImGui.DragInt("drag int wrap 100..200", s.di3, 1, 100, 200, "%d", ImGuiSliderFlags.WrapAround) s.df1 = ImGui.DragFloat("drag float", s.df1, 0.005) s.df2 = ImGui.DragFloat("drag small float", s.df2, 0.0001, 0.0, 0.0, "%.06f ns") + -- ImGui.DragFloat("drag wrap -1..1", f3, 0.005, -1.0, 1.0, nil, ImGuiSliderFlags.WrapAround) ImGui.SeparatorText("Sliders") s.si1 = ImGui.SliderInt("slider int", s.si1, -1, 3) @@ -23983,23 +27502,38 @@ function DemoWindowWidgetsBasic() s.sf1 = ImGui.SliderFloat("slider float", s.sf1, 0.0, 1.0, "ratio = %.3f") s.sf2 = ImGui.SliderFloat("slider float (log)", s.sf2, -10.0, 10.0, "%.4f", ImGuiSliderFlags.Logarithmic) s.angle = ImGui.SliderAngle("slider angle", s.angle) + + -- Using the format string to display a name instead of an integer. + -- Here we completely omit '%d' from the format string, so it'll only display a name. + -- This technique can also be used with DragInt(). local elems_names = { "Fire", "Earth", "Air", "Water" } local elem_name = elems_names[s.elem + 1] or "Unknown" - s.elem = ImGui.SliderInt("slider enum", s.elem, 0, 3, elem_name) + s.elem = ImGui.SliderInt("slider enum", s.elem, 0, 3, elem_name) -- Use ImGuiSliderFlags.NoInput flag to disable Ctrl+Click here. ImGui.SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer.") ImGui.SeparatorText("Selectors/Pickers") ImGui.ColorEdit3("color 1", s.col1) ImGui.SameLine(); HelpMarker("Click on the color square to open a color picker.\nClick and hold to use drag and drop.\nRight-Click on the color square to show options.\nCtrl+Click on individual component to input value.\n") ImGui.ColorEdit4("color 2", s.col2) + + -- Using the _simplified_ one-liner Combo() api here + -- See "Combo" section for examples of how to use the more flexible BeginCombo()/EndCombo() api. s.combo = ImGui.Combo("combo", s.combo, { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }) ImGui.SameLine(); HelpMarker("Using the simplified one-liner Combo API here.") + + -- Using the _simplified_ one-liner ListBox() api here + -- See "List boxes" section for examples of how to use the more flexible BeginListBox()/EndListBox() api. s.listbox = ImGui.ListBox("listbox", s.listbox, { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }, 9, 4) ImGui.SameLine(); HelpMarker("Using the simplified one-liner ListBox API here.") ImGui.TreePop() end S.chdr = { closable_group = true } + +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsBullets() +------------------------------------------------------------------------------- + function DemoWindowWidgetsBullets() if not ImGui.TreeNode("Bullets") then return end ImGui.BulletText("Bullet point 1") @@ -24010,6 +27544,10 @@ function DemoWindowWidgetsBullets() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsCollapsingHeaders() +------------------------------------------------------------------------------- + function DemoWindowWidgetsCollapsingHeaders() if not ImGui.TreeNode("Collapsing Headers") then return end local s = S.chdr @@ -24024,9 +27562,16 @@ function DemoWindowWidgetsCollapsingHeaders() ImGui.Text("IsItemHovered: %d", ImGui.IsItemHovered() and 1 or 0) for i = 0, 4 do ImGui.Text("More content %d", i) end end + -- if ImGui.CollapsingHeader("Header with a bullet", ImGuiTreeNodeFlags.Bullet) then + -- ImGui.Text("IsItemHovered: %d", ImGui.IsItemHovered()) + -- end ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsColorAndPickers() +------------------------------------------------------------------------------- + IMGUI_PAYLOAD_TYPE_COLOR_3F = IMGUI_PAYLOAD_TYPE_COLOR_3F or "_COL3F" IMGUI_PAYLOAD_TYPE_COLOR_4F = IMGUI_PAYLOAD_TYPE_COLOR_4F or "_COL4F" @@ -24064,9 +27609,11 @@ function DemoWindowWidgetsColorAndPickers() ImGui.ColorEdit4("MyColor##3", color, bit32.bor(CE.NoInputs, CE.NoLabel, base_flags)) ImGui.Text("Color button with Custom Picker Popup:") + + -- Generate a default palette. The palette will persist and can be edited. if s.palette == nil then s.palette = {} - for n = 0, 31 do s.palette[n] = HSV(n / 31.0, 0.8, 0.8, 1.0) end + for n = 0, 31 do s.palette[n] = HSV(n / 31.0, 0.8, 0.8, 1.0) end -- Alpha = 1.0 end local open_popup = ImGui.ColorButton("MyColor##3b", color, base_flags) ImGui.SameLine(0, ImGui.GetStyle().ItemInnerSpacing.x) @@ -24080,7 +27627,7 @@ function DemoWindowWidgetsColorAndPickers() ImGui.Separator() ImGui.ColorPicker4("##picker", color, bit32.bor(base_flags, CE.NoSidePreview, CE.NoSmallPreview)) ImGui.SameLine() - ImGui.BeginGroup() + ImGui.BeginGroup() -- Lock X position ImGui.Text("Current") ImGui.ColorButton("##current", color, bit32.bor(CE.NoPicker, CE.AlphaPreviewHalf), ImVec2(60, 40)) ImGui.Text("Previous") @@ -24096,6 +27643,9 @@ function DemoWindowWidgetsColorAndPickers() if ImGui.ColorButton("##palette", pal, bit32.bor(CE.NoAlpha, CE.NoPicker, CE.NoTooltip), ImVec2(20, 20)) then color.x = pal.x; color.y = pal.y; color.z = pal.z -- Preserve alpha! end + + -- Allow user to drop colors into each palette entry. Note that ColorButton() is already a + -- drag source by default, unless specifying the ImGuiColorEditFlags.NoDragDrop flag. if ImGui.BeginDragDropTarget() then local payload = ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F) if payload and payload.Data then pal.x, pal.y, pal.z = payload.Data[1], payload.Data[2], payload.Data[3] end @@ -24134,8 +27684,8 @@ function DemoWindowWidgetsColorAndPickers() local flags = bit32.bor(base_flags, s.picker_flags) if s.picker_mode == 1 then flags = bit32.bor(flags, CE.PickerHueBar) end if s.picker_mode == 2 then flags = bit32.bor(flags, CE.PickerHueWheel) end - if s.display_mode == 1 then flags = bit32.bor(flags, CE.NoInputs) end - if s.display_mode == 2 then flags = bit32.bor(flags, CE.DisplayRGB) end + if s.display_mode == 1 then flags = bit32.bor(flags, CE.NoInputs) end -- Disable all RGB/HSV/Hex displays + if s.display_mode == 2 then flags = bit32.bor(flags, CE.DisplayRGB) end -- Override display mode if s.display_mode == 3 then flags = bit32.bor(flags, CE.DisplayHSV) end if s.display_mode == 4 then flags = bit32.bor(flags, CE.DisplayHex) end ImGui.ColorPicker4("MyColor##4", color, flags, s.ref_color and s.ref_color_v or nil) @@ -24149,6 +27699,8 @@ function DemoWindowWidgetsColorAndPickers() ImGui.GetIO().ConfigColorEditFlags = bit32.bor(CE.Float, CE.HDR, CE.PickerHueWheel, CE.DisplayRGB, CE.InputRGB) end + -- Always display a small version of both types of pickers + -- (that's in order to make it more visible in the demo to people who are skimming quickly through it) ImGui.Text("Both types:") local w = (ImGui.GetContentRegionAvail().x - ImGui.GetStyle().ItemSpacing.y) * 0.40 ImGui.SetNextItemWidth(w) @@ -24158,6 +27710,8 @@ function DemoWindowWidgetsColorAndPickers() ImGui.ColorPicker3("##MyColor##6", color, bit32.bor(CE.PickerHueWheel, CE.NoSidePreview, CE.NoInputs, CE.NoAlpha)) ImGui.PopID() + -- HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0) + -- (s.hsv is stored as HSV!) ImGui.Spacing() ImGui.Text("HSV encoded colors") ImGui.SameLine(); HelpMarker("By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV.") @@ -24168,36 +27722,53 @@ function DemoWindowWidgetsColorAndPickers() ImGui.TreePop() end -S.combo = { flags = 0, sel = 0, filter = nil, c2 = 0, c3 = -1, c4 = 0 } +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsComboBoxes() +------------------------------------------------------------------------------- + +S.combo = { flags = 0, sel = 0, filter = nil, c2 = 0, c3 = -1, c4 = 0 } -- sel: Here we store our selection data as an index. function DemoWindowWidgetsComboBoxes() if not ImGui.TreeNode("Combo") then return end local s = S.combo local CF = ImGuiComboFlags local p + -- Combo Boxes are also called "Dropdown" in other systems + -- Expose flags as checkbox for the demo _, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", s.flags, CF.PopupAlignLeft) ImGui.SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo") p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_NoArrowButton", s.flags, CF.NoArrowButton) - if p then s.flags = bit32.band(s.flags, bit32.bnot(CF.NoPreview)) end + if p then s.flags = bit32.band(s.flags, bit32.bnot(CF.NoPreview)) end -- Clear incompatible flags p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_NoPreview", s.flags, CF.NoPreview) - if p then s.flags = bit32.band(s.flags, bit32.bnot(bit32.bor(CF.NoArrowButton, CF.WidthFitPreview))) end + if p then s.flags = bit32.band(s.flags, bit32.bnot(bit32.bor(CF.NoArrowButton, CF.WidthFitPreview))) end -- Clear incompatible flags p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_WidthFitPreview", s.flags, CF.WidthFitPreview) if p then s.flags = bit32.band(s.flags, bit32.bnot(CF.NoPreview)) end + + -- Override default popup height for _, h in ipairs({ "HeightSmall", "HeightRegular", "HeightLargest" }) do p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_" .. h, s.flags, CF[h]) if p then s.flags = bit32.band(s.flags, bit32.bnot(bit32.band(CF.HeightMask_, bit32.bnot(CF[h])))) end end + -- Using the generic BeginCombo() API, you have full control over how to display the combo contents. + -- (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + -- stored in the object itself, etc.) local items = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" } + + -- Pass in the preview value visible before opening the combo (it could technically be different contents or not pulled from items[]) local combo_preview_value = items[s.sel + 1] if ImGui.BeginCombo("combo 1", combo_preview_value, s.flags) then for n = 0, #items - 1 do local is_selected = (s.sel == n) if ImGui.Selectable(items[n + 1], is_selected) then s.sel = n end + + -- Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if is_selected then ImGui.SetItemDefaultFocus() end end ImGui.EndCombo() end + -- Show case embedding a filter using a simple trick: displaying the filter inside combo contents. + -- See https://github.com/ocornut/imgui/issues/718 for advanced/esoteric alternatives. if ImGui.BeginCombo("combo 2 (w/ filter)", combo_preview_value, s.flags) then s.filter = s.filter or ImGuiTextFilter() if ImGui.IsWindowAppearing() then @@ -24219,19 +27790,46 @@ function DemoWindowWidgetsComboBoxes() ImGui.Spacing() ImGui.SeparatorText("One-liner variants") HelpMarker("The Combo() function is not greatly useful apart from cases were you want to embed all options in a single strings.\nFlags above don't apply to this section.") + + -- Simplified one-liner Combo() API, using values packed in a single constant string + -- This is a convenience for when the selection set is small and known at compile-time. s.c2 = ImGui.Combo("combo 3 (one-liner)", s.c2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0") - s.c3 = ImGui.Combo("combo 4 (array)", s.c3, items, #items) + + -- Simplified one-liner Combo() using an array of strings + -- This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control. + s.c3 = ImGui.Combo("combo 4 (array)", s.c3, items, #items) -- If the selection isn't within 0..count, Combo won't display a preview + + -- Simplified one-liner Combo() using an accessor function s.c4 = ImGui.Combo("combo 5 (function)", s.c4, function(data, n) return data[n + 1] end, items, #items) ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDataTypes() +------------------------------------------------------------------------------- + S.dt = { s8 = 127, u8 = 255, s16 = 32767, u16 = 65535, s32 = -1, u32 = 0xFFFFFFFF, s64 = -1, u64 = 0, f32 = 0.123, f64 = 90000.01234567890123456789, drag_clamp = false, inputs_step = true, flags = 0 } function DemoWindowWidgetsDataTypes() if not ImGui.TreeNode("Data Types") then return end local s = S.dt local DT = ImGuiDataType + -- DragScalar/InputScalar/SliderScalar functions allow various data types + -- - signed/unsigned + -- - 8/16/32/64-bits + -- - integer/float/double + -- To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum + -- to pass the type. + -- In practice, if you frequently use a given type that is not covered by the normal API entry points, + -- you can wrap it yourself inside a 1 line function which can take typed argument as value, + -- and then pass them to the generic function. For example: + -- local function MySliderU32(label, value, min, max, format) + -- return ImGui.SliderScalar(label, ImGuiDataType.U32, value, min or 0, max or 0, format or "%u") + -- end + -- ponytail: Luau numbers are doubles, so S64/U64 are shown with S32/Double here (no 64-bit integer type) + -- Setup limits + -- Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2. local s32_min, s32_max = math.floor(-2147483648 / 2), math.floor(2147483647 / 2) local u32_max = math.floor(4294967295 / 2) local drag_speed = 0.2 @@ -24295,6 +27893,10 @@ function DemoWindowWidgetsDataTypes() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDisableBlocks() +------------------------------------------------------------------------------- + function DemoWindowWidgetsDisableBlocks(demo_data) if not ImGui.TreeNode("Disable Blocks") then return end _, demo_data.DisableSections = ImGui.Checkbox("Disable entire section above", demo_data.DisableSections) @@ -24302,6 +27904,10 @@ function DemoWindowWidgetsDisableBlocks(demo_data) ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDragAndDrop() +------------------------------------------------------------------------------- + S.dnd = { col1 = { 1.0, 0.0, 0.2 }, col2 = { 0.4, 0.7, 0.0, 0.5 }, mode = 0, names = { "Bobby", "Beatrice", "Betty", "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" }, item_names = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" }, col4 = ImVec4(1.0, 0.0, 0.2, 1.0) } @@ -24309,6 +27915,10 @@ function DemoWindowWidgetsDragAndDrop() if not ImGui.TreeNode("Drag and Drop") then return end local s = S.dnd if ImGui.TreeNode("Drag and drop in standard widgets") then + -- ColorEdit widgets automatically act as drag source and drag target. + -- They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F + -- to allow your own widgets to use colors in their drag and drop interaction. + -- Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo. HelpMarker("You can drag from the color squares.") ImGui.ColorEdit3("color 1", s.col1) ImGui.ColorEdit4("color 2", s.col2) @@ -24325,8 +27935,14 @@ function DemoWindowWidgetsDragAndDrop() ImGui.PushID(n) if n % 3 ~= 0 then ImGui.SameLine() end ImGui.Button(names[n + 1], ImVec2(60, 60)) + + -- Our buttons are both drag sources and drag targets here! if ImGui.BeginDragDropSource(ImGuiDragDropFlags.None) then + -- Set payload to carry the index of our item (could be anything) ImGui.SetDragDropPayload("DND_DEMO_CELL", n, 4) + + -- Display preview (could be anything, e.g. when dragging an image we could decide to display + -- the filename and a small preview of the image, etc.) if s.mode == Mode_Copy then ImGui.Text("Copy %s", names[n + 1]) end if s.mode == Mode_Move then ImGui.Text("Move %s", names[n + 1]) end if s.mode == Mode_Swap then ImGui.Text("Swap %s", names[n + 1]) end @@ -24348,7 +27964,12 @@ function DemoWindowWidgetsDragAndDrop() end if ImGui.TreeNode("Drag to reorder items (simple)") then + -- FIXME: there is temporary (usually single-frame) ID Conflict during reordering as a same item may be submitting twice. + -- This code was always slightly faulty but in a way which was not easily noticeable. + -- Until we fix this, enable ImGuiItemFlags.AllowDuplicateId to disable detecting the issue. ImGui.PushItemFlag(ImGuiItemFlags.AllowDuplicateId, true) + + -- Simple reordering HelpMarker("We don't use the drag and drop api at all here! Instead we query when the item is held but not hovered, and order items accordingly.") local item_names = s.item_names for n = 1, #item_names do @@ -24369,6 +27990,7 @@ function DemoWindowWidgetsDragAndDrop() if ImGui.TreeNode("Tooltip at target location") then for n = 0, 1 do + -- Drop targets ImGui.Button((n == 1) and "drop here##1" or "drop here##0") if ImGui.BeginDragDropTarget() then local drop_target_flags = bit32.bor(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoPreviewTooltip) @@ -24378,6 +28000,8 @@ function DemoWindowWidgetsDragAndDrop() end ImGui.EndDragDropTarget() end + + -- Drop source if n == 0 then ImGui.ColorButton("drag me", s.col4) end end ImGui.TreePop() @@ -24385,9 +28009,14 @@ function DemoWindowWidgetsDragAndDrop() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDragsAndSliders() +------------------------------------------------------------------------------- + S.ds = { flags = 0, drag_f = 0.5, drag_f4 = { 0, 0, 0, 0 }, drag_i = 50, slider_f = 0.5, slider_f4 = { 0, 0, 0, 0 }, slider_i = 50 } function DemoWindowWidgetsDragsAndSliders() if not ImGui.TreeNode("Drag/Slider Flags") then return end + -- Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! local s = S.ds local SF = ImGuiSliderFlags local function F(name, help) @@ -24406,45 +28035,70 @@ function DemoWindowWidgetsDragsAndSliders() F("ColorMarkers") local flags = s.flags + -- Drags ImGui.Text("Underlying float value: %f", s.drag_f) s.drag_f = ImGui.DragFloat("DragFloat (0 -> 1)", s.drag_f, 0.005, 0.0, 1.0, "%.3f", flags) s.drag_f = ImGui.DragFloat("DragFloat (0 -> +inf)", s.drag_f, 0.005, 0.0, FLT_MAX, "%.3f", flags) s.drag_f = ImGui.DragFloat("DragFloat (-inf -> 1)", s.drag_f, 0.005, -FLT_MAX, 1.0, "%.3f", flags) s.drag_f = ImGui.DragFloat("DragFloat (-inf -> +inf)", s.drag_f, 0.005, -FLT_MAX, FLT_MAX, "%.3f", flags) + -- ImGui.DragFloat("DragFloat (0 -> 0)", drag_f, 0.005, 0.0, 0.0, "%.3f", flags) -- To test ClampZeroRange + -- ImGui.DragFloat("DragFloat (100 -> 100)", drag_f, 0.005, 100.0, 100.0, "%.3f", flags) s.drag_i = ImGui.DragInt("DragInt (0 -> 100)", s.drag_i, 0.5, 0, 100, "%d", flags) - ImGui.DragFloat4("DragFloat4 (0 -> 1)", s.drag_f4, 0.005, 0.0, 1.0, "%.3f", flags) + ImGui.DragFloat4("DragFloat4 (0 -> 1)", s.drag_f4, 0.005, 0.0, 1.0, "%.3f", flags) -- Multi-component item, mostly here to document the effect of ImGuiSliderFlags.ColorMarkers. + -- Sliders local flags_for_sliders = bit32.band(flags, bit32.bnot(SF.WrapAround)) ImGui.Text("Underlying float value: %f", s.slider_f) s.slider_f = ImGui.SliderFloat("SliderFloat (0 -> 1)", s.slider_f, 0.0, 1.0, "%.3f", flags_for_sliders) s.slider_i = ImGui.SliderInt("SliderInt (0 -> 100)", s.slider_i, 0, 100, "%d", flags_for_sliders) - ImGui.SliderFloat4("SliderFloat4 (0 -> 1)", s.slider_f4, 0.0, 1.0, "%.3f", flags_for_sliders) + ImGui.SliderFloat4("SliderFloat4 (0 -> 1)", s.slider_f4, 0.0, 1.0, "%.3f", flags_for_sliders) -- Multi-component item, mostly here to document the effect of ImGuiSliderFlags.ColorMarkers. ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsFonts() +------------------------------------------------------------------------------- + function DemoWindowWidgetsFonts() if not ImGui.TreeNode("Fonts") then return end if ImGui.ShowFontAtlas then ImGui.ShowFontAtlas(ImGui.GetIO().Fonts) else DemoNotPorted("ShowFontAtlas") end + -- FIXME-NEWATLAS: Provide a demo to add/create a procedural font? ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsImages() +------------------------------------------------------------------------------- + S.img = { viewer = nil, pressed_count = 0 } function DemoWindowWidgetsImages() if not ImGui.TreeNode("Images") then return end local s = S.img local io = ImGui.GetIO() ImGui.TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!") + + -- Below we are displaying the font texture because it is the only texture we have access to inside the demo! + -- Read description about ImTextureID/ImTextureRef and FAQ for details about texture identifiers. + -- - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer, + -- it will help you debug issues if you are confused about it. + -- - Consider using the lower-level ImDrawList:AddImage() API, via ImGui.GetWindowDrawList():AddImage(). + -- - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md + -- - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + + -- Grab the current texture identifier used by the font atlas. local atlas = io.Fonts local my_tex_id = atlas.TexRef - local my_tex_w = atlas.TexData and atlas.TexData.Width or 0 + local my_tex_w = atlas.TexData and atlas.TexData.Width or 0 -- Regular user code should never have to care about TexData fields, but since we want to display the entire texture here, we pull Width/Height from it. local my_tex_h = atlas.TexData and atlas.TexData.Height or 0 ImGui.Text("%.0fx%.0f", my_tex_w, my_tex_h) + -- Basic drawing ImGui.SeparatorText("Image()/ImageWithBg() function") ImGui.PushStyleVar(ImGuiStyleVar.ImageBorderSize, math.max(1.0, ImGui.GetStyle().ImageBorderSize)) - ImGui.ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0.0, 0.0), ImVec2(1.0, 1.0), ImVec4(0.0, 0.0, 0.0, 1.0)) + ImGui.ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0.0, 0.0), ImVec2(1.0, 1.0), ImVec4(0.0, 0.0, 0.0, 1.0)) -- uv_min: Top-left, uv_max: Lower-right ImGui.PopStyleVar() + -- Fancy widget ImGui.SeparatorText("Interactive Image Viewer") s.viewer = s.viewer or ExampleImageViewerData() local canvas_size = ImVec2(ImGui.GetContentRegionAvail().x, my_tex_h * 2.0) @@ -24454,11 +28108,15 @@ function DemoWindowWidgetsImages() ImGui.SeparatorText("Textured Buttons") ImGui.TextWrapped("And now some textured buttons..") for i = 0, 7 do + -- UV coordinates are often (0.0, 0.0) and (1.0, 1.0) to display an entire textures. + -- Here are trying to display only a 32x32 pixels area of the texture, hence the UV computation. + -- Read about UV coordinates here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples ImGui.PushID(i) if i > 0 then ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, ImVec2(i - 1.0, i - 1.0)) end - local size = ImVec2(32.0, 32.0) - local uv0 = ImVec2(0.0, 0.0) - local uv1 = ImVec2(32.0 / my_tex_w, 32.0 / my_tex_h) + local size = ImVec2(32.0, 32.0) -- Size of the image we want to make visible + local uv0 = ImVec2(0.0, 0.0) -- UV coordinates for lower-left + local uv1 = ImVec2(32.0 / my_tex_w, 32.0 / my_tex_h) -- UV coordinates for (32,32) in our texture + -- bg_col: Black background, tint_col: No tint if ImGui.ImageButton("", my_tex_id, size, uv0, uv1, ImVec4(0.0, 0.0, 0.0, 1.0), ImVec4(1.0, 1.0, 1.0, 1.0)) then s.pressed_count = s.pressed_count + 1 end @@ -24471,29 +28129,45 @@ function DemoWindowWidgetsImages() ImGui.TreePop() end -S.lb = { sel = 0, highlight = false } +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsListBoxes() +------------------------------------------------------------------------------- + +S.lb = { sel = 0, highlight = false } -- sel: Here we store our selected data as an index. function DemoWindowWidgetsListBoxes() if not ImGui.TreeNode("List Boxes") then return end + -- BeginListBox() is essentially a thin wrapper to using BeginChild()/EndChild() + -- using the ImGuiChildFlags.FrameStyle flag for stylistic changes + displaying a label. + -- You may be tempted to simply use BeginChild() directly. However note that BeginChild() requires EndChild() + -- to always be called (inconsistent with BeginListBox()/EndListBox()). + + -- Using the generic BeginListBox() API, you have full control over how to display the combo contents. + -- (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + -- stored in the object itself, etc.) local s = S.lb local items = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" } - local item_highlighted_idx = -1 + local item_highlighted_idx = -1 -- Here we store our highlighted data as an index. _, s.highlight = ImGui.Checkbox("Highlight hovered item in second listbox", s.highlight) if ImGui.BeginListBox("listbox 1") then for n = 0, #items - 1 do local is_selected = (s.sel == n) if ImGui.Selectable(items[n + 1], is_selected) then s.sel = n end if s.highlight and ImGui.IsItemHovered() then item_highlighted_idx = n end + -- Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if is_selected then ImGui.SetItemDefaultFocus() end end ImGui.EndListBox() end ImGui.SameLine(); HelpMarker("Here we are sharing selection state between both boxes.") + + -- Custom size: use all width, 5 items tall ImGui.Text("Full-width:") if ImGui.BeginListBox("##listbox 2", ImVec2(-FLT_MIN, 5 * ImGui.GetTextLineHeightWithSpacing())) then for n = 0, #items - 1 do local is_selected = (s.sel == n) local flags = (item_highlighted_idx == n) and ImGuiSelectableFlags.Highlight or 0 if ImGui.Selectable(items[n + 1], is_selected, flags) then s.sel = n end + -- Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if is_selected then ImGui.SetItemDefaultFocus() end end ImGui.EndListBox() @@ -24501,6 +28175,10 @@ function DemoWindowWidgetsListBoxes() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsLiveEdit() +------------------------------------------------------------------------------- + S.le = { str = Buf("", 32), i = 0, f = 0.0 } function DemoWindowWidgetsLiveEdit(demo_data) if not ImGui.TreeNode("Live Edit Flags") then return end @@ -24524,15 +28202,22 @@ function DemoWindowWidgetsLiveEdit(demo_data) ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsMixedValues() +------------------------------------------------------------------------------- + S.mv = { use_liveedit = false, items = { 12.0, 0.0, 0.0 } } function DemoWindowWidgetsMixedValues() if not ImGui.TreeNode("Mixed Values") then return end local s = S.mv local items = s.items + -- This is designed for advanced property editors which are generally reusable and data-driven. HelpMarker("Using ImGuiItemFlags_MixedValue.") _, s.use_liveedit = ImGui.Checkbox("ImGuiItemFlags_LiveEditOnInput", s.use_liveedit) ImGui.SeparatorText("Scalar/Text Widgets") local is_mixed = items[1] ~= items[2] or items[1] ~= items[3] + + -- Demonstrate Drags, Sliders, Inputs ImGui.PushItemFlag(ImGuiItemFlags.LiveEditOnInput, s.use_liveedit) ImGui.PushItemFlag(ImGuiItemFlags.MixedValue, is_mixed) local edited, e = false, false @@ -24547,27 +28232,32 @@ function DemoWindowWidgetsMixedValues() items[3] = ImGui.InputFloat("item 2", items[3]) ImGui.PopItemFlag() + -- Demonstrate Checkbox(), RadioButton(), Combo(), ColorEdit4() ImGui.SeparatorText("Others Widgets") - ImGui.Text("(note: edits are not applied in this demo)") + ImGui.Text("(note: edits are not applied in this demo)") -- <-- Would need more state tracking. ImGui.Checkbox("Checkbox On", true) ImGui.Checkbox("Checkbox Off", false) ImGui.PushItemFlag(ImGuiItemFlags.MixedValue, true) ImGui.Checkbox("Checkbox Mixed", false) ImGui.RadioButtonEx("RadioButton Mixed", true) ImGui.SameLine() - ImGui.RadioButtonEx("RadioButton Mixed##2", true) + ImGui.RadioButtonEx("RadioButton Mixed##2", true) -- Showing 2 radio buttons makes the example more clear ImGui.Combo("Combo", 0, "One\0Two\0Three\0") ImGui.ColorEdit4("ColorEdit4", ImVec4(0.5, 0.5, 0.5, 0.5)) ImGui.PopItemFlag() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsMultiComponents() +------------------------------------------------------------------------------- + S.mc = { vec4f = { 0.10, 0.20, 0.30, 0.44 }, vec4i = { 1, 5, 100, 255 }, flags = 0, b = 10, e = 90, bi = 100, ei = 1000 } function DemoWindowWidgetsMultiComponents() if not ImGui.TreeNode("Multi-component Widgets") then return end local s = S.mc local f, i = s.vec4f, s.vec4i - if ImGuiSliderFlags.ColorMarkers then _, s.flags = ImGui.CheckboxFlags("ImGuiSliderFlags_ColorMarkers", s.flags, ImGuiSliderFlags.ColorMarkers) end + if ImGuiSliderFlags.ColorMarkers then _, s.flags = ImGui.CheckboxFlags("ImGuiSliderFlags_ColorMarkers", s.flags, ImGuiSliderFlags.ColorMarkers) end -- Only passing this to Drag/Sliders local flags = s.flags for _, n in ipairs({ 2, 3, 4 }) do ImGui.SeparatorText(n .. "-wide") @@ -24585,6 +28275,13 @@ function DemoWindowWidgetsMultiComponents() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsPlotting() +------------------------------------------------------------------------------- + +-- Plot/Graph widgets are not very good. +-- Consider using a third-party library such as ImPlot: https://github.com/epezent/implot +-- (see others https://github.com/ocornut/imgui/wiki/Useful-Extensions) S.plot = { animate = true, arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }, values = {}, values_offset = 0, refresh_time = 0.0, phase = 0.0, func_type = 0, display_count = 70 } for n = 1, 90 do S.plot.values[n] = 0.0 end @@ -24595,22 +28292,32 @@ function DemoWindowWidgetsPlotting() ImGui.TextLinkOpenURL("https://github.com/epezent/implot") ImGui.Separator() _, s.animate = ImGui.Checkbox("Animate", s.animate) + + -- Plot as lines and plot as histogram ImGui.PlotLines("Frame Times", s.arr, nil, #s.arr) ImGui.PlotHistogram("Histogram", s.arr, nil, #s.arr, 0, nil, 0.0, 1.0, ImVec2(0, 80.0)) + -- ImGui.SameLine(); HelpMarker("Consider using ImPlot instead!") + -- Fill an array of contiguous float values to plot local values = s.values if not s.animate or s.refresh_time == 0.0 then s.refresh_time = ImGui.GetTime() end - while s.refresh_time < ImGui.GetTime() do + while s.refresh_time < ImGui.GetTime() do -- Create data at fixed 60 Hz rate for the demo values[s.values_offset + 1] = math.cos(s.phase) s.values_offset = (s.values_offset + 1) % #values s.phase = s.phase + 0.10 * s.values_offset s.refresh_time = s.refresh_time + 1.0 / 60.0 end + + -- Plots can display overlay texts + -- (in this example, we will display an average value) local average = 0.0 for n = 1, #values do average = average + values[n] end average = average / #values ImGui.PlotLines("Lines", values, nil, #values, s.values_offset, string.format("avg %f", average), -1.0, 1.0, ImVec2(0, 80.0)) + -- Use functions to generate output + -- FIXME: This is actually VERY awkward because current plot API only pass in indices. + -- We probably want an API passing floats and user provide sample rate/count. -- Getters receive a 1-based index in this port local function Sin(_, i) return math.sin((i - 1) * 0.1) end local function Saw(_, i) return ((i - 1) % 2 == 1) and 1.0 or -1.0 end @@ -24625,24 +28332,39 @@ function DemoWindowWidgetsPlotting() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsProgressBars() +------------------------------------------------------------------------------- + S.pb = { accum = 0.0, dir = 1.0 } function DemoWindowWidgetsProgressBars() if not ImGui.TreeNode("Progress Bars") then return end + -- Animate a simple progress bar local s = S.pb s.accum = s.accum + s.dir * 0.4 * ImGui.GetIO().DeltaTime if s.accum >= 1.1 then s.accum = 1.1; s.dir = -s.dir end if s.accum <= -0.1 then s.accum = -0.1; s.dir = -s.dir end local progress = DemoClamp(s.accum, 0.0, 1.0) + + -- Typically we would use ImVec2(-1.0,0.0) or ImVec2(-FLT_MIN,0.0) to use all available width, + -- or ImVec2(width,0.0) for a specified width. ImVec2(0.0,0.0) uses ItemWidth. ImGui.ProgressBar(progress, ImVec2(0.0, 0.0)) ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x) ImGui.Text("Progress Bar") ImGui.ProgressBar(progress, ImVec2(0.0, 0.0), string.format("%d/%d", math.floor(progress * 1753), 1753)) + + -- Pass an animated negative value, e.g. -1.0 * ImGui.GetTime() is the recommended value. + -- Adjust the factor if you want to adjust the animation speed. ImGui.ProgressBar(-1.0 * ImGui.GetTime(), ImVec2(0.0, 0.0), "Searching..") ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x) ImGui.Text("Indeterminate") ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsQueryingStatuses() +------------------------------------------------------------------------------- + -- Selectable(label, bool* p_selected) overload: toggles on press local function SelectableP(label, sel, flags, size) local pressed = ImGui.Selectable(label, sel, flags, size) @@ -24658,6 +28380,7 @@ S.qs = { item_type = 4, item_disabled = false, item_mixedvalue = false, liveedit function DemoWindowWidgetsQueryingStatuses() local s = S.qs if ImGui.TreeNode("Querying Item Status (Edited/Active/Hovered etc.)") then + -- Select an item type local item_names = { "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputTextMultiline", "InputFloat", "InputFloat3", "ColorEdit4", "Selectable", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "Combo", "ListBox" } s.item_type = ImGui.Combo("Item Type", s.item_type, item_names, #item_names, #item_names) @@ -24680,24 +28403,25 @@ function DemoWindowWidgetsQueryingStatuses() ImGui.PushItemFlag(ImGuiItemFlags.LiveEditOnInputScalar, bit32.band(s.liveedit_flags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0) end + -- Submit selected items so we can query their status in the code following it. local ret = false local t = s.item_type if s.item_disabled then ImGui.BeginDisabled(true) end if s.item_mixedvalue then ImGui.PushItemFlag(ImGuiItemFlags.MixedValue, true) end - if t == 0 then ImGui.Text("ITEM: Text") end - if t == 1 then ret = ImGui.Button("ITEM: Button") end - if t == 2 then ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true); ret = ImGui.Button("ITEM: Button"); ImGui.PopItemFlag() end - if t == 3 then ret, s.b = ImGui.Checkbox("ITEM: Checkbox", s.b) end - if t == 4 then s.col4f[1], ret = ImGui.SliderFloat("ITEM: SliderFloat", s.col4f[1], 0.0, 1.0) end - if t == 5 then ret = ImGui.InputText("ITEM: InputText", s.str, 16) end - if t == 6 then ret = ImGui.InputTextMultiline("ITEM: InputTextMultiline", s.str, 16) end - if t == 7 then s.col4f[1], ret = ImGui.InputFloat("ITEM: InputFloat", s.col4f[1], 1.0) end - if t == 8 then ret = ImGui.InputFloat3("ITEM: InputFloat3", s.col4f) end - if t == 9 then ret = ImGui.ColorEdit4("ITEM: ColorEdit4", s.col4f) end - if t == 10 then ret = ImGui.Selectable("ITEM: Selectable") end - if t == 11 then ret = ImGui.MenuItem("ITEM: MenuItem") end - if t == 12 then ret = ImGui.TreeNode("ITEM: TreeNode"); if ret then ImGui.TreePop() end end - if t == 13 then ret = ImGui.TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", bit32.bor(ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.NoTreePushOnOpen)) end + if t == 0 then ImGui.Text("ITEM: Text") end -- Testing text items with no identifier/interaction + if t == 1 then ret = ImGui.Button("ITEM: Button") end -- Testing button + if t == 2 then ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true); ret = ImGui.Button("ITEM: Button"); ImGui.PopItemFlag() end -- Testing button (with repeater) + if t == 3 then ret, s.b = ImGui.Checkbox("ITEM: Checkbox", s.b) end -- Testing checkbox + if t == 4 then s.col4f[1], ret = ImGui.SliderFloat("ITEM: SliderFloat", s.col4f[1], 0.0, 1.0) end -- Testing basic item + if t == 5 then ret = ImGui.InputText("ITEM: InputText", s.str, 16) end -- Testing input text (which handles tabbing) + if t == 6 then ret = ImGui.InputTextMultiline("ITEM: InputTextMultiline", s.str, 16) end -- Testing input text (which uses a child window) + if t == 7 then s.col4f[1], ret = ImGui.InputFloat("ITEM: InputFloat", s.col4f[1], 1.0) end -- Testing +/- buttons on scalar input + if t == 8 then ret = ImGui.InputFloat3("ITEM: InputFloat3", s.col4f) end -- Testing multi-component items (IsItemXXX flags are reported merged) + if t == 9 then ret = ImGui.ColorEdit4("ITEM: ColorEdit4", s.col4f) end -- Testing multi-component items (IsItemXXX flags are reported merged) + if t == 10 then ret = ImGui.Selectable("ITEM: Selectable") end -- Testing selectable item + if t == 11 then ret = ImGui.MenuItem("ITEM: MenuItem") end -- Testing menu item (they use ImGuiButtonFlags.PressedOnRelease button policy) + if t == 12 then ret = ImGui.TreeNode("ITEM: TreeNode"); if ret then ImGui.TreePop() end end -- Testing tree node + if t == 13 then ret = ImGui.TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", bit32.bor(ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.NoTreePushOnOpen)) end -- Testing tree node with ImGuiButtonFlags.PressedOnDoubleClick button policy. if t == 14 then s.combo, ret = ImGui.Combo("ITEM: Combo", s.combo, { "Apple", "Banana", "Cherry", "Kiwi" }) end if t == 15 then s.listbox, ret = ImGui.ListBox("ITEM: ListBox", s.listbox, { "Apple", "Banana", "Cherry", "Kiwi" }, 4, 4) end @@ -24706,7 +28430,12 @@ function DemoWindowWidgetsQueryingStatuses() local hovered_delay_stationary = ImGui.IsItemHovered(HF.Stationary) local hovered_delay_short = ImGui.IsItemHovered(HF.DelayShort) local hovered_delay_normal = ImGui.IsItemHovered(HF.DelayNormal) - local hovered_delay_tooltip = ImGui.IsItemHovered(HF.ForTooltip) + local hovered_delay_tooltip = ImGui.IsItemHovered(HF.ForTooltip) -- = Normal + Stationary + + -- Display the values of IsItemHovered() and other common item state functions. + -- Note that the ImGuiHoveredFlags.XXX flags can be combined. + -- Because BulletText is an item itself and that would affect the output of IsItemXXX functions, + -- we query every state in a single call to avoid storing them and to simplify the code. local rmin, rmax, rsize = ImGui.GetItemRectMin(), ImGui.GetItemRectMax(), ImGui.GetItemRectSize() ImGui.BulletText( "Return value = %d\nIsItemFocused() = %d\nIsItemHovered() = %d\nIsItemHovered(_AllowWhenBlockedByPopup) = %d\n" .. @@ -24740,6 +28469,7 @@ function DemoWindowWidgetsQueryingStatuses() if s.embed then ImGui.BeginChild("outer_child", ImVec2(0, ImGui.GetFontSize() * 20.0), ImGuiChildFlags.Borders) end local FF, HF = ImGuiFocusedFlags, ImGuiHoveredFlags local bor = bit32.bor + -- Testing IsWindowFocused() function with its various flags. ImGui.BulletText( "IsWindowFocused() = %d\nIsWindowFocused(_ChildWindows) = %d\nIsWindowFocused(_ChildWindows|_NoPopupHierarchy) = %d\n" .. "IsWindowFocused(_ChildWindows|_DockHierarchy) = %d\nIsWindowFocused(_ChildWindows|_RootWindow) = %d\n" .. @@ -24751,6 +28481,8 @@ function DemoWindowWidgetsQueryingStatuses() B(ImGui.IsWindowFocused(bor(FF.ChildWindows, FF.RootWindow, FF.NoPopupHierarchy))), B(ImGui.IsWindowFocused(bor(FF.ChildWindows, FF.RootWindow, FF.DockHierarchy))), B(ImGui.IsWindowFocused(FF.RootWindow)), B(ImGui.IsWindowFocused(bor(FF.RootWindow, FF.NoPopupHierarchy))), B(ImGui.IsWindowFocused(bor(FF.RootWindow, FF.DockHierarchy))), B(ImGui.IsWindowFocused(FF.AnyWindow))) + + -- Testing IsWindowHovered() function with its various flags. ImGui.BulletText( "IsWindowHovered() = %d\nIsWindowHovered(_AllowWhenBlockedByPopup) = %d\nIsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n" .. "IsWindowHovered(_ChildWindows) = %d\nIsWindowHovered(_ChildWindows|_NoPopupHierarchy) = %d\nIsWindowHovered(_ChildWindows|_DockHierarchy) = %d\n" .. @@ -24769,10 +28501,15 @@ function DemoWindowWidgetsQueryingStatuses() ImGui.EndChild() if s.embed then ImGui.EndChild() end + -- Calling IsItemHovered() after begin returns the hovered status of the title bar. + -- This is useful in particular if you want to create a context menu associated to the title bar of a window. + -- This will also work when docked into a Tab (the Tab replace the Title Bar and guarantee the same properties). _, s.test_window = ImGui.Checkbox("Hovered/Active tests after Begin() for title bar testing", s.test_window) if s.test_window then + -- FIXME-DOCK: This window cannot be docked within the ImGui Demo window, this will cause a feedback loop and get them stuck. + -- Could we fix this through an ImGuiWindowClass feature? Or an API call to tag our parent as "don't skip items"? s.test_window = ImGui.Begin("Title bar Hovered/Active tests", s.test_window) - if ImGui.BeginPopupContextItem() then + if ImGui.BeginPopupContextItem() then -- <-- This is using IsItemHovered() if ImGui.MenuItem("Close") then s.test_window = false end ImGui.EndPopup() end @@ -24784,13 +28521,25 @@ function DemoWindowWidgetsQueryingStatuses() end end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsSelectables() +------------------------------------------------------------------------------- + S.sel = { basic = { false, true, false, false }, multi = { false, false, false }, checked = { false, false, false, false, false }, selected_n = 0, tables = {}, grid = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }, align = { true, false, true, false, true, false, true, false, true } } for i = 1, 10 do S.sel.tables[i] = false end function DemoWindowWidgetsSelectables() + -- ImGui.SetNextItemOpen(true, ImGuiCond.Once) if not ImGui.TreeNode("Selectables") then return end local s = S.sel + -- Selectable() has 2 overloads: + -- - The one taking "bool selected" as a read-only selection information. + -- When Selectable() has been clicked it returns true and you can alter selection state accordingly. + -- - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases) + -- (in this port: the SelectableP() helper above, which returns (pressed, selected)) + -- The earlier is more flexible, as in real application your selection may be stored in many different ways + -- and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc). if ImGui.TreeNode("Basic") then local b = s.basic _, b[1] = SelectableP("1. I am selectable", b[1]) @@ -24803,10 +28552,17 @@ function DemoWindowWidgetsSelectables() end if ImGui.TreeNode("Multiple items on the same line") then + -- - Using SetNextItemAllowOverlap() + -- - Using the Selectable() override that takes "bool* p_selected" parameter, the bool value is toggled automatically. local m = s.multi ImGui.SetNextItemAllowOverlap(); _, m[1] = SelectableP("main.c", m[1]); ImGui.SameLine(); ImGui.SmallButton("Link 1") ImGui.SetNextItemAllowOverlap(); _, m[2] = SelectableP("hello.cpp", m[2]); ImGui.SameLine(); ImGui.SmallButton("Link 2") ImGui.SetNextItemAllowOverlap(); _, m[3] = SelectableP("hello.h", m[3]); ImGui.SameLine(); ImGui.SmallButton("Link 3") + + -- (2) + -- - Using ImGuiSelectableFlags.AllowOverlap is a shortcut for calling SetNextItemAllowOverlap() + -- - No visible label, display contents inside the selectable bounds. + -- - We don't maintain actual selection in this example to keep things simple. ImGui.Spacing() local color_marker_w = ImGui.CalcTextSize("x").x for n = 0, 4 do @@ -24831,7 +28587,7 @@ function DemoWindowWidgetsSelectables() if ImGui.BeginTable("split1", 3, bit32.bor(TF.Resizable, TF.NoSavedSettings, TF.Borders)) then for i = 0, 9 do ImGui.TableNextColumn() - _, sel[i + 1] = SelectableP(string.format("Item %d", i), sel[i + 1]) + _, sel[i + 1] = SelectableP(string.format("Item %d", i), sel[i + 1]) -- FIXME-TABLE: Selection overlap end ImGui.EndTable() end @@ -24853,9 +28609,11 @@ function DemoWindowWidgetsSelectables() if ImGui.TreeNode("Grid") then local g = s.grid + + -- Add in a bit of silly fun... local time = ImGui.GetTime() local winning_state = true - for y = 1, 4 do for x = 1, 4 do if g[y][x] == 0 then winning_state = false end end end + for y = 1, 4 do for x = 1, 4 do if g[y][x] == 0 then winning_state = false end end end -- If all cells are selected... if winning_state then ImGui.PushStyleVar(ImGuiStyleVar.SelectableTextAlign, ImVec2(0.5 + 0.5 * math.cos(time * 2.0), 0.5 + 0.5 * math.sin(time * 3.0))) end @@ -24865,6 +28623,7 @@ function DemoWindowWidgetsSelectables() if x > 1 then ImGui.SameLine() end ImGui.PushID((y - 1) * 4 + (x - 1)) if ImGui.Selectable("Sailor", g[y][x] ~= 0, 0, ImVec2(size, size)) then + -- Toggle clicked cell + toggle neighbors g[y][x] = 1 - g[y][x] if x > 1 then g[y][x - 1] = 1 - g[y][x - 1] end if x < 4 then g[y][x + 1] = 1 - g[y][x + 1] end @@ -24896,6 +28655,10 @@ function DemoWindowWidgetsSelectables() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTabs() +------------------------------------------------------------------------------- + local function EditTabBarFittingPolicyFlags(flags) local TB = ImGuiTabBarFlags if bit32.band(flags, TB.FittingPolicyMask_) == 0 then flags = bit32.bor(flags, TB.FittingPolicyDefault_) end @@ -24926,17 +28689,23 @@ function DemoWindowWidgetsTabs() end if ImGui.TreeNode("Advanced & Close Button") then + -- Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0). for _, n in ipairs({ "Reorderable", "AutoSelectNewTabs", "TabListPopupButton", "NoCloseWithMiddleMouseButton", "DrawSelectedOverline" }) do _, s.adv_flags = ImGui.CheckboxFlags("ImGuiTabBarFlags_" .. n, s.adv_flags, TB[n]) end s.adv_flags = EditTabBarFittingPolicyFlags(s.adv_flags) + + -- Tab Bar ImGui.AlignTextToFramePadding() ImGui.Text("Opened:") local names = { "Artichoke", "Beetroot", "Celery", "Daikon" } - for n = 1, 4 do + for n = 1, 4 do -- s.opened: Persistent user state ImGui.SameLine() _, s.opened[n] = ImGui.Checkbox(names[n], s.opened[n]) end + + -- Passing an open flag to BeginTabItem() is similar to passing one to Begin(): + -- the returned open value will be false when the tab is closed. if ImGui.BeginTabBar("MyTabBar", s.adv_flags) then for n = 1, 4 do if s.opened[n] then @@ -24956,14 +28725,22 @@ function DemoWindowWidgetsTabs() end if ImGui.TreeNode("TabItemButton & Leading/Trailing flags") then - if s.next_tab_id == 0 then + if s.next_tab_id == 0 then -- Initialize with some default tabs for _ = 1, 3 do s.active_tabs[#s.active_tabs + 1] = s.next_tab_id; s.next_tab_id = s.next_tab_id + 1 end end + + -- TabItemButton() and Leading/Trailing flags are distinct features which we will demo together. + -- (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags... + -- but they tend to make more sense together) _, s.show_leading = ImGui.Checkbox("Show Leading TabItemButton()", s.show_leading) _, s.show_trailing = ImGui.Checkbox("Show Trailing TabItemButton()", s.show_trailing) _, s.show_lt_tabs = ImGui.Checkbox("Show Leading+Trailing TabItem()", s.show_lt_tabs) + + -- Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs s.tib_flags = EditTabBarFittingPolicyFlags(s.tib_flags) + if ImGui.BeginTabBar("MyTabBar", s.tib_flags) then + -- Demo a Leading TabItemButton(): click the "?" button to open a menu if s.show_leading then if ImGui.TabItemButton("?", bit32.bor(TI.Leading, TI.NoTooltip)) then ImGui.OpenPopup("MyHelpMenu") end end @@ -24971,15 +28748,23 @@ function DemoWindowWidgetsTabs() ImGui.Selectable("Hello!") ImGui.EndPopup() end + + -- Demo Leading/Trailing Tabs if s.show_lt_tabs then if ImGui.BeginTabItem("Leading", nil, TI.Leading) then ImGui.EndTabItem() end if ImGui.BeginTabItem("Trailing", nil, TI.Trailing) then ImGui.EndTabItem() end end + + -- Demo Trailing Tabs: click the "+" button to add a new tab. + -- (In your app you may want to use a font icon instead of the "+") + -- We submit it before the regular tabs, but thanks to the ImGuiTabItemFlags.Trailing flag it will always appear at the end. if s.show_trailing then if ImGui.TabItemButton("+", bit32.bor(TI.Trailing, TI.NoTooltip)) then - s.active_tabs[#s.active_tabs + 1] = s.next_tab_id; s.next_tab_id = s.next_tab_id + 1 + s.active_tabs[#s.active_tabs + 1] = s.next_tab_id; s.next_tab_id = s.next_tab_id + 1 -- Add new tab end end + + -- Submit our regular tabs local n = 1 while n <= #s.active_tabs do local name = string.format("%04d", s.active_tabs[n]) @@ -24998,11 +28783,16 @@ function DemoWindowWidgetsTabs() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsText() +------------------------------------------------------------------------------- + S.text = { custom_size = 16.0, custom_scale = 1.0, wrap_width = 200.0, utf8 = Buf("\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e", 32) } function DemoWindowWidgetsText() if not ImGui.TreeNode("Text") then return end local s = S.text if ImGui.TreeNode("Colorful Text") then + -- Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. ImGui.TextColored(ImVec4(1.0, 0.0, 1.0, 1.0), "Pink") ImGui.TextColored(ImVec4(1.0, 1.0, 0.0, 1.0), "Yellow") ImGui.TextDisabled("Disabled") @@ -25015,8 +28805,9 @@ function DemoWindowWidgetsText() local global_scale = style.FontScaleMain * style.FontScaleDpi ImGui.Text("style.FontScaleMain = %0.2f", style.FontScaleMain) ImGui.Text("style.FontScaleDpi = %0.2f", style.FontScaleDpi) - ImGui.Text("global_scale = ~%0.2f", global_scale) + ImGui.Text("global_scale = ~%0.2f", global_scale) -- This is not technically accurate as internal scales may apply, but conceptually let's pretend it is. ImGui.Text("FontSize = %0.2f", ImGui.GetFontSize()) + ImGui.SeparatorText("") s.custom_size = ImGui.SliderFloat("custom_size", s.custom_size, 10.0, 100.0, "%.0f") ImGui.Text("ImGui::PushFont(nullptr, custom_size);") @@ -25041,6 +28832,7 @@ function DemoWindowWidgetsText() end if ImGui.TreeNode("Word Wrapping") then + -- Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. ImGui.TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages.") ImGui.Spacing() s.wrap_width = ImGui.SliderFloat("Wrap width", s.wrap_width, -20, 600, "%.0f") @@ -25056,6 +28848,8 @@ function DemoWindowWidgetsText() else ImGui.Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh") end + + -- Draw actual text bounding box, following by marker of our expected limit (should not overlap!) draw_list:AddRect(ImGui.GetItemRectMin(), ImGui.GetItemRectMax(), IM_COL32(255, 255, 0, 255)) draw_list:AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255)) ImGui.PopTextWrapPos() @@ -25064,6 +28858,12 @@ function DemoWindowWidgetsText() end if ImGui.TreeNode("UTF-8 Text") then + -- UTF-8 test with Japanese characters + -- (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.) + -- - FOR THIS DEMO FILE ONLY, WE ARE *NOT* INCLUDING RAW UTF-8 + -- CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal escapes. + -- Note that characters values are preserved even by InputText() if the font cannot be displayed, + -- so you can safely copy & paste garbled characters into another application. ImGui.TextWrapped("CJK text will only appear if the font was loaded with the appropriate CJK character ranges. Call io.Fonts->AddFontFromFileTTF() manually to load extra character ranges. Read docs/FONTS.md for details.") ImGui.Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)") ImGui.Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)") @@ -25073,9 +28873,15 @@ function DemoWindowWidgetsText() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTextFilter() +------------------------------------------------------------------------------- + S.tf = { filter = nil } function DemoWindowWidgetsTextFilter() if not ImGui.TreeNode("Text Filter") then return end + -- Helper class to easy setup a text filter. + -- You may want to implement a more feature-full filtering scheme in your own application. S.tf.filter = S.tf.filter or ImGuiTextFilter() local filter = S.tf.filter HelpMarker("Not a widget per-se, but ImGuiTextFilter is a helper to perform simple filtering on text strings.") @@ -25094,6 +28900,10 @@ function DemoWindowWidgetsTextFilter() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTextInput() +------------------------------------------------------------------------------- + S.ti = { text = Buf("/*\n The Pentium F00F bug, shorthand for F0 0F C7 C8,\n the hexadecimal encoding of one offending instruction,\n more formally, the invalid operand with locked CMPXCHG8B\n instruction bug, is a design flaw in the majority of\n Intel Pentium, Pentium MMX, and Pentium OverDrive\n processors (all in the P5 microarchitecture).\n*/\n\nlabel:\n\tlock cmpxchg8b eax\n", 1024 * 16), ml_flags = ImGuiInputTextFlags.AllowTabInput, @@ -25110,6 +28920,7 @@ function DemoWindowWidgetsTextInput() if IT[name] then _, s[key] = ImGui.CheckboxFlags("ImGuiInputTextFlags_" .. name, s[key], IT[name]) end end if ImGui.TreeNode("Multi-line Text Input") then + -- WE ARE USING A FIXED-SIZE BUFFER FOR SIMPLICITY HERE. HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type.") FlagBox("ml_flags", "ReadOnly") FlagBox("ml_flags", "WordWrap") @@ -25123,12 +28934,14 @@ function DemoWindowWidgetsTextInput() if ImGui.TreeNode("Filtered Text Input") then local a, z, A, Z = string.byte("a"), string.byte("z"), string.byte("A"), string.byte("Z") + -- Modify character input by altering 'data.EventChar' (ImGuiInputTextFlags.CallbackCharFilter callback) local function FilterCasingSwap(data) local c = data.EventChar - if c >= a and c <= z then data.EventChar = c - (a - A) - elseif c >= A and c <= Z then data.EventChar = c + (a - A) end + if c >= a and c <= z then data.EventChar = c - (a - A) -- Lowercase becomes uppercase + elseif c >= A and c <= Z then data.EventChar = c + (a - A) end -- Uppercase becomes lowercase return 0 end + -- Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i', otherwise return 1 (filter out) local function FilterImGuiLetters(data) local c = data.EventChar if c < 256 and string.find("imgui", string.char(c), 1, true) then return 0 end @@ -25140,8 +28953,8 @@ function DemoWindowWidgetsTextInput() ImGui.InputText("hexadecimal", f[3], 32, bit32.bor(IT.CharsHexadecimal, IT.CharsUppercase)) ImGui.InputText("uppercase", f[4], 32, IT.CharsUppercase) ImGui.InputText("no blank", f[5], 32, IT.CharsNoBlank) - ImGui.InputText("casing swap", f[6], 32, IT.CallbackCharFilter, FilterCasingSwap) - ImGui.InputText("\"imgui\"", f[7], 32, IT.CallbackCharFilter, FilterImGuiLetters) + ImGui.InputText("casing swap", f[6], 32, IT.CallbackCharFilter, FilterCasingSwap) -- Use CharFilter callback to replace characters. + ImGui.InputText("\"imgui\"", f[7], 32, IT.CallbackCharFilter, FilterImGuiLetters) -- Use CharFilter callback to disable some characters. ImGui.TreePop() end @@ -25168,9 +28981,12 @@ function DemoWindowWidgetsTextInput() data:SelectAll() end elseif data.EventFlag == IT.CallbackEdit then + -- Toggle casing of first character local c = data.Buf[1] if (c >= 97 and c <= 122) or (c >= 65 and c <= 90) then data.Buf[1] = bit32.bxor(c, 32) end data.BufDirty = true + + -- Increment a counter local p_int = data.UserData p_int[1] = p_int[1] + 1 end @@ -25210,12 +29026,25 @@ function DemoWindowWidgetsTextInput() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTooltips() +------------------------------------------------------------------------------- + S.tt = { arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }, always_on = 0 } function DemoWindowWidgetsTooltips() if not ImGui.TreeNode("Tooltips") then return end local s = S.tt local HF = ImGuiHoveredFlags + -- Tooltips are windows following the mouse. They do not take focus away. ImGui.SeparatorText("General") + + -- Typical use cases: + -- - Short-form (text only): SetItemTooltip("Hello") + -- - Short-form (any contents): if BeginItemTooltip() then Text("Hello"); EndTooltip() end + + -- - Full-form (text only): if IsItemHovered(...) then SetTooltip("Hello") end + -- - Full-form (any contents): if IsItemHovered(...) and BeginTooltip() then Text("Hello"); EndTooltip() end + HelpMarker("Tooltip are typically created by using a IsItemHovered() + SetTooltip() sequence.\n\nWe provide a helper SetItemTooltip() function to perform the two with standards flags.") local sz = ImVec2(-FLT_MIN, 0.0) ImGui.Button("Basic", sz) @@ -25229,6 +29058,9 @@ function DemoWindowWidgetsTooltips() end ImGui.SeparatorText("Always On") + + -- Showcase NOT relying on a IsItemHovered() to emit a tooltip. + -- Here the tooltip is always emitted when 'always_on == true'. _, s.always_on = ImGui.RadioButton("Off", s.always_on, 0) ImGui.SameLine() _, s.always_on = ImGui.RadioButton("Always On (Simple)", s.always_on, 1) @@ -25243,6 +29075,11 @@ function DemoWindowWidgetsTooltips() ImGui.SeparatorText("Custom") HelpMarker("Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() is the preferred way to standardize tooltip activation details across your application. You may however decide to use custom flags for a specific tooltip instance.") + + -- The following examples are passed for documentation purpose but may not be useful to most users. + -- Passing ImGuiHoveredFlags.ForTooltip to IsItemHovered() will pull ImGuiHoveredFlags flags values from + -- 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on whether mouse or keyboard/gamepad is being used. + -- With default settings, ImGuiHoveredFlags.ForTooltip is equivalent to ImGuiHoveredFlags.DelayShort + ImGuiHoveredFlags.Stationary. ImGui.Button("Manual", sz) if ImGui.IsItemHovered(HF.ForTooltip) then ImGui.SetTooltip("I am a manually emitted tooltip.") end ImGui.Button("DelayNone", sz) @@ -25253,6 +29090,9 @@ function DemoWindowWidgetsTooltips() if ImGui.IsItemHovered(bit32.bor(HF.DelayNormal, HF.NoSharedDelay)) then ImGui.SetTooltip("I am a tooltip with a long delay (%0.2f sec).", ImGui.GetStyle().HoverDelayNormal) end ImGui.Button("Stationary", sz) if ImGui.IsItemHovered(HF.Stationary) then ImGui.SetTooltip("I am a tooltip requiring mouse to be stationary before activating.") end + + -- Using ImGuiHoveredFlags.ForTooltip will pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav', + -- which default value include the ImGuiHoveredFlags.AllowWhenDisabled flag. ImGui.BeginDisabled() ImGui.Button("Disabled item", sz) if ImGui.IsItemHovered(HF.ForTooltip) then ImGui.SetTooltip("I am a tooltip for a disabled item.") end @@ -25260,6 +29100,10 @@ function DemoWindowWidgetsTooltips() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTreeNodes() +------------------------------------------------------------------------------- + S.tn = { lines_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), selection_mask = 0, adv_flags = bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.SpanAvailWidth), align_label = false, use_dnd = false } @@ -25267,9 +29111,16 @@ function DemoWindowWidgetsTreeNodes() if not ImGui.TreeNode("Tree Nodes") then return end local s = S.tn local TN = ImGuiTreeNodeFlags + -- See see "Examples -> Property Editor" (ShowExampleAppPropertyEditor() function) for a fancier, data-driven tree. if ImGui.TreeNode("Basic Trees") then for i = 0, 4 do + -- Use SetNextItemOpen() so set the default state of a node to be open. We could + -- also use TreeNodeEx() with the ImGuiTreeNodeFlags.DefaultOpen flag to achieve the same thing! if i == 0 then ImGui.SetNextItemOpen(true, ImGuiCond.Once) end + + -- Here we use PushID() to generate a unique base ID, and then the "" used as TreeNode id won't conflict. + -- An alternative to using 'PushID() + TreeNode("", ...)' to generate a unique ID is to use 'TreeNode(i, ...)', + -- aka pass a number value to be hashed. The demo below uses that technique. Both are fine. ImGui.PushID(i) if ImGui.TreeNode("", "Child %d", i) then ImGui.Text("blah blah") @@ -25305,8 +29156,18 @@ function DemoWindowWidgetsTreeNodes() if ImGui.TreeNode("Selectable Nodes") then HelpMarker("Manually implemented selectable nodes.\nClick to select, Ctrl+Click to toggle, click on arrows or double-click to open.") + + -- Hold in 'selection_mask' a simple representation of what may be user-side selection state. + -- - You may retain selection state inside or outside your objects in whatever format you see fit. + -- You may use ImGuiSelectionBasicStorage which is conceptually close to a set<> of identifiers. + -- - We record which node was clicked and then apply selection at the end of the loop. + -- - This is a manual and simplified reimplementation of multi-selection, which the full + -- BeginMultiSelect() API implements better, but which is not trivial to wire for trees. local node_clicked_idx = -1 for node_n = 0, 5 do + -- Disable the default "open on single-click behavior" + set Selected flag according to our selection. + -- To alter selection we use if 'IsItemClicked() and not IsItemToggledOpen()', so clicking on an arrow doesn't alter selection. + -- In a BeginMultiSelect()/EndMultiSelect() we could use IsItemToggledSelection() but here we reimplement and use our own logic. local flags = bit32.bor(TN.OpenOnArrow, TN.OpenOnDoubleClick, TN.SpanAvailWidth) if bit32.band(s.selection_mask, bit32.lshift(1, node_n)) ~= 0 then flags = bit32.bor(flags, TN.Selected) end local is_open = ImGui.TreeNodeEx(node_n, flags, "Selectable Node %d", node_n) @@ -25317,10 +29178,11 @@ function DemoWindowWidgetsTreeNodes() end end if node_clicked_idx ~= -1 then + -- Update selection state (process outside of tree loop to avoid visual inconsistencies during the clicking frame) if ImGui.GetIO().KeyCtrl then - s.selection_mask = bit32.bxor(s.selection_mask, bit32.lshift(1, node_clicked_idx)) - else - s.selection_mask = bit32.lshift(1, node_clicked_idx) + s.selection_mask = bit32.bxor(s.selection_mask, bit32.lshift(1, node_clicked_idx)) -- Ctrl+Click to toggle + else -- if not (selection_mask & (1 << node_clicked_idx)) -- Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection + s.selection_mask = bit32.lshift(1, node_clicked_idx) -- Click to single-select end end ImGui.TreePop() @@ -25347,6 +29209,7 @@ function DemoWindowWidgetsTreeNodes() for node_n = 0, 5 do local node_flags = s.adv_flags if node_n < 3 then + -- Items 0..2 are Tree Node local is_open = ImGui.TreeNodeEx(node_n, node_flags, "Selectable Node %d", node_n) if s.use_dnd and ImGui.BeginDragDropSource() then ImGui.SetDragDropPayload("MY_TREENODE_PAYLOAD_TYPE", nil, 0) @@ -25354,6 +29217,7 @@ function DemoWindowWidgetsTreeNodes() ImGui.EndDragDropSource() end if node_n == 2 and bit32.band(s.adv_flags, TN.SpanLabelWidth) ~= 0 then + -- Item 2 has an additional inline button to help demonstrate SpanLabelWidth. ImGui.SameLine() if ImGui.SmallButton("button") then end end @@ -25364,7 +29228,10 @@ function DemoWindowWidgetsTreeNodes() ImGui.TreePop() end else - node_flags = bit32.bor(node_flags, TN.Leaf, TN.NoTreePushOnOpen) + -- Items 3..5 are Tree Leaves + -- The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can + -- use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). + node_flags = bit32.bor(node_flags, TN.Leaf, TN.NoTreePushOnOpen) -- ImGuiTreeNodeFlags.Bullet ImGui.TreeNodeEx(node_n, node_flags, "Selectable Leaf %d", node_n) if s.use_dnd and ImGui.BeginDragDropSource() then ImGui.SetDragDropPayload("MY_TREENODE_PAYLOAD_TYPE", nil, 0) @@ -25379,6 +29246,10 @@ function DemoWindowWidgetsTreeNodes() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsVerticalSliders() +------------------------------------------------------------------------------- + S.vs = { int_value = 0, values = { 0.0, 0.60, 0.35, 0.9, 0.70, 0.20, 0.0 }, values2 = { 0.20, 0.80, 0.40, 0.25 } } function DemoWindowWidgetsVerticalSliders() if not ImGui.TreeNode("Vertical Sliders") then return end @@ -25435,11 +29306,16 @@ function DemoWindowWidgetsVerticalSliders() ImGui.TreePop() end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - ShowExampleAppMainMenuBar() +-- - ShowExampleMenuFile() +------------------------------------------------------------------------------- S.menu = { enabled = true, f = 0.5, n = 0, b = true } +-- Note that shortcuts are currently provided for display only +-- (future version will add explicit flags to BeginMenu() to request processing shortcuts) function ShowExampleMenuFile() local s = S.menu ImGui.MenuItem("(demo menu)", nil, false, false) @@ -25489,12 +29365,14 @@ function ShowExampleMenuFile() end -- Here we demonstrate appending again to the "Options" menu (which we already created above) - if ImGui.BeginMenu("Options") then + -- Of course in this demo it is a little bit silly that this function calls BeginMenu("Options") twice. + -- In a real code-base using it would make senses to use this feature from very different code locations. + if ImGui.BeginMenu("Options") then -- <-- Append! _, s.b = ImGui.Checkbox("SomeOption", s.b) ImGui.EndMenu() end - if ImGui.BeginMenu("Disabled", false) then + if ImGui.BeginMenu("Disabled", false) then -- Disabled IM_ASSERT(false) end if ImGui.MenuItem("Checked", nil, true) then end @@ -25502,6 +29380,10 @@ function ShowExampleMenuFile() if ImGui.MenuItem("Quit", "Alt+F4") then end end +-- Demonstrate creating a "main" fullscreen menu bar and populating it. +-- Note the difference between BeginMainMenuBar() and BeginMenuBar(): +-- - BeginMenuBar() = menu-bar inside current window (which needs the ImGuiWindowFlags.MenuBar flag!) +-- - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it. function ShowExampleAppMainMenuBar() if ImGui.BeginMainMenuBar() then if ImGui.BeginMenu("File") then @@ -25510,7 +29392,7 @@ function ShowExampleAppMainMenuBar() end if ImGui.BeginMenu("Edit") then if ImGui.MenuItem("Undo", "Ctrl+Z") then end - if ImGui.MenuItem("Redo", "Ctrl+Y", false, false) then end + if ImGui.MenuItem("Redo", "Ctrl+Y", false, false) then end -- Disabled item ImGui.Separator() if ImGui.MenuItem("Cut", "Ctrl+X") then end if ImGui.MenuItem("Copy", "Ctrl+C") then end @@ -25521,9 +29403,12 @@ function ShowExampleAppMainMenuBar() end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Style Editor / ShowStyleEditor() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - ShowStyleSelector() +-- - ShowStyleEditor() +------------------------------------------------------------------------------- -- Deep copy of an ImGuiStyle (ImVec2/ImVec4 fields and Colors[] are copied by value) local function StyleCopy(dst, src) @@ -25548,7 +29433,10 @@ end local function ColorsEqual(a, b) return a[1] == b[1] and a[2] == b[2] and a[3] == b[3] and a[4] == b[4] end S.ss = { style_idx = -1 } +-- Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. function ImGui.ShowStyleSelector(label) + -- FIXME: This is a bit tricky to get right as style are functions, they don't register a name nor the fact that one is active. + -- So we keep track of last active one among our limited selection. local s = S.ss local style_names = { "Dark", "Light", "Classic" } local ret = false @@ -25577,13 +29465,19 @@ end S.se = { ref_saved_style = nil, init = true, output_dest = 0, output_only_modified = true, alpha_flags = 0, filter = nil } function ImGui.ShowStyleEditor(ref) + -- You can pass in a reference ImGuiStyle structure to compare to, revert to and save to + -- (without a reference style, we will use one compared locally as a reference) local se = S.se local style = ImGui.GetStyle() if se.ref_saved_style == nil then se.ref_saved_style = {} end + + -- Default to using internal storage as reference if se.init and ref == nil then StyleCopy(se.ref_saved_style, style) end se.init = false if ref == nil then ref = se.ref_saved_style end + -- The logic behind dynamically changing 'max_border_size' is to not encourage people to increase border size too much: it'll likely reveal lots of subtle rendering artifacts and this isn't a priority right now. + -- Note that _MainScale is currently internal PLEASE DO NOT USE IN YOUR CODE. local default_border_size = math.floor(style._MainScale or 1.0) local max_border_size = math.max(default_border_size, 2.0) local function SF(name, mn, mx, fmt) if style[name] ~= nil then style[name] = ImGui.SliderFloat(name, style[name], mn, mx, fmt or "%.0f") end end @@ -25592,6 +29486,7 @@ function ImGui.ShowStyleEditor(ref) ImGui.PushItemWidth(ImGui.GetWindowWidth() * 0.50) + -- General ImGui.SeparatorText("General") if bit32.band(ImGui.GetIO().BackendFlags, ImGuiBackendFlags.RendererHasTextures) == 0 then ImGui.BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!") @@ -25603,7 +29498,7 @@ function ImGui.ShowStyleEditor(ref) if ImGui.ShowFontSelector then ImGui.ShowFontSelector("Fonts##Selector") end local changed style.FontSizeBase, changed = ImGui.DragFloat("FontSizeBase", style.FontSizeBase, 0.20, 5.0, 100.0, "%.0f") - if changed then style._NextFrameFontSizeBase = style.FontSizeBase end + if changed then style._NextFrameFontSizeBase = style.FontSizeBase end -- FIXME: Temporary hack until we finish remaining work. ImGui.SameLine(0.0, 0.0); ImGui.Text(" (out %.2f)", ImGui.GetFontSize()) style.FontScaleMain = ImGui.DragFloat("FontScaleMain", style.FontScaleMain, 0.02, 0.5, 4.0) ImGui.BeginDisabled(ImGui.GetIO().ConfigDpiScaleFonts == true) @@ -25611,8 +29506,9 @@ function ImGui.ShowStyleEditor(ref) ImGui.SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten.") ImGui.EndDisabled() + -- Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0 or 1.0) style.FrameRounding, changed = ImGui.SliderFloat("FrameRounding", style.FrameRounding, 0.0, 12.0, "%.0f") - if changed then style.GrabRounding = style.FrameRounding end + if changed then style.GrabRounding = style.FrameRounding end -- Make GrabRounding always the same value as FrameRounding local p, border p, border = ImGui.Checkbox("WindowBorder", style.WindowBorderSize > 0.0); if p then style.WindowBorderSize = border and default_border_size or 0.0 end ImGui.SameLine() @@ -25620,6 +29516,7 @@ function ImGui.ShowStyleEditor(ref) ImGui.SameLine() p, border = ImGui.Checkbox("PopupBorder", style.PopupBorderSize > 0.0); if p then style.PopupBorderSize = border and default_border_size or 0.0 end + -- Save/Revert button if ImGui.Button("Save Ref") then StyleCopy(se.ref_saved_style, style); if ref ~= se.ref_saved_style then StyleCopy(ref, style) end end ImGui.SameLine() if ImGui.Button("Revert Ref") then StyleCopy(style, ref) end @@ -25641,6 +29538,7 @@ function ImGui.ShowStyleEditor(ref) ImGui.SeparatorText("Rounding") SF("WindowRounding", 0.0, 12.0); SF("ChildRounding", 0.0, 12.0); SF("FrameRounding", 0.0, 12.0) SF("PopupRounding", 0.0, 12.0); SF("GrabRounding", 0.0, 12.0); SF("MenuItemRounding", 0.0, 12.0) + -- NB: SelectableRounding is intentionally NOT made visible here. We don't want to encourage people using that. ImGui.SeparatorText("Scrollbar") SF("ScrollbarSize", 1.0, 20.0); SF("ScrollbarRounding", 0.0, 12.0); SF("ScrollbarPadding", 0.0, 10.0) @@ -25692,6 +29590,7 @@ function ImGui.ShowStyleEditor(ref) SF("LogSliderDeadzone", 0.0, 12.0); SF("ImageRounding", 0.0, 12.0); SF("ImageBorderSize", 0.0, max_border_size) ImGui.SeparatorText("Docking") + -- SetCursorPosX(GetCursorPosX() + CalcItemWidth() - GetFrameHeight()) _, style.DockingNodeHasCloseButton = ImGui.Checkbox("DockingNodeHasCloseButton", style.DockingNodeHasCloseButton) SF("DockingSeparatorSize", 0.0, 12.0) @@ -25761,6 +29660,9 @@ function ImGui.ShowStyleEditor(ref) end ImGui.ColorEdit4("##color", style.Colors[i], bit32.bor(CE.AlphaBar, se.alpha_flags)) if not ColorsEqual(style.Colors[i], ref.Colors[i]) then + -- Tips: in a real user application, you may want to merge and use an icon font into the main font, + -- so instead of "Save"/"Revert" you'd use icons! + -- Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient! ImGui.SameLine(0.0, style.ItemInnerSpacing.x); if ImGui.Button("Save") then ImVec4_Copy(ref.Colors[i], style.Colors[i]) end ImGui.SameLine(0.0, style.ItemInnerSpacing.x); if ImGui.Button("Revert") then ImVec4_Copy(style.Colors[i], ref.Colors[i]) end end @@ -25797,6 +29699,7 @@ function ImGui.ShowStyleEditor(ref) if curve_err < 0.10 then curve_err = 0.10 end style.CurveTessellationTol = curve_err * curve_err + -- When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles. style.CircleTessellationMaxError = ImGui.DragFloat("Circle Tessellation Max Error", style.CircleTessellationMaxError, 0.005, 0.10, 5.0, "%.2f", ImGuiSliderFlags.AlwaysClamp) local show_samples = ImGui.IsItemActive() if show_samples then ImGui.SetNextWindowPos(ImGui.GetCursorScreenPos()) end @@ -25809,6 +29712,8 @@ function ImGui.ShowStyleEditor(ref) local RAD_MIN, RAD_MAX = 5.0, 70.0 local rad = RAD_MIN + (RAD_MAX - RAD_MIN) * n / (8.0 - 1.0) ImGui.BeginGroup() + + -- N is not always exact here due to how PathArcTo() function work internally ImGui.Text("R: %.f\nN: %d", rad, draw_list:_CalcCircleAutoSegmentCount(rad)) local canvas_width = math.max(min_widget_width, rad * 2.0) local offset_x = math.floor(canvas_width * 0.5) @@ -25816,6 +29721,11 @@ function ImGui.ShowStyleEditor(ref) local p1 = ImGui.GetCursorScreenPos() draw_list:AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, ImGui.GetColorU32(ImGuiCol.Text)) ImGui.Dummy(ImVec2(canvas_width, RAD_MAX * 2)) + + -- local p2 = ImGui.GetCursorScreenPos() + -- draw_list:AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, ImGui.GetColorU32(ImGuiCol.Text)) + -- ImGui.Dummy(ImVec2(canvas_width, RAD_MAX * 2)) + ImGui.EndGroup() ImGui.SameLine() end @@ -25823,7 +29733,7 @@ function ImGui.ShowStyleEditor(ref) end ImGui.SameLine() HelpMarker("When drawing circle primitives with \"num_segments == 0\" tessellation will be calculated automatically.") - style.Alpha = ImGui.DragFloat("Global Alpha", style.Alpha, 0.005, 0.20, 1.0, "%.2f") + style.Alpha = ImGui.DragFloat("Global Alpha", style.Alpha, 0.005, 0.20, 1.0, "%.2f") -- Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. style.DisabledAlpha = ImGui.DragFloat("Disabled Alpha", style.DisabledAlpha, 0.005, 0.0, 1.0, "%.2f") ImGui.SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha).") ImGui.PopItemWidth() @@ -25839,9 +29749,10 @@ do --[[ About window ]] -- Demo tools: ShowAboutWindow(), ShowFontAtlas(), ShowFontSelector(), ShowDebugLogWindow(), ShowIDStackToolWindow() local _ ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] About Window / ShowAboutWindow() ----------------------------------------------------------------- +-- Access from Dear ImGui Demo -> Tools -> About +------------------------------------------------------------------------------- local show_config_info = false function ImGui.ShowAboutWindow(p_open) @@ -25872,7 +29783,7 @@ function ImGui.ShowAboutWindow(p_open) if copy_to_clipboard then ImGui.LogToClipboard() ImGui.LogText("// (Copy from the next line. Keep the ``` markers for formatting.)\n") - ImGui.LogText("```cpp\n") + ImGui.LogText("```cpp\n") -- Back quotes will make text appears without formatting when pasting on GitHub end ImGui.Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM) ImGui.Separator() @@ -25930,12 +29841,34 @@ end __FILES['imgui_draw.lua'] = function() --- Dear ImGui WIP --- (Draw Code) +-- (drawing and font code) -FONT_ATLAS_DEFAULT_TEX_DATA_W = 122 +-- +-- Index of this file: +-- +-- [SECTION] STB libraries implementation +-- [SECTION] Style functions +-- [SECTION] ImDrawList +-- [SECTION] ImTriangulator, ImDrawList concave polygon fill +-- [SECTION] ImDrawListSplitter +-- [SECTION] ImDrawData +-- [SECTION] Helpers ShadeVertsXXX functions +-- [SECTION] ImFontConfig +-- [SECTION] ImFontAtlas, ImFontAtlasBuilder +-- [SECTION] ImFontAtlas: backend for stb_truetype +-- [SECTION] ImFontAtlas: glyph ranges helpers +-- [SECTION] ImFontGlyphRangesBuilder +-- [SECTION] ImFontBaked, ImFont +-- [SECTION] ImGui Internal Render Helpers +-- [SECTION] Decompression code +-- [SECTION] Default font data (ProggyClean.ttf) +-- [SECTION] Default font data (ProggyForever.ttf) +-- + +FONT_ATLAS_DEFAULT_TEX_DATA_W = 122 -- Actual texture will be 2 times that + 1 spacing. FONT_ATLAS_DEFAULT_TEX_DATA_H = 27 -local IM_DRAWLIST_TEX_LINES_WIDTH_MAX = 32 +local IM_DRAWLIST_TEX_LINES_WIDTH_MAX = 32 -- The maximum line width to bake anti-aliased textures for. local writef64, writeu32, readf64, readu32 = buffer.writef64, buffer.writeu32, buffer.readf64, buffer.readu32 -- Write vertex i (1-based) of a VtxBuffer.Buf @@ -25945,8 +29878,8 @@ local function WV(b, i, x, y, u, v, col) end local function WVP(b, i, p, uv, col) WV(b, i, p.x, p.y, uv.x, uv.y, col) end -local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE +local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- ((ImU16)-1) +local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE -- ((ImU16)-2) --- @param str string --- @return table @@ -25966,7 +29899,9 @@ local function write_u32(buf, base, u32) buf[base + 3] = bit32.band(bit32.rshift(u32, 24), 0xFF) end ---- Original ImGui pixel art! +-- A work of art lies ahead! (. = white layer, X = black layer, others are blank) +-- The 2x2 white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes. +-- (This is used when io.MouseDrawCursor = true) local FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS = str_to_table( "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX - XX XX " .. "..- -X.....X- X.X - X.X -X.....X - X.....X- X..X -X..X X..X" .. @@ -26014,15 +29949,19 @@ local FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA = { local MT = ImGui.GetMetatables() +------------------------------------------------------------------------------- +-- [SECTION] STB libraries implementation (for stb_truetype and stb_rect_pack) +------------------------------------------------------------------------------- + --- @module "imstb_rectpack" local stbrp = IM_INCLUDE("imstb_rectpack.lua") --- @module "imstb_truetype" local stbtt = IM_INCLUDE("imstb_truetype.lua") ---------------------------------------------------------------------------------------- --- [SECTION] STYLE FUNCTIONS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Style functions +------------------------------------------------------------------------------- --- @param a ImVec4 --- @param b ImVec4 @@ -26083,8 +30022,8 @@ function ImGui.StyleColorsDark(dst) colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00) colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00) colors[ImGuiCol.TableHeaderBg] = ImVec4(0.19, 0.19, 0.20, 1.00) - colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.35, 1.00) - colors[ImGuiCol.TableBorderLight] = ImVec4(0.23, 0.23, 0.25, 1.00) + colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.35, 1.00) -- Prefer using Alpha=1.0 here + colors[ImGuiCol.TableBorderLight] = ImVec4(0.23, 0.23, 0.25, 1.00) -- Prefer using Alpha=1.0 here colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00) colors[ImGuiCol.TableRowBgAlt] = ImVec4(1.00, 1.00, 1.00, 0.06) colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive] @@ -26153,8 +30092,8 @@ function ImGui.StyleColorsClassic(dst) colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00) colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00) colors[ImGuiCol.TableHeaderBg] = ImVec4(0.27, 0.27, 0.38, 1.00) - colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.45, 1.00) - colors[ImGuiCol.TableBorderLight] = ImVec4(0.26, 0.26, 0.28, 1.00) + colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.45, 1.00) -- Prefer using Alpha=1.0 here + colors[ImGuiCol.TableBorderLight] = ImVec4(0.26, 0.26, 0.28, 1.00) -- Prefer using Alpha=1.0 here colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00) colors[ImGuiCol.TableRowBgAlt] = ImVec4(1.00, 1.00, 1.00, 0.07) colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive] @@ -26224,8 +30163,8 @@ function ImGui.StyleColorsLight(dst) colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00) colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.45, 0.00, 1.00) colors[ImGuiCol.TableHeaderBg] = ImVec4(0.78, 0.87, 0.98, 1.00) - colors[ImGuiCol.TableBorderStrong] = ImVec4(0.57, 0.57, 0.64, 1.00) - colors[ImGuiCol.TableBorderLight] = ImVec4(0.68, 0.68, 0.74, 1.00) + colors[ImGuiCol.TableBorderStrong] = ImVec4(0.57, 0.57, 0.64, 1.00) -- Prefer using Alpha=1.0 here + colors[ImGuiCol.TableBorderLight] = ImVec4(0.68, 0.68, 0.74, 1.00) -- Prefer using Alpha=1.0 here colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00) colors[ImGuiCol.TableRowBgAlt] = ImVec4(0.30, 0.30, 0.30, 0.09) colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive] @@ -26240,6 +30179,11 @@ function ImGui.StyleColorsLight(dst) colors[ImGuiCol.ModalWindowDimBg] = ImVec4(0.20, 0.20, 0.20, 0.35) end +------------------------------------------------------------------------------- +-- [SECTION] Helpers ShadeVertsXXX functions +------------------------------------------------------------------------------- + +-- Generic linear color gradient, write to RGB fields, leave A untouched. --- @param draw_list ImDrawList --- @param vert_start_idx int --- @param vert_end_idx int @@ -26372,10 +30316,102 @@ local ImTextClassifierSetCharClassFromStr local ImTextureDataGetFormatBytesPerPixel +------------------------------------------------------------------------------- +-- [SECTION] ImFontAtlas, ImFontAtlasBuilder +------------------------------------------------------------------------------- +-- - Default texture data encoded in ASCII +-- - ImFontAtlas() +-- - ImFontAtlas:Clear() +-- - ImFontAtlas:ClearFonts() +-- - ImFontAtlas:ClearInputData() +-- - ImFontAtlas:ClearTexData() +-- - ImFontAtlas:CompactCache() +-- - ImFontAtlas:SetFontLoader() +------------------------------------------------------------------------------- +-- - ImFontAtlasUpdateNewFrame() +-- - ImFontAtlasTextureBlockConvert() +-- - ImFontAtlasTextureBlockPostProcess() +-- - ImFontAtlasTextureBlockPostProcessMultiply() +-- - ImFontAtlasTextureBlockFill() +-- - ImFontAtlasTextureBlockCopy() +-- - ImFontAtlasTextureBlockQueueUpload() +------------------------------------------------------------------------------- +-- - ImFontAtlas:GetTexDataAsAlpha8() [legacy] +-- - ImFontAtlas:GetTexDataAsRGBA32() [legacy] +-- - ImFontAtlas:Build() [legacy] +------------------------------------------------------------------------------- +-- - ImFontAtlas:AddFont() +-- - ImFontAtlas:AddFontDefault() +-- - ImFontAtlas:AddFontDefaultBitmap() +-- - ImFontAtlas:AddFontDefaultVector() +-- - ImFontAtlas:AddFontFromFileTTF() +-- - ImFontAtlas:AddFontFromMemoryTTF() +-- - ImFontAtlas:AddFontFromMemoryCompressedTTF() +-- - ImFontAtlas:AddFontFromMemoryCompressedBase85TTF() +-- - ImFontAtlas:RemoveFont() +-- - ImFontAtlasBuildNotifySetFont() +------------------------------------------------------------------------------- +-- - ImFontAtlas:AddCustomRect() +-- - ImFontAtlas:RemoveCustomRect() +-- - ImFontAtlas:GetCustomRect() +-- - ImFontAtlas:AddCustomRectFontGlyph() [legacy] +-- - ImFontAtlas:AddCustomRectFontGlyphForSize() [legacy] +-- - ImFontAtlasGetMouseCursorTexData() +------------------------------------------------------------------------------- +-- - ImFontAtlasBuildMain() +-- - ImFontAtlasBuildSetupFontLoader() +-- - ImFontAtlasBuildPreloadAllGlyphRanges() +-- - ImFontAtlasBuildUpdatePointers() +-- - ImFontAtlasBuildRenderBitmapFromString() +-- - ImFontAtlasBuildAddFont() +-- - ImFontAtlasBuildSetupFontBakedEllipsis() +-- - ImFontAtlasBuildSetupFontBakedBlanks() +-- - ImFontAtlasBuildSetupFontBakedFallback() +-- - ImFontAtlasBuildSetupFontSpecialGlyphs() +-- - ImFontAtlasBuildDiscardBakes() +-- - ImFontAtlasBuildDiscardFontBakedGlyph() +-- - ImFontAtlasBuildDiscardFontBaked() +-- - ImFontAtlasBuildDiscardFontBakes() +------------------------------------------------------------------------------- +-- - ImFontAtlasAddDrawListSharedData() +-- - ImFontAtlasRemoveDrawListSharedData() +-- - ImFontAtlasUpdateDrawListsTextures() +-- - ImFontAtlasUpdateDrawListsSharedData() +------------------------------------------------------------------------------- +-- - ImFontAtlasBuildSetTexture() +-- - ImFontAtlasBuildUpdateTexData() +-- - ImFontAtlasTextureAdd() +-- - ImFontAtlasTextureRepack() +-- - ImFontAtlasTextureGrow() +-- - ImFontAtlasTextureMakeSpace() +-- - ImFontAtlasTextureGetSizeEstimate() +-- - ImFontAtlasBuildClear() +-- - ImFontAtlasTextureCompact() +-- - ImFontAtlasBuildInit() +-- - ImFontAtlasBuildDestroy() +------------------------------------------------------------------------------- +-- - ImFontAtlasPackInit() +-- - ImFontAtlasPackAllocRectEntry() +-- - ImFontAtlasPackReuseRectEntry() +-- - ImFontAtlasPackDiscardRect() +-- - ImFontAtlasPackAddRect() +-- - ImFontAtlasPackGetRect() +------------------------------------------------------------------------------- +-- - ImFontBaked_BuildGrowIndex() +-- - ImFontBaked_BuildLoadGlyph() +-- - ImFontBaked_BuildLoadGlyphAdvanceX() +-- - ImFontAtlasDebugLogTextureRequests() +------------------------------------------------------------------------------- +-- - ImFontAtlasGetFontLoaderForStbTruetype() +------------------------------------------------------------------------------- + +-- You probably should not call this directly. It is not well specified. +-- If you want to replace all your fonts mid-frame, most likely you should instead call ClearFonts() then load the new fonts. +-- Calling this mid-frame will discard the CPU-side copy of the texture data which is generally unreliable as you may have textures queued for creation or updates. function MT.ImFontAtlas:Clear() IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlas:Clear()") local backup_renderer_has_textures = self.RendererHasTextures - self.RendererHasTextures = false + self.RendererHasTextures = false -- Full Clear() is supported, but ClearTexData() only isn't. self:ClearFonts() self:ClearTexData() self.RendererHasTextures = backup_renderer_has_textures @@ -26395,12 +30431,14 @@ function MT.ImFontAtlas:ClearInputData() ImFontAtlasFontDestroySourceData(self, font_cfg) end for _, font in self.Fonts:iter() do + -- When clearing this we lose access to the font name and other information used to build the font. font.Sources:clear() font.Flags = bit32.bor(font.Flags, ImFontFlags.NoLoadGlyphs) end self.Sources:clear() end +-- Clear CPU-side copy of the texture data. function MT.ImFontAtlas:ClearTexData() IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") IM_ASSERT(self.RendererHasTextures == false, "Not supported for dynamic atlases, but you may call Clear().") @@ -26408,6 +30446,7 @@ function MT.ImFontAtlas:ClearTexData() for _, tex in self.TexList:iter() do tex:DestroyPixels() end + --self.Locked = true -- Hoped to be able to lock this down but some reload patterns may not be happy with it. end function MT.ImFontAtlas:CompactCache() @@ -26415,6 +30454,7 @@ function MT.ImFontAtlas:CompactCache() end function MT.ImFontAtlas:ClearFonts() + -- FIXME-NEWATLAS: Illegal to remove currently bound font. IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlas:ClearFonts()") IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") @@ -26445,25 +30485,34 @@ function ImTextureDataUpdateNewFrame(tex) tex.UpdateRect.w = 0 tex.UpdateRect.h = 0 end + -- 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. if (tex.WantDestroyNextFrame and tex.Status ~= ImTextureStatus.Destroyed and tex.Status ~= ImTextureStatus.WantDestroy) then IM_ASSERT(tex.Status == ImTextureStatus.OK or tex.Status == ImTextureStatus.WantCreate or tex.Status == ImTextureStatus.WantUpdates) tex.Status = ImTextureStatus.WantDestroy end + -- If a texture has never reached the backend, they don't need to know about it. + -- (note: backends between 1.92.0 and 1.92.4 could set an already destroyed texture to ImTextureStatus.WantDestroy + -- when invalidating graphics objects twice, which would previously remove it from the list and crash.) if (tex.Status == ImTextureStatus.WantDestroy and tex.TexID == ImTextureID_Invalid and tex.BackendUserData == nil and tex.QueueUserData == nil) then tex.Status = ImTextureStatus.Destroyed end + -- Process texture being destroyed if (tex.Status == ImTextureStatus.Destroyed) then IM_ASSERT(tex.TexID == ImTextureID_Invalid and tex.BackendUserData == nil, "Backend set texture Status to Destroyed but did not clear TexID/BackendUserData!") IM_ASSERT(tex.QueueUserData == nil, "Texture queue set Status to Destroyed but did not clear QueueUserData!") if (tex.WantDestroyNextFrame) then - remove_from_list = true + remove_from_list = true -- Destroy was scheduled by us else - tex.Status = ImTextureStatus.WantCreate + tex.Status = ImTextureStatus.WantCreate -- Destroy was done was backend: recreate it (e.g. freed resources mid-run) end end + -- 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) then tex.UnusedFrames = tex.UnusedFrames + 1 end @@ -26471,15 +30520,24 @@ function ImTextureDataUpdateNewFrame(tex) return remove_from_list end +-- 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. --- @param atlas ImFontAtlas --- @param frame_count int --- @param renderer_has_textures any function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures) - IM_ASSERT(atlas.Builder == nil or atlas.Builder.FrameCount < frame_count) + IM_ASSERT(atlas.Builder == nil or atlas.Builder.FrameCount < frame_count) -- Protection against being called twice. atlas.RendererHasTextures = renderer_has_textures + -- Update texture status and discard old textures. + -- (we do this first thing to handle an edge case: if user mistakenly calls ClearFonts()+SetStatus(OK) during + -- rendering, it would ImFontAtlasBuildMain() rebuilding before tex.Updates[] gets a chance to be cleared) + -- (if somehow we need to move this back lower in the function, we could manually call the code to clear Updates[]). local tex_n = 1 while tex_n <= atlas.TexList.Size do + -- Update and remove if requested local tex = atlas.TexList.Data[tex_n] if (tex.Status == ImTextureStatus.WantCreate and atlas.RendererHasTextures) then @@ -26498,13 +30556,14 @@ function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures) tex_n = tex_n + 1 end + -- Check that font atlas was built or backend support texture reload in which case we can build now if (atlas.RendererHasTextures) then atlas.TexIsBuilt = true - if (atlas.Builder == nil) then + if (atlas.Builder == nil) then -- This will only happen if fonts were not already loaded. ImFontAtlasBuildMain(atlas) end end - + -- Legacy backend if (not atlas.RendererHasTextures) then 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().") end @@ -26512,12 +30571,15 @@ function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures) 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().") end + -- Clear BakedCurrent cache, this is important because it ensure the uncached path gets taken once. + -- We also rely on ImFontBaked pointers never crossing frames. local builder = atlas.Builder builder.FrameCount = frame_count for _, font in atlas.Fonts:iter() do font.LastBaked = nil end + -- Garbage collect BakedPool if builder.BakedDiscardedCount > 0 then local dst_n = 1 @@ -26598,8 +30660,11 @@ function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixe end end +-- Source buffer may be written to (used for in-place mods). +-- Post-process hooks may eventually be added here. --- @param data ImFontAtlasPostProcessData function ImFontAtlasTextureBlockPostProcess(data) + -- Multiply operator (legacy) if data.FontSrc.RasterizerMultiply ~= 1.0 then ImFontAtlasTextureBlockPostProcessMultiply(data, data.FontSrc.RasterizerMultiply) end @@ -26640,6 +30705,7 @@ function ImFontAtlasTextureBlockPostProcessMultiply(data, multiply_factor) end end +-- Copy block from one texture to another --- @param src_tex ImTextureData --- @param src_x int --- @param src_y int @@ -26662,6 +30728,7 @@ function ImFontAtlasTextureBlockCopy(src_tex, src_x, src_y, dst_tex, dst_x, dst_ end end +-- Queue texture block update for renderer backend --- @param tex ImTextureData --- @param x int --- @param y int @@ -26683,6 +30750,7 @@ local function ImTextureDataQueueUpload(tex, x, y, w, h) tex.UsedRect.w = (ImMax(tex.UsedRect.x + tex.UsedRect.w, req.x + req.w) - tex.UsedRect.x) -- (unsigned short) tex.UsedRect.h = (ImMax(tex.UsedRect.y + tex.UsedRect.h, req.y + req.h) - tex.UsedRect.y) -- (unsigned short) + -- No need to queue if status is == ImTextureStatus.WantCreate if (tex.Status == ImTextureStatus.OK or tex.Status == ImTextureStatus.WantUpdates) then tex.Status = ImTextureStatus.WantUpdates tex.Updates:push_back(req) @@ -26700,6 +30768,7 @@ function ImFontAtlasTextureBlockQueueUpload(atlas, tex, x, y, w, h) atlas.TexIsBuilt = false end +-- Copy to texture, post-process and queue update for backend --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @param src ImFontConfig @@ -26720,6 +30789,8 @@ local function ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, glyph, r, s end local function ImFontAtlasBuildGetOversampleFactors(src, baked) + -- (Only used by stb_truetype builder) + -- Automatically disable horizontal oversampling over size 36 local raster_size = baked.Size * baked.RasterizerDensity * src.RasterizerDensity local out_oversample_h if src.OversampleH ~= 0 then @@ -26733,6 +30804,7 @@ local function ImFontAtlasBuildGetOversampleFactors(src, baked) return out_oversample_h, out_oversample_v end +-- use unused_frames==0 to discard everything. local function ImFontAtlasBuildDiscardBakes(atlas, unused_frames) local builder = atlas.Builder @@ -26753,6 +30825,7 @@ local function ImFontAtlasBuildDiscardBakes(atlas, unused_frames) end end +-- Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData --- @param atlas ImFontAtlas --- @param data ImDrawListSharedData function ImFontAtlasAddDrawListSharedData(atlas, data) @@ -26779,7 +30852,16 @@ local function ImFontAtlasTextureRepack(atlas, w, h) new_tex.UseColors = old_tex.UseColors IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d", old_tex.UniqueID, old_tex.Width, old_tex.Height, new_tex.UniqueID, new_tex.Width, new_tex.Height) + --for baked_n = 1, builder.BakedPool.Size do + -- IMGUI_DEBUG_LOG_FONT("[font] - Baked %.2fpx, %d glyphs, want_destroy=%d", builder.BakedPool[baked_n].FontSize, builder.BakedPool[baked_n].Glyphs.Size, builder.BakedPool[baked_n].WantDestroy) + --end + --IMGUI_DEBUG_LOG_FONT("[font] - Old packed rects: %d, area %d px", 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) local old_rects = ImVector() local old_index = builder.RectsIndex:copy() @@ -26798,13 +30880,15 @@ local function ImFontAtlasTextureRepack(atlas, w, h) local new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, index_entry) if new_r_id == ImFontAtlasRectId_Invalid then + -- 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.", new_tex.UniqueID) new_tex.WantDestroyNextFrame = true builder.Rects:swap(old_rects) builder.RectsIndex = old_index ImFontAtlasBuildSetTexture(atlas, old_tex) - ImFontAtlasTextureGrow(atlas, w, h) + ImFontAtlasTextureGrow(atlas, w, h) -- Recurse return end @@ -26820,6 +30904,7 @@ local function ImFontAtlasTextureRepack(atlas, w, h) builder.RectsDiscardedCount = 0 builder.RectsDiscardedSurface = 0 + -- Patch glyphs UV for baked_n = 1, builder.BakedPool.Size do for _, glyph in builder.BakedPool[baked_n].Glyphs:iter() do if (glyph.PackId ~= ImFontAtlasRectId_Invalid) then @@ -26832,14 +30917,16 @@ local function ImFontAtlasTextureRepack(atlas, w, h) end end + -- Update other cached UV ImFontAtlasBuildUpdateTexData(atlas) builder.LockDisableResize = false ImFontAtlasUpdateDrawListsSharedData(atlas) - -- ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack"); + --ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack") end function ImFontAtlasTextureGrow(atlas, old_tex_w, old_tex_h) + --ImFontAtlasDebugWriteTexToDisk(atlas.TexData, "Before Grow") local builder = atlas.Builder old_tex_w = old_tex_w or -1 @@ -26852,12 +30939,18 @@ function ImFontAtlasTextureGrow(atlas, old_tex_w, old_tex_h) old_tex_h = atlas.TexData.Height end + -- 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) and ImIsPowerOfTwo(old_tex_h)) IM_ASSERT(ImIsPowerOfTwo(atlas.TexMinWidth) and ImIsPowerOfTwo(atlas.TexMaxWidth) and ImIsPowerOfTwo(atlas.TexMinHeight) and 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. local new_tex_w = (old_tex_h <= old_tex_w) and old_tex_w or old_tex_w * 2 local new_tex_h = (old_tex_h <= old_tex_w) and old_tex_h * 2 or old_tex_h + -- Handle minimum size first (for pathologically large packed rects) local 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)) @@ -26872,9 +30965,12 @@ end --- @param atlas ImFontAtlas local function ImFontAtlasTextureMakeSpace(atlas) + -- Can some baked contents be ditched? + --IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlasBuildMakeSpace()") local builder = atlas.Builder ImFontAtlasBuildDiscardBakes(atlas, 2) + -- Currently using a heuristic for repack without growing. if (builder.RectsDiscardedSurface < builder.RectsPackedSurface * 0.20) then ImFontAtlasTextureGrow(atlas) else @@ -26882,6 +30978,7 @@ local function ImFontAtlasTextureMakeSpace(atlas) end end +-- This is essentially a free-list pattern, it may be nice to wrap it into a dedicated type. --- @param atlas ImFontAtlas --- @param rect_idx ImFontAtlasRectId local function ImFontAtlasPackAllocRectEntry(atlas, rect_idx) @@ -26895,7 +30992,7 @@ local function ImFontAtlasPackAllocRectEntry(atlas, rect_idx) else index_idx = builder.RectsIndexFreeListStart index_entry = builder.RectsIndex[index_idx + 1] - IM_ASSERT(index_entry.IsUsed == false and index_entry.Generation > 0) + IM_ASSERT(index_entry.IsUsed == false and index_entry.Generation > 0) -- Generation is incremented during DiscardRect builder.RectsIndexFreeListStart = index_entry.TargetIndex end @@ -26905,6 +31002,7 @@ local function ImFontAtlasPackAllocRectEntry(atlas, rect_idx) return ImFontAtlasRectId_Make(index_idx, index_entry.Generation) end +-- Overwrite existing entry --- @param atlas ImFontAtlas --- @param index_entry ImFontAtlasRectEntry local function ImFontAtlasPackReuseRectEntry(atlas, index_entry) @@ -26914,6 +31012,7 @@ local function ImFontAtlasPackReuseRectEntry(atlas, index_entry) return ImFontAtlasRectId_Make(index_idx, index_entry.Generation) end +-- This is expected to be called in batches and followed by a repack --- @param atlas ImFontAtlas --- @param id ImFontAtlasRectId function ImFontAtlasPackDiscardRect(atlas, id) @@ -26932,16 +31031,18 @@ function ImFontAtlasPackDiscardRect(atlas, id) index_entry.TargetIndex = builder.RectsIndexFreeListStart index_entry.Generation = index_entry.Generation + 1 if (index_entry.Generation == 0) then - index_entry.Generation = index_entry.Generation + 1 + index_entry.Generation = index_entry.Generation + 1 -- Keep non-zero on overflow end local pack_padding = atlas.TexGlyphPadding builder.RectsIndexFreeListStart = index_idx builder.RectsDiscardedCount = builder.RectsDiscardedCount + 1 builder.RectsDiscardedSurface = builder.RectsDiscardedSurface + ((rect.w + pack_padding) * (rect.h + pack_padding)) - rect.w = 0 rect.h = 0 + rect.w = 0 rect.h = 0 -- Clear rectangle so it won't be packed again end +-- 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 function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) IM_ASSERT(w > 0 and w <= 0xFFFF) IM_ASSERT(h > 0 and h <= 0xFFFF) @@ -26951,8 +31052,10 @@ function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) builder.MaxRectSize.x = ImMax(builder.MaxRectSize.x, w) builder.MaxRectSize.y = ImMax(builder.MaxRectSize.y, h) + -- Pack local r = ImTextureRect(0, 0, w, h) for attempts_remaining = 3, 0, -1 do + -- Try packing local pack_r = stbrp.rect() pack_r.w = w + pack_padding pack_r.h = h + pack_padding @@ -26963,12 +31066,14 @@ function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) break end + -- If we ran out of attempts, return fallback if (attempts_remaining == 0 or builder.LockDisableResize) then IMGUI_DEBUG_LOG_FONT("[font] Failed packing %dx%d rectangle. Returning fallback.", w, h) return ImFontAtlasRectId_Invalid end + -- Resize or repack atlas! (this should be a rare event) ImFontAtlasTextureMakeSpace(atlas) end @@ -26979,12 +31084,13 @@ function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) builder.Rects:push_back(r) if (overwrite_entry ~= nil) then - return ImFontAtlasPackReuseRectEntry(atlas, overwrite_entry) + 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) end end +-- Generally for non-user facing functions: assert on invalid ID. --- @param atlas ImFontAtlas --- @param id ImFontAtlasRectId --- @return ImTextureRect @@ -26999,6 +31105,8 @@ function ImFontAtlasPackGetRect(atlas, id) return builder.Rects.Data[index_entry.TargetIndex + 1] end +-- For user-facing functions: return nil on invalid ID. +-- Important: return value is valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous rects. --- @param atlas ImFontAtlas --- @param id ImFontAtlasRectId function ImFontAtlasPackGetRectSafe(atlas, id) @@ -27021,6 +31129,8 @@ function ImFontAtlasPackGetRectSafe(atlas, id) return builder.Rects.Data[index_entry.TargetIndex + 1] end +-- 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. --- @param src ImFontConfig --- @param codepoint ImWchar --- @return bool @@ -27051,6 +31161,13 @@ function ImFontBaked_BuildGrowIndex(baked, new_size) baked.IndexLookup:resize(new_size, IM_FONTGLYPH_INDEX_UNUSED) end +------------------------------------------------------------------------------- +-- [SECTION] ImFontAtlas: backend for stb_truetype +------------------------------------------------------------------------------- +-- (imstb_truetype.lua in included near the top of this file) +------------------------------------------------------------------------------- + +-- One for each ConfigData --- @class ImGui_ImplStbTrueType_FontSrcData --- @field FontInfo stbtt_fontinfo --- @field ScaleFactor float @@ -27078,6 +31195,7 @@ local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) local bd_font_data = ImGui_ImplStbTrueType_FontSrcData() IM_ASSERT(src.FontLoaderData == nil) + -- Initialize helper structure for font loading and verify that the TTF/OTF data is correct local font_offset = stbtt.GetFontOffsetForIndex(src.FontData, src.FontNo) if font_offset < 0 then bd_font_data = nil @@ -27098,7 +31216,7 @@ local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) bd_font_data.ScaleFactor = stbtt.ScaleForPixelHeight(bd_font_data.FontInfo, 1.0) if (src.MergeMode and src.SizePixels ~= 0.0 and ref_size ~= 0.0) then - bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * (src.SizePixels / ref_size) + bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * (src.SizePixels / ref_size) -- FIXME-NEWATLAS: Should tidy up that a bit end bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * src.ExtraSizeScale @@ -27124,11 +31242,14 @@ local function ImGui_ImplStbTrueType_FontBakedInit(atlas, src, baked) local bd_font_data = src.FontLoaderData if (src.MergeMode == false) then + -- FIXME-NEWFONTS: reevaluate how to use sizing metrics + -- FIXME-NEWFONTS: make use of line gap value local scale_for_layout = bd_font_data.ScaleFactor * baked.Size / src.ExtraSizeScale local unscaled_ascent, unscaled_descent, unscaled_line_gap = stbtt.GetFontVMetrics(bd_font_data.FontInfo) baked.Ascent = ImCeil(unscaled_ascent * scale_for_layout) baked.Descent = ImFloor(unscaled_descent * scale_for_layout) + -- FIXME: round to rasterizer density? (#9348) end return true @@ -27144,6 +31265,7 @@ end --- @return bool --- @return float? out_advance_x # Updated `advance_x` local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, codepoint, out_glyph, advance_x) + -- Search for first font which has the glyph local bd_font_data = src.FontLoaderData IM_ASSERT(bd_font_data ~= nil) local glyph_index = stbtt.FindGlyphIndex(bd_font_data.FontInfo, codepoint) @@ -27151,15 +31273,18 @@ local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, co return false, advance_x end + -- Fonts unit to pixels local oversample_h, oversample_v = ImFontAtlasBuildGetOversampleFactors(src, baked) local scale_for_layout = bd_font_data.ScaleFactor * baked.Size local rasterizer_density = src.RasterizerDensity * baked.RasterizerDensity local scale_for_raster_x = bd_font_data.ScaleFactor * baked.Size * rasterizer_density * oversample_h local scale_for_raster_y = bd_font_data.ScaleFactor * baked.Size * rasterizer_density * oversample_v + -- Obtain size and advance local x0, y0, x1, y1 = stbtt.GetGlyphBitmapBoxSubpixel(bd_font_data.FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, 0, 0) local advance, lsb = stbtt.GetGlyphHMetrics(bd_font_data.FontInfo, glyph_index) + -- Load metrics only mode if (advance_x ~= nil) then IM_ASSERT(out_glyph == nil) advance_x = advance * scale_for_layout @@ -27167,9 +31292,12 @@ local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, co return true, advance_x end + -- Prepare glyph out_glyph.Codepoint = codepoint out_glyph.AdvanceX = advance * scale_for_layout + -- Pack and retrieve position inside texture atlas + -- (generally based on stbtt_PackFontRangesRenderIntoRects) local is_visible = (x0 ~= x1 and y0 ~= y1) if is_visible then local w = (x1 - x0 + oversample_h - 1) @@ -27183,23 +31311,30 @@ local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, co local r = ImFontAtlasPackGetRect(atlas, pack_id) + -- Render x0, y0, x1, y1 = stbtt.GetGlyphBitmapBox(bd_font_data.FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y) local builder = atlas.Builder builder.TempBuffer:resize(w * h * 1) local bitmap_pixels = builder.TempBuffer.Data ImStd.memset(bitmap_pixels, 0, w * h * 1) + + -- Render with oversampling + -- (those functions conveniently assert if pixels are not cleared, which is another safety layer) local 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, glyph_index) local ref_size = baked.OwnerFont.Sources[1].SizePixels local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0 - local font_off_x = ImFloor(src.GlyphOffset.x * offsets_scale + 0.5) + local font_off_x = ImFloor(src.GlyphOffset.x * offsets_scale + 0.5) -- Snap scaled offset. local font_off_y = ImFloor(src.GlyphOffset.y * offsets_scale + 0.5) font_off_x = font_off_x + sub_x font_off_y = font_off_y + (sub_y + IM_ROUND(baked.Ascent)) local recip_h = 1.0 / (oversample_h * rasterizer_density) local recip_v = 1.0 / (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 + r.w) * recip_h + font_off_x @@ -27231,11 +31366,14 @@ end --- @param atlas ImFontAtlas --- @param baked ImFontBaked function ImFontAtlasBuildSetupFontBakedBlanks(atlas, 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) local space_glyph = baked:FindGlyphNoFallback(32) if space_glyph ~= nil then space_glyph.Visible = false end + -- 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(9) == nil and space_glyph ~= nil then local tab_glyph = ImFontGlyph() tab_glyph.Codepoint = 9 @@ -27261,8 +31399,9 @@ function ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, ba baked.OwnerFont = font baked.LastUsedFrame = atlas.Builder.FrameCount + -- Initialize backend data local loader_data_size = 0 - for _, src in font.Sources:iter() do + for _, src in font.Sources:iter() do -- Cannot easily be cached as we allow changing backend local loader = src.FontLoader and src.FontLoader or atlas.FontLoader loader_data_size = loader_data_size + loader.FontBakedSrcLoaderDataSize end @@ -27280,6 +31419,7 @@ function ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, ba return baked end +-- 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. --- @param atlas ImFontAtlas --- @param font ImFont --- @param font_size float @@ -27298,7 +31438,7 @@ function ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer break end - if (step_n == 0 and baked.RasterizerDensity ~= font_rasterizer_density) then + if (step_n == 0 and baked.RasterizerDensity ~= font_rasterizer_density) then -- First try with same density break end @@ -27355,9 +31495,10 @@ function ImFontAtlasBakedDiscard(atlas, font, baked) font.LastBaked = nil end +-- use unused_frames==0 to discard everything. function ImFontAtlasFontDiscardBakes(atlas, font, unused_frames) local builder = atlas.Builder - if builder then + if builder then -- This can be called from font destructor for baked_n = 1, builder.BakedPool.Size do repeat local baked = builder.BakedPool[baked_n] @@ -27376,6 +31517,7 @@ function ImFontAtlasFontDiscardBakes(atlas, font, unused_frames) end end +-- Was tempted to lazily init FontSrc but wouldn't save much + makes it more complicated to detect invalid data at AddFont() function ImFontAtlasFontInitOutput(atlas, font) local ret = true for _, src in font.Sources:iter() do @@ -27383,10 +31525,11 @@ function ImFontAtlasFontInitOutput(atlas, font) ret = false end end - IM_ASSERT(ret) + IM_ASSERT(ret) -- Unclear how to react to this meaningfully. Assume that result will be same as initial AddFont() call. return ret end +-- Keep source/input FontData function ImFontAtlasFontDestroyOutput(atlas, font) font:ClearOutputData() for _, src in font.Sources:iter() do @@ -27414,10 +31557,11 @@ end function ImFontAtlasFontSourceAddToFont(atlas, font, src) if src.MergeMode == false then font:ClearOutputData() + --font.FontSize = src.SizePixels font.OwnerAtlas = atlas IM_ASSERT(font.Sources[1] == src) end - atlas.TexIsBuilt = false + atlas.TexIsBuilt = false -- For legacy backends ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) end @@ -27436,6 +31580,8 @@ function ImFontAtlasFontDestroySourceData(atlas, src) src.GlyphExcludeRanges = nil end +-- Load/identify special glyphs +-- (note that this is called again for fonts with MergeMode) --- @param atlas ImFontAtlas --- @param font ImFont --- @param src ImFontConfig @@ -27443,6 +31589,7 @@ function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) -- IM_UNUSED(atlas) IM_ASSERT(font.Sources:contains(src)) + -- Find Fallback character. Actual glyph loaded in GetFontBaked(). --- @type ImWchar[] local fallback_chars = {font.FallbackChar, IM_UNICODE_CODEPOINT_INVALID, 63, 32} if font.FallbackChar == 0 then @@ -27455,6 +31602,9 @@ function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) end end + -- 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. --- @type ImWchar[] local ellipsis_chars = {src.EllipsisChar, 0x2026, 0x0085} if font.EllipsisChar == 0 then @@ -27473,6 +31623,9 @@ function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) end end +-- 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. --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @return ImFontGlyph? @@ -27487,7 +31640,7 @@ function ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) if (dot_glyph == nil) then return nil end - local dot_r_id = dot_glyph.PackId + local dot_r_id = dot_glyph.PackId -- Deep copy to avoid invalidation of glyphs and rect pointers local dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id) local dot_spacing = 1 local dot_step = (dot_glyph.X1 - dot_glyph.X0) + dot_spacing @@ -27497,7 +31650,7 @@ function ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) local glyph = ImFontGlyph() glyph.Codepoint = font.EllipsisChar - glyph.AdvanceX = ImMax(dot_glyph.AdvanceX, dot_glyph.X0 + dot_step * 3.0 - dot_spacing) + glyph.AdvanceX = ImMax(dot_glyph.AdvanceX, dot_glyph.X0 + dot_step * 3.0 - 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 @@ -27517,6 +31670,8 @@ function ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) return glyph end +-- 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) --- @param baked ImFontBaked function ImFontAtlasBuildSetupFontBakedFallback(baked) IM_ASSERT(baked.FallbackGlyphIndex == -1) @@ -27533,10 +31688,12 @@ function ImFontAtlasBuildSetupFontBakedFallback(baked) glyph.AdvanceX = space_glyph and space_glyph.AdvanceX or IM_ROUND(baked.Size * 0.40) fallback_glyph = ImFontAtlasBakedAddFontGlyph(font.OwnerAtlas, baked, nil, glyph) end - baked.FallbackGlyphIndex = baked.Glyphs:index_from_ptr(fallback_glyph) + 1 + baked.FallbackGlyphIndex = baked.Glyphs:index_from_ptr(fallback_glyph) + 1 -- Storing index avoid need to update pointer on growth and simplify inner loop code baked.FallbackAdvanceX = fallback_glyph.AdvanceX end +-- Setup main font loader for the atlas +-- Every font source (ImFontConfig) will use this unless ImFontConfig.FontLoader specify a custom loader. function ImFontAtlasBuildSetupFontLoader(atlas, font_loader) if atlas.FontLoader == font_loader then return @@ -27568,6 +31725,11 @@ function ImFontAtlasBuildSetupFontLoader(atlas, font_loader) end local function ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas) + -- [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 _, shared_data in atlas.DrawListSharedDatas:iter() do local imgui_ctx = shared_data.Context if (imgui_ctx) then @@ -27587,21 +31749,27 @@ local function ImFontAtlasBuildUpdatePointers(atlas) -- end end +-- Update texture identifier in all active draw lists --- @param atlas ImFontAtlas --- @param old_tex ImTextureRef --- @param new_tex ImTextureRef local function ImFontAtlasUpdateDrawListsTextures(atlas, old_tex, new_tex) for _, shared_data in atlas.DrawListSharedDatas:iter() do repeat + -- If Context 2 uses font owned by Context 1 which already called EndFrame()/Render(), we don't want to mess with draw commands for Context 1 if (shared_data.Context and not shared_data.Context.WithinFrameScope) then break end for _, draw_list in shared_data.DrawLists:iter() do + -- 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 and draw_list._CmdHeader.TexRef == old_tex) then draw_list:_SetTexture(new_tex) end + -- Replace in stack for i, stacked_tex in draw_list._TextureStack:iter() do if (stacked_tex == old_tex) then draw_list._TextureStack.Data[i] = new_tex @@ -27613,12 +31781,13 @@ local function ImFontAtlasUpdateDrawListsTextures(atlas, old_tex, new_tex) end end +-- Set current texture. This is mostly called from AddTexture() + to handle a failed resize. function ImFontAtlasBuildSetTexture(atlas, tex) local old_tex_ref = atlas.TexRef atlas.TexData = tex atlas.TexUvScale = ImVec2(1.0 / tex.Width, 1.0 / 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. + --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) end @@ -27628,17 +31797,28 @@ function ImFontAtlasBuildUpdateTexData(atlas) ImFontAtlasBuildUpdateTexDataBasic(atlas) end +-- Create a new texture, discard previous one function ImFontAtlasTextureAdd(atlas, w, h) local old_tex = atlas.TexData local new_tex -- FIXME: Cannot reuse texture because old UV may have been used already (unless we remap UV). + --if (old_tex ~= nil and old_tex.Status == ImTextureStatus.WantCreate) then + -- -- Reuse texture not yet used by backend. + -- IM_ASSERT(old_tex.TexID == ImTextureID_Invalid and old_tex.BackendUserData == nil) + -- old_tex:DestroyPixels() + -- old_tex.Updates:clear() + -- new_tex = old_tex + -- old_tex = nil + --else + -- Add new new_tex = ImTextureData() new_tex.UniqueID = atlas.TexNextUniqueID atlas.TexNextUniqueID = atlas.TexNextUniqueID + 1 atlas.TexList:push_back(new_tex) if old_tex ~= nil then + -- Queue old as to destroy next frame old_tex.WantDestroyNextFrame = true IM_ASSERT(old_tex.Status == ImTextureStatus.OK or old_tex.Status == ImTextureStatus.WantCreate or old_tex.Status == ImTextureStatus.WantUpdates) end @@ -27663,7 +31843,7 @@ function ImFontAtlasTextureGetSizeEstimate(atlas) local builder = atlas.Builder min_w = ImMax(ImUpperPowerOfTwo(builder.MaxRectSize.x), min_w) min_h = ImMax(ImUpperPowerOfTwo(builder.MaxRectSize.y), min_h) - local surface_approx = builder.RectsPackedSurface - builder.RectsDiscardedSurface + local surface_approx = builder.RectsPackedSurface - builder.RectsDiscardedSurface -- Expected surface after repack local surface_sqrt = ImFloor(ImSqrt(surface_approx)) local new_tex_w @@ -27686,6 +31866,7 @@ function ImFontAtlasTextureGetSizeEstimate(atlas) return ImVec2(new_tex_w, new_tex_h) -- ImVec2i end +-- Clear all output. Invalidates all AddCustomRect() return values! --- @param atlas ImFontAtlas function ImFontAtlasBuildClear(atlas) local new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas) -- ImVec2i @@ -27702,6 +31883,8 @@ function ImFontAtlasBuildClear(atlas) end end +-- You should not need to call this manually! +-- If you think you do, let us know and we can advise about policies auto-compact. --- @param atlas ImFontAtlas function ImFontAtlasTextureCompact(atlas) local builder = atlas.Builder @@ -27722,6 +31905,7 @@ function ImFontAtlasPackInit(atlas) local tex = atlas.TexData local 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. local pack_node_count = ImFloor(tex.Width / 2) builder.PackNodes:resize(pack_node_count) for i = 1, builder.PackNodes.Size do builder.PackNodes.Data[i] = stbrp.node() end @@ -27739,18 +31923,22 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) return end + -- Pack and store identifier so we can refresh UV coordinates on texture resize. local tex = atlas.TexData local builder = atlas.Builder local r = ImFontAtlasRect() local add_and_draw = (atlas:GetCustomRect(builder.PackIdLinesTexData, r) == false) if add_and_draw then + -- 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 local pack_size = ImVec2(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) -- ImVec2i builder.PackIdLinesTexData = atlas:AddCustomRect(pack_size.x, pack_size.y, r) IM_ASSERT(builder.PackIdLinesTexData ~= ImFontAtlasRectId_Invalid) end - for n = 0, IM_DRAWLIST_TEX_LINES_WIDTH_MAX do + for n = 0, IM_DRAWLIST_TEX_LINES_WIDTH_MAX do -- +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 local y = n local line_width = n @@ -27759,8 +31947,9 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) --- @type int local pad_right = r.w - (pad_left + line_width) - IM_ASSERT(pad_left + line_width + pad_right == r.w and y < r.h) + IM_ASSERT(pad_left + line_width + pad_right == r.w and y < r.h) -- Make sure we're inside the texture bounds before we start writing pixels + -- Write each slice if (add_and_draw and tex.Format == ImTextureFormat.Alpha8) then local write_ptr, write_ptr_base = tex:GetPixelsAt(r.x, r.y + y) @@ -27791,13 +31980,15 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) end end + -- Refresh UV coordinates local uv0 = ImVec2(r.x + pad_left - 1, r.y + y) * atlas.TexUvScale local uv1 = ImVec2(r.x + pad_left + line_width + 1, r.y + y + 1) * atlas.TexUvScale - local half_v = (uv0.y + uv1.y) * 0.5 + local half_v = (uv0.y + uv1.y) * 0.5 -- 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) end end +-- Render a white-colored bitmap encoded in a string --- @param atlas ImFontAtlas --- @param x int --- @param y int @@ -27837,6 +32028,8 @@ end --- @param atlas ImFontAtlas function ImFontAtlasBuildUpdateTexDataBasic(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. local builder = atlas.Builder local pack_size = (bit32.band(atlas.Flags, ImFontAtlasFlags.NoMouseCursors) ~= 0) and ImVec2(2, 2) or ImVec2(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H) @@ -27846,9 +32039,12 @@ function ImFontAtlasBuildUpdateTexDataBasic(atlas) builder.PackIdMouseCursors = atlas:AddCustomRect(pack_size.x, pack_size.y, r) IM_ASSERT(builder.PackIdMouseCursors ~= ImFontAtlasRectId_Invalid) + -- Draw to texture if bit32.band(atlas.Flags, ImFontAtlasFlags.NoMouseCursors) ~= 0 then + -- 2x2 white pixels ImFontAtlasBuildRenderBitmapFromString(atlas, r.x, r.y, 2, 2, {"X", "X", "X", "X"}, "X") else + -- 2x2 white pixels + mouse cursors local x_for_white = r.x local 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, ".") @@ -27856,9 +32052,12 @@ function ImFontAtlasBuildUpdateTexDataBasic(atlas) end end + -- Refresh UV coordinates atlas.TexUvWhitePixel = ImVec2((r.x + 0.5) * atlas.TexUvScale.x, (r.y + 0.5) * atlas.TexUvScale.y) end +-- 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? function ImFontAtlasUpdateDrawListsSharedData(atlas) for _, shared_data in atlas.DrawListSharedDatas:iter() do if (shared_data.FontAtlas == atlas) then @@ -27868,12 +32067,19 @@ function ImFontAtlasUpdateDrawListsSharedData(atlas) end end +-- Start packing over current empty texture function ImFontAtlasBuildInit(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 == nil then -- IMGUI_ENABLE_STB_TRUETYPE atlas:SetFontLoader(ImFontAtlasGetFontLoaderForStbTruetype()) end + -- Create initial texture size if atlas.TexData == nil or atlas.TexData.Pixels == nil then ImFontAtlasTextureAdd(atlas, ImUpperPowerOfTwo(atlas.TexMinWidth), ImUpperPowerOfTwo(atlas.TexMinHeight)) end @@ -27886,15 +32092,23 @@ function ImFontAtlasBuildInit(atlas) ImFontAtlasPackInit(atlas) + -- Add required texture data ImFontAtlasBuildUpdateTexData(atlas) + -- Register fonts ImFontAtlasBuildUpdatePointers(atlas) + -- Update UV coordinates etc. stored in bound ImDrawListSharedData instance ImFontAtlasUpdateDrawListsSharedData(atlas) + --atlas.TexIsBuilt = true + + -- Lazily initialize char/text classifier + -- FIXME: This could be practically anywhere, and should eventually be parameters to CalcTextSize/word-wrapping code, but there's no obvious spot now. ImTextInitClassifiers() end +-- Destroy builder and all cached glyphs. Do not destroy actual fonts. --- @param atlas ImFontAtlas function ImFontAtlasBuildDestroy(atlas) for _, font in atlas.Fonts:iter() do @@ -27907,6 +32121,8 @@ function ImFontAtlasBuildDestroy(atlas) atlas.Builder = nil end +-- 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) --- @param atlas ImFontAtlas --- @param old_font ImFont? --- @param new_font ImFont? @@ -27918,9 +32134,9 @@ function ImFontAtlasBuildNotifySetFont(atlas, old_font, new_font) local ctx = shared_data.Context if ctx then repeat + -- While this should work either way, we save ourselves the bother / debugging confusion of running ImGui code so early when it is not needed. + -- Also fixes erroneously rewriting style.FontSizeBase during init if adding default fonts. if old_font == nil and ctx.Font == nil and ctx.FontSizeBase == 0.0 then - -- While this should work either way, we save ourselves the bother / debugging confusion of running ImGui code so early when it is not needed. - -- Also fixes erroneously rewriting style.FontSizeBase during init if adding default fonts. break end @@ -27950,6 +32166,7 @@ function ImFontAtlasBuildNotifySetFont(atlas, old_font, new_font) end end +-- When atlas.RendererHasTextures = true, this is only called if no font were loaded. --- @param atlas ImFontAtlas function ImFontAtlasBuildMain(atlas) IM_ASSERT(not atlas.Locked, "Cannot modify a locked ImFontAtlas!") @@ -27968,13 +32185,20 @@ function ImFontAtlasBuildMain(atlas) -- [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs -- ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); - -- if atlas.RendererHasTextures == false then + -- if atlas.RendererHasTextures == false then -- ~ImGuiBackendFlags.RendererHasTextures -- ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas) -- end atlas.TexIsBuilt = true end +------------------------------------------------------------------------------- +-- [SECTION] ImTextureData +------------------------------------------------------------------------------- +-- - ImTextureData:Create() +-- - ImTextureData:DestroyPixels() +------------------------------------------------------------------------------- + function MT.ImTextureData:DestroyPixels() self.Pixels = nil self.UseColors = false @@ -28011,6 +32235,10 @@ function MT.ImTextureData:Create(format, w, h) self.UpdateRect.h = 0 end +------------------------------------------------------------------------------- +-- [SECTION] ImFontBaked, ImFont +------------------------------------------------------------------------------- + function MT.ImFontBaked:ClearOutputData() self.FallbackAdvanceX = 0.0 self.Glyphs:clear() @@ -28022,6 +32250,7 @@ function MT.ImFontBaked:ClearOutputData() self.MetricsTotalSurface = 0 end +-- Find glyph, load if necessary, return fallback if missing --- @param c ImWchar --- @return ImFontGlyph? function MT.ImFontBaked:FindGlyph(c) @@ -28044,6 +32273,7 @@ function MT.ImFontBaked:IsGlyphLoaded(c) return self.IndexLookup.Data[c + 1] ~= IM_FONTGLYPH_INDEX_UNUSED end +-- Attempt to load but when missing, return nil instead of FallbackGlyph --- @param c ImWchar --- @return ImFontGlyph? function MT.ImFontBaked:FindGlyphNoFallback(c) @@ -28057,7 +32287,7 @@ function MT.ImFontBaked:FindGlyphNoFallback(c) end end - self.LoadNoFallback = true + self.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. local glyph = ImFontBaked_BuildLoadGlyph(self, c, nil) self.LoadNoFallback = false return glyph @@ -28068,6 +32298,7 @@ function MT.ImFont:ClearOutputData() if atlas ~= nil then ImFontAtlasFontDiscardBakes(atlas, self, 0) end + --self.FallbackChar = 0 self.EllipsisChar = 0 for i = 1, (IM_UNICODE_CODEPOINT_MAX + 1) / 8192 / 8 do self.Used8kPagesMap[i] = 0 end self.LastBaked = nil @@ -28088,6 +32319,8 @@ end --- @param font_rasterizer_density float --- @return ImFontBaked? function ImFontAtlasBakedGetOrAdd(atlas, font, font_size, font_rasterizer_density) + -- 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.0 and font_rasterizer_density > 0.0) local baked_id = ImFontAtlasBakedGetId(font.FontId, font_size, font_rasterizer_density) local builder = atlas.Builder @@ -28098,23 +32331,29 @@ function ImFontAtlasBakedGetOrAdd(atlas, font, font_size, font_rasterizer_densit return baked end + -- If atlas is locked, find closest match + -- FIXME-OPT: This is not an optimal query. if (bit32.band(font.Flags, ImFontFlags.LockBakedSizes) ~= 0 or atlas.Locked) then baked = ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer_density) if baked ~= nil then return baked end if atlas.Locked then - IM_ASSERT(not atlas.Locked, "Cannot use dynamic font size with a locked ImFontAtlas!") + IM_ASSERT(not atlas.Locked, "Cannot use dynamic font size with a locked ImFontAtlas!") -- Locked because rendering backend does not support ImGuiBackendFlags.RendererHasTextures! return nil end end + -- Create new baked = ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, baked_id) builder.BakedMap[baked_id] = baked return baked end +-- 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 == 'self.Sources' because multiple source fonts+configs can be used to build one target font. --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @param src? ImFontConfig @@ -28124,8 +32363,9 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) local glyph_idx = baked.Glyphs.Size + 1 baked.Glyphs:push_back(in_glyph) local glyph = baked.Glyphs.Data[glyph_idx] - IM_ASSERT(baked.Glyphs.Size < 0xFFFE) + 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) then local r = ImFontAtlasPackGetRect(atlas, glyph.PackId) IM_ASSERT(glyph.U0 == 0.0 and glyph.V0 == 0.0 and glyph.U1 == 0.0 and glyph.V1 == 0.0) @@ -28137,6 +32377,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) end if (src ~= nil) then + -- Clamp & recenter if needed local ref_size = baked.OwnerFont.Sources[1].SizePixels local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0 local advance_x = ImClamp(glyph.AdvanceX, src.GlyphMinAdvanceX * offsets_scale, src.GlyphMaxAdvanceX * offsets_scale) @@ -28146,10 +32387,12 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) glyph.X1 = glyph.X1 + char_off_x end + -- Snap to pixel if (src.PixelSnapH) then advance_x = IM_ROUND(advance_x) end + -- Bake spacing glyph.AdvanceX = advance_x + src.GlyphExtraAdvanceX end if (glyph.Colored) then @@ -28157,6 +32400,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) atlas.TexPixelsUseColors = true end + -- Update lookup tables local codepoint = glyph.Codepoint ImFontBaked_BuildGrowIndex(baked, codepoint + 1) baked.IndexAdvanceX.Data[codepoint + 1] = glyph.AdvanceX @@ -28167,6 +32411,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) return glyph end +-- FIXME: Code is duplicated with code above. --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @param src? ImFontConfig @@ -28175,14 +32420,17 @@ end function ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, advance_x) -- IM_UNUSED(atlas) if (src ~= nil) then + -- Clamp & recenter if needed local ref_size = baked.OwnerFont.Sources[1].SizePixels local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0 advance_x = ImClamp(advance_x, src.GlyphMinAdvanceX * offsets_scale, src.GlyphMaxAdvanceX * offsets_scale) + -- Snap to pixel if (src.PixelSnapH) then advance_x = IM_ROUND(advance_x) end + -- Bake spacing advance_x = advance_x + src.GlyphExtraAdvanceX end @@ -28190,6 +32438,7 @@ function ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, adv baked.IndexAdvanceX.Data[codepoint + 1] = advance_x end +-- ImFontBaked are valid for the entire frame but shall never be kept between frames. --- @param size float --- @param density float? --- @return ImFontBaked? @@ -28199,6 +32448,8 @@ function MT.ImFont:GetFontBaked(size, density) --- @type ImFontBaked? local baked = self.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.0 then @@ -28244,6 +32495,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) local font = baked.OwnerFont local atlas = font.OwnerAtlas if atlas.Locked or bit32.band(font.Flags, ImFontFlags.NoLoadGlyphs) ~= 0 then + -- Lazily load fallback glyph if baked.FallbackGlyphIndex == -1 and baked.LoadNoFallback == false then ImFontAtlasBuildSetupFontBakedFallback(baked) end @@ -28251,9 +32503,14 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) return nil, only_load_advance_x end + -- User remapping hooks local src_codepoint = codepoint codepoint = ImFontAtlas_FontHookRemapCodepoint(atlas, font, codepoint) + --IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)", codepoint, ImTextCharToUtf8(codepoint)) + + -- Special hook + -- FIXME-NEWATLAS: it would be nicer if this used a more standardized way of hooking if (codepoint == font.EllipsisChar and font.EllipsisAutoBake) then local glyph = ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) if (glyph) then @@ -28261,6 +32518,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) end end + -- Call backend local loader_user_data_p = baked.FontLoaderDatas local src_n = 1 for _, src in font.Sources:iter() do @@ -28271,12 +32529,14 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) local glyph_buf = ImFontGlyph() if loader.FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, glyph_buf, nil) then + -- FIXME: Add hooks for e.g. #7962 glyph_buf.Codepoint = src_codepoint glyph_buf.SourceIdx = src_n return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph_buf) end else + -- Special mode but only loading glyphs metrics. Will rasterize and pack later. local ret --[[@as bool]] ret, only_load_advance_x = loader.FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, nil, only_load_advance_x) if ret then @@ -28292,6 +32552,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) src_n = src_n + 1 end + -- Lazily load fallback glyph if (baked.LoadNoFallback) then return nil, only_load_advance_x end @@ -28299,6 +32560,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) ImFontAtlasBuildSetupFontBakedFallback(baked) end + -- Mark index as not found, so we don't attempt the search twice ImFontBaked_BuildGrowIndex(baked, codepoint + 1); baked.IndexAdvanceX.Data[codepoint + 1] = baked.FallbackAdvanceX baked.IndexLookup.Data[codepoint + 1] = IM_FONTGLYPH_INDEX_NOT_FOUND @@ -28311,6 +32573,7 @@ end --- @return float function ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint) if (baked.Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE) or baked.LoadNoRenderOnLayout then + -- First load AdvanceX value used by CalcTextSize() API then load the rest when loaded by drawing API. local only_advance_x local glyph glyph, only_advance_x = ImFontBaked_BuildLoadGlyph(baked, codepoint, only_advance_x) @@ -28322,6 +32585,7 @@ function ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint) end end +-- This is not fast query --- @param c ImWchar --- @return bool function MT.ImFont:IsGlyphInFont(c) @@ -28337,10 +32601,12 @@ function MT.ImFont:IsGlyphInFont(c) return false end +-- This is manually inlined in CalcTextSizeA() and CalcWordWrapPosition(), with a non-inline call to BuildLoadGlyphGetAdvanceOrFallback(). --- @param c ImWchar --- @return float function MT.ImFontBaked:GetCharAdvance(c) if c < self.IndexAdvanceX.Size then + -- Missing glyphs fitting inside index will have stored FallbackAdvanceX already. local x = self.IndexAdvanceX.Data[c + 1] if x >= 0.0 then return x @@ -28349,10 +32615,12 @@ function MT.ImFontBaked:GetCharAdvance(c) return ImFontBaked_BuildLoadGlyphAdvanceX(self, c) end +-- The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b function BuildLoadGlyphGetAdvanceOrFallback(baked, codepoint) return ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint) end +-- Trim trailing space and find beginning of next line --- @param text ImString --- @param text_begin int --- @param text_end int @@ -28411,14 +32679,17 @@ function ImTextClassifierGet(_BITS, _CHAR_OFFSET) return bit32.band(bit32.rshift(_BITS[bit32.rshift(_CHAR_OFFSET, 4) + 1], bit32.lshift(bit32.band(_CHAR_OFFSET, 15), 1)), 0x03) end +-- 2-bit per character local g_CharClassifierIsSeparator_0000_007f = {} for i = 1, 128 / 16 do g_CharClassifierIsSeparator_0000_007f[i] = 0 end local g_CharClassifierIsSeparator_3000_300f = {} for i = 1, 16 / 16 do g_CharClassifierIsSeparator_3000_300f[i] = 0 end function ImTextInitClassifiers() - if (ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, 44) ~= 0) then + if (ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, 44) ~= 0) then -- ',' return end + -- List of hardcoded separators: .,;!?'" + -- Making this dynamic given known ranges is trivial BUT requires us to standardize where you pass them as parameters. (#3002, #8503) ImTextClassifierClear(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Other) ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Blank, " \t") ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Punct, ".,;!?\"") @@ -28429,6 +32700,9 @@ function ImTextInitClassifiers() ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass.Punct, 0x3002) end +-- 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. +-- Refer to imgui_test_suite's "drawlist_text_wordwrap_1" for tests. --- @param font ImFont --- @param size float --- @param text ImString @@ -28438,12 +32712,22 @@ end --- @param flags ImDrawTextFlags --- @return int function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_width, flags) + -- For references, possible wrap point marked with ^ + -- "aaa bbb, ccc,ddd. eee fff. ggg!" + -- ^ ^ ^ ^ ^__ ^ ^ + + -- Skip extra blanks after a line returns (that includes not counting them in width computation) + -- e.g. "Hello world" --> "Hello" "World" + + -- Cut words that cannot possibly fit within one line. + -- e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + local baked = font:GetFontBaked(size) local scale = size / baked.Size local line_width = 0.0 local blank_width = 0.0 - wrap_width = wrap_width / scale + wrap_width = wrap_width / scale -- We work with unscaled widths to avoid scaling every characters local s = pos IM_ASSERT(text_end ~= nil) @@ -28451,6 +32735,8 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt local prev_type = ImWcharClass.Other local keep_blanks = bit32.band(flags, ImDrawTextFlags.WrapKeepBlanks) ~= 0 + -- Find next wrapping point + --local span_begin = s local span_end = s local span_width = 0.0 @@ -28470,20 +32756,22 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt if c < 32 then if c == 10 then -- '\n' - return s + return s -- Direct return, skip "Wrap_width is too small to fit anything" path. end if c == 13 then -- '\r' - s = next_s + s = next_s -- Fast-skip break end end + -- Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' local char_width = (c < baked.IndexAdvanceX.Size) and baked.IndexAdvanceX.Data[c + 1] or -1.0 if char_width < 0.0 then char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c) end + -- Classify current character local curr_type if c < 128 then curr_type = ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, c) @@ -28494,6 +32782,7 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt end if curr_type == ImWcharClass.Blank then + -- End span: 'A ' or '. ' if (prev_type ~= ImWcharClass.Blank and not keep_blanks) then span_end = s line_width = line_width + span_width @@ -28502,11 +32791,13 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt blank_width = blank_width + char_width else - if (prev_type == ImWcharClass.Punct and curr_type ~= ImWcharClass.Punct and not (c >= 48 and c <= 57)) then + -- End span: '.X' unless X is a digit + if (prev_type == ImWcharClass.Punct and curr_type ~= ImWcharClass.Punct and not (c >= 48 and c <= 57)) then -- FIXME: Digit checks might be removed if allow custom separators (#8503) span_end = s line_width = line_width + (span_width + blank_width) blank_width = 0.0 span_width = 0.0 + -- End span: 'A ' or '. ' elseif (prev_type == ImWcharClass.Blank and keep_blanks) then span_end = s line_width = line_width + (span_width + blank_width) @@ -28521,7 +32812,10 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt if span_width + blank_width > wrap_width then stop = true; break end - + -- FIXME: Narrow wrapping e.g. "A quick brown" -> "Quic|k br|own", would require knowing if span is going to be longer than wrap_width. + --if (span_width > wrap_width and not is_blank and not was_blank) then + -- return s + --end return span_end end @@ -28532,6 +32826,8 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt if stop then break end end + -- 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 == pos and s < text_end then local bytes = ImStd.ImTextCountUtf8BytesFromChar(text, s, text_end) @@ -28574,7 +32870,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi cache_key = text end if not text_end then - text_end = #text + 1 + text_end = #text + 1 -- FIXME-OPT: Need to avoid this. end if not text_end_display then text_end_display = text_end @@ -28594,7 +32890,9 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi local stop = false while s < text_end_display do repeat + -- Word-wrapping if word_wrap_enabled then + -- 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 not word_wrap_eol then word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, text, s, text_end, wrap_width - line_width, flags) end @@ -28605,7 +32903,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end text_size.y = text_size.y + line_height line_width = 0.0 - s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) + s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then stop = true; break end @@ -28615,6 +32913,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end end + -- Decode and advance source local prev_s = s local c = ImStrByte(text, s) if c < 0x80 then @@ -28640,6 +32939,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi break end + -- Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' local char_width = (c < baked.IndexAdvanceX.Size) and baked.IndexAdvanceX.Data[c + 1] or -1.0 if (char_width < 0.0) then char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c) @@ -28661,12 +32961,12 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi text_size.x = line_width end - if out_offset then + if out_offset then -- offset allow for the possibility of sitting after a trailing \n out_offset.x = line_width out_offset.y = text_size.y + line_height end - if (line_width > 0 or text_size.y == 0.0) then + if (line_width > 0 or text_size.y == 0.0) then -- whereas size.y will ignore the trailing \n text_size.y = text_size.y + line_height end @@ -28748,6 +33048,7 @@ function MT.ImFont:RenderChar(draw_list, size, pos, col, c, cpu_fine_clip) end function MT.ImFontAtlas:AddFont(font_cfg_in) + -- Sanity Checks IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") IM_ASSERT((font_cfg_in.FontData ~= nil and font_cfg_in.FontDataSize > 0) or (font_cfg_in.FontLoader ~= nil)) IM_ASSERT(font_cfg_in.SizePixels > 0.0, "Is ImFontConfig struct correctly initialized?") @@ -28759,10 +33060,12 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) "Specifying glyph offset/advances requires a reference size to base it on.") end + -- Lazily create builder on the first call to AddFont if self.Builder == nil then ImFontAtlasBuildInit(self) end + -- Create new font local is_first_font = (self.Fonts.Size == 0) local font if not font_cfg_in.MergeMode then @@ -28774,11 +33077,12 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) font.CurrentRasterizerDensity = font_cfg_in.RasterizerDensity self.Fonts:push_back(font) else - IM_ASSERT(self.Fonts.Size > 0, "Cannot use MergeMode for the first font!") + IM_ASSERT(self.Fonts.Size > 0, "Cannot use MergeMode for the first font!") -- When using MergeMode make sure that a font has already been added before. font = (font_cfg_in.DstFont ~= nil) and font_cfg_in.DstFont or self.Fonts:back() - ImFontAtlasFontDiscardBakes(self, font, 0) + ImFontAtlasFontDiscardBakes(self, font, 0) -- Need to discard bakes if the font was already used, because baked->FontLoaderDatas[] will change size. (#9162) end + -- Add to list self.Sources:push_back(font_cfg_in) local font_cfg = self.Sources:back() if (font_cfg.DstFont == nil) then @@ -28787,6 +33091,8 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) font.Sources:push_back(font_cfg) ImFontAtlasBuildUpdatePointers(self) + -- Sanity check + -- We don't round cfg.SizePixels yet as relative size of merged fonts are used afterwards. if font_cfg.GlyphExcludeRanges ~= nil then local size = 0 for _, v in ipairs(font_cfg.GlyphExcludeRanges) do if v == 0 then break end size = size + 1 end @@ -28796,14 +33102,18 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) if font_cfg.FontLoader ~= nil then IM_ASSERT(font_cfg.FontLoader.FontBakedLoadGlyph ~= nil) - IM_ASSERT(font_cfg.FontLoader.LoaderInit == nil and font_cfg.FontLoader.LoaderShutdown == nil) + IM_ASSERT(font_cfg.FontLoader.LoaderInit == nil and font_cfg.FontLoader.LoaderShutdown == nil) -- FIXME-NEWATLAS: Unsupported yet. end + -- | Target w/ Implicit RefSize | Target w/ Explicit RefSize | + -- Adding w/ Implicit RefSize: | OK (same scale) | OK (same scale) | + -- Adding w/ Explicit RefSize: | KO | OK (custom scale) | if font_cfg_in.MergeMode and font_cfg_in.SizePixels > 0 then IM_ASSERT(bit32.band(font.Flags, ImFontFlags.ImplicitRefSize) == 0, "Cannot use MergeMode with an explicit reference size when the destination font used an implicit reference size!") end IM_ASSERT(font_cfg.FontLoaderData == nil) if not ImFontAtlasFontSourceInit(self, font_cfg) then + -- Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) ImFontAtlasFontDestroySourceData(self, font_cfg) self.Sources:pop_back() font.Sources:pop_back() @@ -28822,12 +33132,16 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) return font end +-- This duplicates some of the logic in UpdateFontsNewFrame() which is a bit chicken-and-eggy/tricky to extract due to variety of codepaths and possible initialization ordering. --- @param ctx ImGuiContext --- @return float local function GetExpectedContextFontSize(ctx) return ((ctx.Style.FontSizeBase > 0.0) and ctx.Style.FontSizeBase or 13.0) * ctx.Style.FontScaleMain * ctx.Style.FontScaleDpi end +-- Legacy function with heuristic to select Pixel or Vector font. +-- The selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold at the time of adding the default font. +-- Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() based on your own logic. --- @param font_cfg ImFontConfig function MT.ImFontAtlas:AddFontDefault(font_cfg) if self.OwnerContext == nil or GetExpectedContextFontSize(self.OwnerContext) >= 15.0 then @@ -28841,7 +33155,7 @@ function MT.ImFontAtlas:AddFontFromMemoryTTF(font_data, font_data_size, size_pix IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() IM_ASSERT(font_cfg.FontData == nil) - IM_ASSERT(font_data_size > 100, "Incorrect value for font_data_size!") + IM_ASSERT(font_data_size > 100, "Incorrect value for font_data_size!") -- Heuristic to prevent accidentally passing a wrong value to font_data_size. font_cfg.FontData = font_data font_cfg.FontDataSize = font_data_size font_cfg.SizePixels = (size_pixels > 0.0) and size_pixels or font_cfg.SizePixels @@ -28871,6 +33185,7 @@ function MT.ImFontAtlas:AddFontFromFileTTF(filename, size_pixels, font_cfg_templ local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() if not font_cfg.Name or font_cfg.Name == "" then + -- Store a short copy of filename into the font name for convenience for i = #filename, 1, -1 do local c = string.byte(filename, i, i) if (c == 47 or c == 92) then -- '/' or '\\' @@ -28892,31 +33207,35 @@ function GetDefaultFontDataProggyForever() end -- TODO: IMGUI_DISABLE_DEFAULT_FONT, IMGUI_DISABLE_DEFAULT_FONT_BITMAP +-- Load ProggyClean.ttf. Default size 13, disable oversampling. +-- If you want a similar font which may be better scaled, consider using AddFontDefaultVector(). --- @param font_cfg_template ImFontConfig function MT.ImFontAtlas:AddFontDefaultBitmap(font_cfg_template) local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() if not font_cfg_template then - font_cfg.PixelSnapH = true + font_cfg.PixelSnapH = true -- Prevents sub-integer scaling factors at lower-level layers. end if font_cfg.SizePixels <= 0.0 then - font_cfg.SizePixels = 13.0 + font_cfg.SizePixels = 13.0 -- This only serves (1) as a reference for GlyphOffset.y setting and (2) as a default for pre-1.92 backend. font_cfg.Flags = bit32.bor(font_cfg.Flags, ImFontFlags.ImplicitRefSize) end if not font_cfg.Name or font_cfg.Name == "" then font_cfg.Name = "ProggyClean.ttf" end font_cfg.EllipsisChar = 0x0085 - font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 1.0 * (font_cfg.SizePixels / 13.0) + font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 1.0 * (font_cfg.SizePixels / 13.0) -- Add +1 offset per 13 units local ttf_data, ttf_data_size = GetDefaultFontDataProggyClean() return self:AddFontFromMemoryTTF(ttf_data, ttf_data_size, font_cfg.SizePixels, font_cfg) end +-- Load a minimal version of ProggyForever, designed to match our good old ProggyClean, but nicely scalable. +-- (See build script in https://github.com/ocornut/proggyforever for details) --- @param font_cfg_template ImFontConfig function MT.ImFontAtlas:AddFontDefaultVector(font_cfg_template) local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() if not font_cfg_template then - font_cfg.PixelSnapH = true + font_cfg.PixelSnapH = true -- Precisely match ProggyClean, but prevents sub-integer scaling factors at lower-level layers. end if font_cfg.SizePixels <= 0.0 then font_cfg.SizePixels = 13.0 @@ -28925,8 +33244,8 @@ function MT.ImFontAtlas:AddFontDefaultVector(font_cfg_template) if not font_cfg.Name or font_cfg.Name == "" then font_cfg.Name = "ProggyForever.ttf" end - font_cfg.ExtraSizeScale = font_cfg.ExtraSizeScale * 1.015 - font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 0.5 * (font_cfg.SizePixels / 16.0) + font_cfg.ExtraSizeScale = font_cfg.ExtraSizeScale * 1.015 -- Match ProggyClean + font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 0.5 * (font_cfg.SizePixels / 16.0) -- Closer match ProggyClean + avoid descenders going too high (with current code). local ttf_data, ttf_data_size = GetDefaultFontDataProggyForever() return self:AddFontFromMemoryTTF(ttf_data, ttf_data_size, font_cfg.SizePixels, font_cfg) @@ -28937,7 +33256,7 @@ function MT.ImFontAtlas:GetCustomRect(id, out_r) if r == nil then return false end - IM_ASSERT(self.TexData.Width > 0 and self.TexData.Height > 0) + IM_ASSERT(self.TexData.Width > 0 and self.TexData.Height > 0) -- Font atlas needs to be built before we can calculate UV coordinates if out_r == nil then return true end @@ -28979,6 +33298,7 @@ function ImFontAtlasGetMouseCursorTexData(atlas, cursor_type, out_offset, out_si return true end +-- At it is common to do an AddCustomRect() followed by a GetCustomRect(), we provide an optional 'out_r' argument to retrieve the info straight away. function MT.ImFontAtlas:AddCustomRect(width, height, out_r) IM_ASSERT(width > 0 and width <= 0xFFFF) IM_ASSERT(height > 0 and height <= 0xFFFF) @@ -29014,7 +33334,7 @@ local function IM_NORMALIZE2F_OVER_ZERO(VX, VY) end local function IM_FIXNORMAL2F(VX, VY) - local IM_FIXNORMAL2F_MAX_INVLEN2 = 100 + local IM_FIXNORMAL2F_MAX_INVLEN2 = 100 -- 500.0f (see #4053, #3366) local d2 = VX * VX + VY * VY if d2 > 0.000001 then @@ -29028,10 +33348,14 @@ local function IM_FIXNORMAL2F(VX, VY) return VX, VY end +------------------------------------------------------------------------------- +-- [SECTION] ImDrawData +------------------------------------------------------------------------------- + function MT.ImDrawData:Clear() self.Valid = false self.FrameCount = 0; self.TotalIdxCount = 0; self.TotalVtxCount = 0 - self.CmdLists:resize(0) + self.CmdLists:resize(0) -- The ImDrawList are NOT owned by ImDrawData but e.g. by ImGuiContext, so we don't clear them. self.DisplayPos = ImVec2(0.0, 0.0) self.DisplaySize = ImVec2(0.0, 0.0) self.FramebufferScale = ImVec2(0.0, 0.0) @@ -29039,6 +33363,8 @@ function MT.ImDrawData:Clear() self.Textures = nil end +-- Important: 'out_list' is generally going to be draw_data.CmdLists, but may be another temporary list +-- as long at it is expected that the result will be later merged into draw_data.CmdLists[]. function ImGui.AddDrawListToDrawDataEx(draw_data, out_list, draw_list) if draw_list.CmdBuffer.Size == 0 then return @@ -29047,12 +33373,15 @@ function ImGui.AddDrawListToDrawDataEx(draw_data, out_list, draw_list) return end + -- Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. + -- May trigger for you if you are using PrimXXX functions incorrectly. IM_ASSERT(draw_list.VtxBuffer.Size == 0 or draw_list._VtxWritePtr == draw_list.VtxBuffer.Size + 1) IM_ASSERT(draw_list.IdxBuffer.Size == 0 or draw_list._IdxWritePtr == draw_list.IdxBuffer.Size + 1) if (bit32.band(draw_list.Flags, ImDrawListFlags.AllowVtxOffset) == 0) then IM_ASSERT(draw_list._VtxCurrentIdx == draw_list.VtxBuffer.Size + 1) end + -- Add to output list + records state in ImDrawData out_list:push_back(draw_list) draw_data.TotalVtxCount = draw_data.TotalVtxCount + draw_list.VtxBuffer.Size draw_data.TotalIdxCount = draw_data.TotalIdxCount + draw_list.IdxBuffer.Size @@ -29070,6 +33399,10 @@ local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD, _MAXERROR) return ImCl local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N, _MAXERROR) return (_MAXERROR / (1 - ImCos(IM_PI / ImMax(_N, IM_PI)))) end local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N, _RAD) return ((1 - ImCos(IM_PI / ImMax(_N, IM_PI))) / _RAD) end +------------------------------------------------------------------------------- +-- [SECTION] ImDrawList +------------------------------------------------------------------------------- + function MT.ImDrawListSharedData:SetCircleTessellationMaxError(max_error) if self.CircleTessellationMaxError == max_error then return @@ -29097,6 +33430,8 @@ function MT.ImDrawList:_SetDrawListSharedData(data) end end +-- 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 PushTexture() after this. -- TODO: function MT.ImDrawList:_ResetForNewFrame() self._ContentClipX0 = nil -- set again by Begin() (Roblox backend scroll reuse) @@ -29146,7 +33481,7 @@ end function MT.ImDrawList:AddDrawCmd() local draw_cmd = ImDrawCmd() - ImVec4_Copy(draw_cmd.ClipRect, self._CmdHeader.ClipRect) -- Same as calling ImDrawCmd_HeaderCopy()? + ImVec4_Copy(draw_cmd.ClipRect, self._CmdHeader.ClipRect) -- Same as calling ImDrawCmd_HeaderCopy() draw_cmd.TexRef = self._CmdHeader.TexRef draw_cmd.VtxOffset = self._CmdHeader.VtxOffset draw_cmd.IdxOffset = self.IdxBuffer.Size @@ -29155,11 +33490,13 @@ function MT.ImDrawList:AddDrawCmd() self.CmdBuffer:push_back(draw_cmd) end +-- Pop trailing draw command (used before merging or presenting to user) +-- Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == nil function MT.ImDrawList:_PopUnusedDrawCmd() while self.CmdBuffer.Size > 0 do local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] if curr_cmd.ElemCount ~= 0 or curr_cmd.UserCallback ~= nil then - break + break -- return;// break; end self.CmdBuffer:pop_back() @@ -29184,6 +33521,7 @@ function MT.ImDrawList:AddCallback(callback, userdata, userdata_size) curr_cmd.UserCallback = callback -- TODO: _CallbacksDataBuf? if userdata_size == 0 then + -- Store user data directly in command (no indirection) curr_cmd.UserCallbackData = userdata else @@ -29192,7 +33530,7 @@ function MT.ImDrawList:AddCallback(callback, userdata, userdata_size) end - self:AddDrawCmd() + self:AddDrawCmd() -- Force a new command after us (see comment below) end --- Compare ClipRect, TexRef, VtxOffset @@ -29240,6 +33578,7 @@ local function ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1) return CMD_0.IdxOffset + CMD_0.ElemCount == CMD_1.IdxOffset end +-- Try to merge two last draw commands function MT.ImDrawList:_TryMergeDrawCmds() IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] @@ -29250,7 +33589,10 @@ function MT.ImDrawList:_TryMergeDrawCmds() end end +-- Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. +-- The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. function MT.ImDrawList:_OnChangedClipRect() + -- If current command is used with different settings we need to add a new command IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] if (curr_cmd.ElemCount ~= 0 and self._CmdHeader.ClipRect ~= curr_cmd.ClipRect) then @@ -29261,6 +33603,7 @@ function MT.ImDrawList:_OnChangedClipRect() IM_ASSERT(curr_cmd.UserCallback == nil) + -- Try to merge with previous command if it matches, else use current command local prev_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size - 1] if (curr_cmd.ElemCount == 0 and self.CmdBuffer.Size > 1 and ImDrawCmd_HeaderCompare(self._CmdHeader, prev_cmd) and ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) and prev_cmd.UserCallback == nil) then self.CmdBuffer:pop_back() @@ -29272,6 +33615,7 @@ function MT.ImDrawList:_OnChangedClipRect() end function MT.ImDrawList:_OnChangedTexture() + -- If current command is used with different settings we need to add a new command IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] if curr_cmd.ElemCount ~= 0 and curr_cmd.TexRef ~= self._CmdHeader.TexRef then @@ -29280,10 +33624,12 @@ function MT.ImDrawList:_OnChangedTexture() return end + -- Unlike other _OnChangedXXX functions this may be called by ImFontAtlasUpdateDrawListsTextures() in more locations so we need to handle this case. if curr_cmd.UserCallback ~= nil then return end + -- Try to merge with previous command if it matches, else use current command local prev_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size - 1] if curr_cmd.ElemCount == 0 and self.CmdBuffer.Size > 1 and ImDrawCmd_HeaderCompare(self._CmdHeader, prev_cmd) and ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) and prev_cmd.UserCallback == nil then self.CmdBuffer:pop_back() @@ -29295,10 +33641,12 @@ function MT.ImDrawList:_OnChangedTexture() end function MT.ImDrawList:_OnChangedVtxOffset() + -- We don't need to compare curr_cmd.VtxOffset ~= _CmdHeader.VtxOffset because we know it'll be different at the time we call this. self._VtxCurrentIdx = 1 IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] + --IM_ASSERT(curr_cmd.VtxOffset ~= self._CmdHeader.VtxOffset) -- See #3349 if curr_cmd.ElemCount ~= 0 then self:AddDrawCmd() return @@ -29307,9 +33655,11 @@ function MT.ImDrawList:_OnChangedVtxOffset() curr_cmd.VtxOffset = self._CmdHeader.VtxOffset end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] ImDrawListSplitter ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. +------------------------------------------------------------------------------- -- Lua: channels swap ImVector objects with the draw list (C++ memcpy of the vector headers). -- Channel 0 holds nothing while it is the current channel (its buffers live in the draw list). @@ -29347,11 +33697,14 @@ function MT.ImDrawListSplitter:Split(draw_list, channels_count) IM_ASSERT(self._Current == 0 and self._Count <= 1, "Nested channel splitting is not supported. Please use separate instances of ImDrawListSplitter.") local old_channels_count = self._Channels.Size if old_channels_count < channels_count then - self._Channels:reserve(channels_count) + self._Channels:reserve(channels_count) -- Avoid over reserving since this is likely to stay stable self._Channels:resize(channels_count) end self._Count = channels_count + -- Channels[] hold storage that we'll swap with draw_list._CmdBuffer/_IdxBuffer + -- The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + -- When we switch to the next channel, we'll copy draw_list._CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list.CmdBuffer/_IdxBuffer -- Channel 0 is the draw list itself (memset to 0 in C++) local channels = self._Channels.Data channels[1] = { _CmdBuffer = nil, _IdxBuffer = nil } @@ -29486,6 +33839,8 @@ function MT.ImDrawList:ChannelsMerge() self._Splitter:Merge(self) end --- @param n int # 0-based function MT.ImDrawList:ChannelsSetCurrent(n) self._Splitter:SetCurrentChannel(self, n) end +-- - We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds. +-- - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. --- @param points ImVec2[] --- @param points_count int --- @param col ImU32 @@ -29513,6 +33868,7 @@ function MT.ImDrawList:AddConvexPolyFilled(points, points_count, col) self._IdxWritePtr = idx_write_ptr + 3 end + -- Compute normals self._Data.TempBuffer:reserve_discard(points_count) local temp_normals = self._Data.TempBuffer.Data @@ -29589,6 +33945,7 @@ function MT.ImDrawList:PopTexture() self:_OnChangedTexture() end +-- This is used by ImGui.PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTexture()/PopTexture(). function MT.ImDrawList:_SetTexture(tex_ref) if (self._CmdHeader.TexRef == tex_ref) then return @@ -29598,11 +33955,18 @@ function MT.ImDrawList:_SetTexture(tex_ref) self:_OnChangedTexture() end +-- Reserve space for a number of vertices and indices. +-- You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or +-- submit the intermediate results. PrimUnreserve() can be used to release unused allocations. function MT.ImDrawList:PrimReserve(idx_count, vtx_count) + -- Large mesh support (when enabled) IM_ASSERT_PARANOID(idx_count >= 0 and vtx_count >= 0) if (self._VtxCurrentIdx + vtx_count >= bit32.lshift(1, 16)) and (bit32.band(self.Flags, ImDrawListFlags.AllowVtxOffset) ~= 0) then + -- FIXME: In theory we should be testing that vtx_count <64k here. + -- In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us + -- to not make that check until we rework the text functions to handle clipping and large horizontal lines better. self._CmdHeader.VtxOffset = self.VtxBuffer.Size + 1 self:_OnChangedVtxOffset() end @@ -29619,6 +33983,7 @@ function MT.ImDrawList:PrimReserve(idx_count, vtx_count) self._IdxWritePtr = idx_buffer_old_size + 1 end +-- Release the number of reserved vertices/indices from the end of the last reservation made with PrimReserve(). function MT.ImDrawList:PrimUnreserve(idx_count, vtx_count) IM_ASSERT_PARANOID(idx_count >= 0 and vtx_count >= 0) @@ -29632,6 +33997,7 @@ function MT.ImDrawList:PrimUnreserve(idx_count, vtx_count) self._IdxWritePtr = self.IdxBuffer.Size + 1 end +-- Fully unrolled with inline call to keep our debug builds decently fast. --- @param a ImVec2 --- @param c ImVec2 --- @param col ImU32 @@ -29709,6 +34075,10 @@ function MT.ImDrawList:AddPolyline(points, points_count, col, thickness, flags) local opaque_uv = self._Data.TexUvWhitePixel local count = closed and points_count or points_count - 1 -- Number of line segments local thick_line = thickness > self._FringeScale + -- If this assert triggers on legacy code: + -- - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. + -- - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. + -- Read more details near AddRect() + see "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?") if bit32.band(self.Flags, ImDrawListFlags.AntiAliasedLines) ~= 0 then @@ -29974,6 +34344,8 @@ function MT.ImDrawList:AddRectFilled(p_min, p_max, col, rounding, flags) end end +-- p_min = upper-left, p_max = lower-right +-- Note: this does not support anti-aliasing when provided non-integer vertices. --- @param p_min ImVec2 --- @param p_max ImVec2 --- @param col_upr_left ImU32 @@ -29995,6 +34367,7 @@ function MT.ImDrawList:AddRectFilledMultiColor(p_min, p_max, col_upr_left, col_u self:PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left) end +-- p_min = upper-left, p_max = lower-right --- @param p_min ImVec2 --- @param p_max ImVec2 --- @param col ImU32 @@ -30006,7 +34379,16 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) if thickness == nil then thickness = 1.0 end if flags == nil then flags = 0 end - IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?") + -- If this assert triggers on legacy code: + -- - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. + -- - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. + -- - 1.82.0 (2021/03): changed ImDrawCornerFlags to ImDrawFlags_RoundXXX values. + -- If you used hard-coded 1 to 15 or ~0 in flags to configure corner rounding use the new flags! + -- - Hard coded support for ~0 == ImDrawFlags_RoundAll. + -- - Hard coded support for values 0x01 to 0x0F (matching 15 out of 16 old flags combinations) --> see FixRectCornerFlags() in <1.90 code. + -- - Hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundNone or use 'float rounding = 0.0f'. + -- See "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. + IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?") -- Or misuse of legacy hard-coded ImDrawCornerFlags values if bit32.band(col, IM_COL32_A_MASK) == 0 then return @@ -30025,7 +34407,7 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) if bit32.band(self.Flags, ImDrawListFlags.AntiAliasedLines) ~= 0 then self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.50, 0.50), rounding, flags) else - self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.49, 0.49), rounding, flags) + self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.49, 0.49), rounding, flags) -- Better looking lower-right corner and rounded non-AA shapes. end self:PathStroke(col, thickness, ImDrawFlags.Closed) @@ -30188,10 +34570,13 @@ function MT.ImDrawList:AddText(font, font_size, pos, col, text, text_begin, text if bit32.band(col, IM_COL32_A_MASK) == 0 then return end + -- Accept null ranges if text_begin == text_end then return end + -- 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 == nil then font = self._Data.Font end @@ -30252,7 +34637,7 @@ function MT.ImDrawList:AddImageRounded(tex_ref, p_min, p_max, uv_min, uv_max, co return end - IM_ASSERT(bit32.band(flags, 0x0F) == 0, "Misuse of legacy hardcoded ImDrawCornerFlags values!") + IM_ASSERT(bit32.band(flags, 0x0F) == 0, "Misuse of legacy hardcoded ImDrawCornerFlags values!") -- If this assert triggers on legacy code: see comments in ImDrawList:PathRect(). if bit32.band(flags, ImDrawFlags.RoundCornersMask_) == 0 then flags = bit32.bor(flags, ImDrawFlags.RoundCornersAll) end @@ -30280,22 +34665,24 @@ end --- @param radius float function MT.ImDrawList:_CalcCircleAutoSegmentCount(radius) - local radius_idx = ImFloor(radius + 0.999) + 1 + -- Automatic segment count + local radius_idx = ImFloor(radius + 0.999) + 1 -- ceil to never reduce accuracy if radius_idx >= 1 and radius_idx <= 64 then -- IM_COUNTOF(_Data->CircleSegmentCounts) - return self._Data.CircleSegmentCounts[radius_idx] + return self._Data.CircleSegmentCounts[radius_idx] -- Use cached value else return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self._Data.CircleTessellationMaxError) end end +-- 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) function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_rect) local cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y) if intersect_with_current_clip_rect then local current = self._CmdHeader.ClipRect - if cr.x < current.x then cr.x = current.x end + if cr.x < current.x then cr.x = current.x end -- = ClipWith(). Note that passing inverted range wouldn't be fixed here. if cr.y < current.y then cr.y = current.y end if cr.z > current.z then cr.z = current.z end if cr.w > current.w then cr.w = current.w end @@ -30331,10 +34718,12 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp return end + -- Calculate arc auto segment step size if a_step <= 0 then a_step = math.floor(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / self:_CalcCircleAutoSegmentCount(radius)) end + -- Make sure we never do steps larger than one quarter of the circle a_step = ImClamp(a_step, 1, math.floor(IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4)) local sample_range = ImAbs(a_max_sample - a_min_sample) @@ -30350,6 +34739,8 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp extra_max_sample = true samples = samples + 1 + -- When we have overstep to avoid awkwardly looking one long line and one tiny one at the end, + -- distribute first step range evenly between them by reducing first step size. if sample_range > 0 then a_step = a_step - math.floor((a_step - overstep) / 2) end @@ -30370,6 +34761,7 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp if a_max_sample >= a_min_sample then local a = a_min_sample while a <= a_max_sample do + -- a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more if sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX then sample_index = sample_index - IM_DRAWLIST_ARCFAST_SAMPLE_MAX end @@ -30385,6 +34777,7 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp else local a = a_min_sample while a >= a_max_sample do + -- a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more if sample_index < 0 then sample_index = sample_index + IM_DRAWLIST_ARCFAST_SAMPLE_MAX end @@ -30413,6 +34806,7 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp IM_ASSERT_PARANOID(self._Path.Size == out_ptr - 1) end +-- 0: East, 3: South, 6: West, 9: North, 12: East function MT.ImDrawList:PathArcToFast(center, radius, a_min_of_12, a_max_of_12) if radius < 0.5 then @@ -30461,9 +34855,12 @@ function MT.ImDrawList:PathArcTo(center, radius, a_min, a_max, num_segments) return end + -- Automatic segment count if radius <= self._Data.ArcFastRadiusCutoff then local a_is_reverse = a_max < a_min + -- We are going to use precomputed values for mid samples. + -- Determine first and last sample in lookup table that belong to the arc. local a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0) local a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0) @@ -30490,7 +34887,8 @@ function MT.ImDrawList:PathArcTo(center, radius, a_min, a_max, num_segments) end end --- Not recommended to call this directly! +-- Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. +-- DO NOT CALL DIRECTLY THIS WILL CHANGE WILDLY IN 2026. Use ImDrawList:AddText(). --- @param draw_list ImDrawList --- @param size float --- @param pos ImVec2 @@ -30506,6 +34904,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b if wrap_width == nil then wrap_width = .0 end if flags == nil then flags = 0 end + -- Align to be pixel perfect local x = pos.x local y = pos.y if y > clip_rect.w then @@ -30526,11 +34925,15 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b local origin_x = x local word_wrap_enabled = (wrap_width > 0.0) + -- Fast-forward to first visible line local s = text_begin if y + line_height < clip_rect.y then while y + line_height < clip_rect.y and s < text_end do local line_end = ImMemchr(text, '\n', s) if word_wrap_enabled then + -- 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 = ImFontCalcWordWrapPositionEx(self, size, text, s, (line_end ~= nil) and line_end or text_end, wrap_width, flags) s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) else @@ -30541,6 +34944,8 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b end end + -- For large text, scan for the last visible line in order to avoid over-reserving in the call to PrimReserve() + -- Note that very large horizontal line will still be affected by the issue (e.g. a one megabyte string buffer without a newline will likely crash atm) if text_end - s > 1e4 and not word_wrap_enabled then local s_end = s local y_end = y @@ -30557,6 +34962,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b return end + -- Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) local vtx_count_max = (text_end - s) * 4 local idx_count_max = (text_end - s) * 6 local idx_expected_size = draw_list.IdxBuffer.Size + idx_count_max @@ -30579,6 +34985,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b while s < text_end do repeat if word_wrap_enabled then + -- 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 not word_wrap_eol then word_wrap_eol = ImFontCalcWordWrapPositionEx(self, size, text, s, text_end, wrap_width - (x - origin_x), flags) end @@ -30587,15 +34994,16 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b x = origin_x y = y + line_height if y > clip_rect.w then - stop = true; break + stop = true; break -- break out of main loop end word_wrap_eol = nil - s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) + s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks break end end + -- Decode and advance source local c if text_is_str then c = string.byte(text, s) else c = text[s] end if c < 0x80 then @@ -30611,7 +35019,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b x = origin_x y = y + line_height if y > clip_rect.w then - stop = true; break + stop = true; break -- break out of main loop end break @@ -30633,16 +35041,19 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b local char_width = glyph.AdvanceX * scale if glyph.Visible then + -- We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w local x1 = x + glyph.X0 * scale local x2 = x + glyph.X1 * scale local y1 = y + glyph.Y0 * scale local y2 = y + glyph.Y1 * scale if x1 <= clip_rect.z and x2 >= clip_rect.x then + -- Render a character local u1 = glyph.U0 local v1 = glyph.V0 local u2 = glyph.U1 local v2 = glyph.V1 + -- CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. if (cpu_fine_clip) then if (x1 < clip_rect.x) then u1 = u1 + (1.0 - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1) @@ -30667,8 +35078,10 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b end end + -- Support for untinted glyphs local glyph_col = glyph.Colored and color_untinted or col + -- We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here: do local o = (vtx_write - 1) * 36 writef64(vtx_data, o, x1); writef64(vtx_data, o + 8, y1); writef64(vtx_data, o + 16, u1); writef64(vtx_data, o + 24, v1); writeu32(vtx_data, o + 32, glyph_col) @@ -30690,7 +35103,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b if stop then break end end - -- Edge case: calling RenderText() with unloaded glyphs triggering texture change. It doesn't happen via ImGui.* calls because CalcTextSize() is always used + -- 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 then IM_ASSERT(draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount == 0) draw_list.CmdBuffer:pop_back() @@ -30700,7 +35113,8 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b return self:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags) -- was `goto begin` end - draw_list.VtxBuffer.Size = vtx_write - 1 + -- Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. + draw_list.VtxBuffer.Size = vtx_write - 1 -- Same as calling shrink() draw_list.IdxBuffer.Size = idx_write - 1 draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount = draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount - (idx_expected_size - draw_list.IdxBuffer.Size) draw_list._VtxWritePtr = vtx_write @@ -30708,6 +35122,22 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b draw_list._VtxCurrentIdx = vtx_index end +------------------------------------------------------------------------------- +-- [SECTION] ImGui Internal Render Helpers +------------------------------------------------------------------------------- +-- Vaguely redesigned to stop accessing ImGui global state: +-- - RenderArrow() +-- - RenderBullet() +-- - RenderCheckMark() +-- - RenderArrowPointingAt() +-- - RenderRectFilledInRangeH() +-- - RenderRectFilledWithHole() +------------------------------------------------------------------------------- +-- Function in need of a redesign (legacy mess) +-- - RenderColorRectWithAlphaCheckerboard() +------------------------------------------------------------------------------- + +-- Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state --- @param draw_list ImDrawList --- @param pos ImVec2 --- @param color ImU32 @@ -30748,7 +35178,7 @@ end --- @param pos ImVec2 --- @param col ImU32 function ImGui.RenderBullet(draw_list, pos, col) - -- FIXME-OPT: This should be baked in font now that it's easier + -- FIXME-OPT: This should be baked in font now that it's easier. local font_size = draw_list._Data.FontSize draw_list:AddCircleFilled(pos, font_size * 0.20, col, (font_size < 22) and 8 or ((font_size < 40) and 12 or 0)) -- Hardcode optimal/nice tessellation threshold end @@ -30772,7 +35202,7 @@ function ImGui.RenderCheckMark(draw_list, pos, col, sz) draw_list:PathStroke(col, thickness) end --- Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side +-- Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. --- @param draw_list ImDrawList --- @param pos ImVec2 --- @param half_sz ImVec2 @@ -30787,7 +35217,7 @@ function ImGui.RenderArrowPointingAt(draw_list, pos, half_sz, direction, col) draw_list:AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col) elseif direction == ImGuiDir.Down then draw_list:AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col) - elseif direction == ImGuiDir.None or direction == ImGuiDir.COUNT then + elseif direction == ImGuiDir.None or direction == ImGuiDir.COUNT then -- Fix warnings end end @@ -30795,9 +35225,12 @@ local function ImAcos01(x) if x <= 0.0 then return IM_PI * 0.5 end if x >= 1.0 then return 0.0 end return ImAcos(x) + --return (-0.69813170079773212 * x * x - 0.87266462599716477) * x + 1.5707963267948966 -- Cheap approximation, may be enough for what we do. end --- FIXME: Cleanup and move code to ImDrawList +-- FIXME: Cleanup and move code to ImDrawList. +-- - Before 2025-12-04: RenderRectFilledRangeH() with 'float x_start_norm, float x_end_norm` <- normalized +-- - After 2025-12-04: RenderRectFilledInRangeH() with 'float x1, float x2' <- absolute coords!! --- @param draw_list ImDrawList --- @param rect ImRect --- @param col ImU32 @@ -30933,7 +35366,7 @@ function ImGui.RenderColorRectWithAlphaCheckerboard(draw_list, p_min, p_max, col break end - cell_flags = ImDrawFlags.RoundCornersNone + cell_flags = ImDrawFlags.RoundCornersNone -- FIXME: Could use CalcRoundingFlagsForRectInRect() if y1 <= p_min.y then if x1 <= p_min.x then cell_flags = bit32.bor(cell_flags, ImDrawFlags.RoundCornersTopLeft) end if x2 >= p_max.x then cell_flags = bit32.bor(cell_flags, ImDrawFlags.RoundCornersTopRight) end @@ -30986,14 +35419,14 @@ function ImGui.RenderRectFilledWithHole(draw_list, outer, inner, col, rounding) if fill_R and fill_D then draw_list:AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, D.RoundCornersBottomRight) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- Extra primitives (Ngon, Ellipse, Bezier, concave fill) ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [port] These follow the 1.92 stroker this port uses (no ImDrawFlags_StrokeXXX placement flags). function MT.ImDrawList:PathEllipticalArcTo(center, radius, rot, a_min, a_max, num_segments) if num_segments == nil or num_segments <= 0 then - num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) + num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) -- A bit pessimistic, maybe there's a better computation to do here. end local cos_rot, sin_rot = ImCos(rot), ImSin(rot) for i = 0, num_segments do @@ -31015,6 +35448,7 @@ function ImBezierQuadraticCalc(p1, p2, p3, t) return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x, w1 * p1.y + w2 * p2.y + w3 * p3.y) end +-- Closely mimics ImBezierCubicClosestPointCasteljau() in imgui.cpp local function PathBezierCubicCurveToCasteljau(path, x1, y1, x2, y2, x3, y3, x4, y4, tess_tol, level) local dx, dy = x4 - x1, y4 - y1 local d2 = math.abs((x2 - x4) * dy - (y2 - y4) * dx) @@ -31050,7 +35484,7 @@ end function MT.ImDrawList:PathBezierCubicCurveTo(p2, p3, p4, num_segments) local p1 = self._Path:back() if num_segments == nil or num_segments == 0 then - PathBezierCubicCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, self._Data.CurveTessellationTol, 0) + PathBezierCubicCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, self._Data.CurveTessellationTol, 0) -- Auto-tessellated else local t_step = 1.0 / num_segments for i_step = 1, num_segments do self._Path:push_back(ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step)) end @@ -31060,33 +35494,39 @@ end function MT.ImDrawList:PathBezierQuadraticCurveTo(p2, p3, num_segments) local p1 = self._Path:back() if num_segments == nil or num_segments == 0 then - PathBezierQuadraticCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, self._Data.CurveTessellationTol, 0) + PathBezierQuadraticCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, self._Data.CurveTessellationTol, 0) -- Auto-tessellated else local t_step = 1.0 / num_segments for i_step = 1, num_segments do self._Path:push_back(ImBezierQuadraticCalc(p1, p2, p3, t_step * i_step)) end end end +-- Guaranteed to honor 'num_segments' function MT.ImDrawList:AddNgon(center, radius, col, num_segments, thickness) if thickness == nil then thickness = 1.0 end if bit32.band(col, IM_COL32_A_MASK) == 0 or num_segments <= 2 then return end + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = (IM_PI * 2.0) * (num_segments - 1.0) / num_segments self:PathArcTo(center, radius - 0.5, 0.0, a_max, num_segments - 1) self:PathStroke(col, thickness, ImDrawFlags.Closed) end +-- Guaranteed to honor 'num_segments' function MT.ImDrawList:AddNgonFilled(center, radius, col, num_segments) if bit32.band(col, IM_COL32_A_MASK) == 0 or num_segments <= 2 then return end + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = (IM_PI * 2.0) * (num_segments - 1.0) / num_segments self:PathArcTo(center, radius, 0.0, a_max, num_segments - 1) self:PathFillConvex(col) end +-- Ellipse function MT.ImDrawList:AddEllipse(center, radius, col, rot, num_segments, thickness) if rot == nil then rot = 0.0 end if thickness == nil then thickness = 1.0 end if bit32.band(col, IM_COL32_A_MASK) == 0 then return end - if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end + if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end -- A bit pessimistic, maybe there's a better computation to do here. + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = IM_PI * 2.0 * (num_segments - 1.0) / num_segments self:PathEllipticalArcTo(center, radius, rot, 0.0, a_max, num_segments - 1) self:PathStroke(col, thickness, ImDrawFlags.Closed) @@ -31095,12 +35535,14 @@ end function MT.ImDrawList:AddEllipseFilled(center, radius, col, rot, num_segments) if rot == nil then rot = 0.0 end if bit32.band(col, IM_COL32_A_MASK) == 0 then return end - if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end + if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end -- A bit pessimistic, maybe there's a better computation to do here. + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = IM_PI * 2.0 * (num_segments - 1.0) / num_segments self:PathEllipticalArcTo(center, radius, rot, 0.0, a_max, num_segments - 1) self:PathFillConvex(col) end +-- Cubic Bezier takes 4 controls points function MT.ImDrawList:AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments) if bit32.band(col, IM_COL32_A_MASK) == 0 then return end self:PathLineTo(p1) @@ -31108,6 +35550,7 @@ function MT.ImDrawList:AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segmen self:PathStroke(col, thickness or 1.0) end +-- Quadratic Bezier takes 3 controls points function MT.ImDrawList:AddBezierQuadratic(p1, p2, p3, col, thickness, num_segments) if bit32.band(col, IM_COL32_A_MASK) == 0 then return end self:PathLineTo(p1) @@ -31167,8 +35610,35 @@ return true -- [Roblox] ModuleScripts must return exactly one value end __FILES['imgui_h.lua'] = function() ---- Dear ImGui WIP --- (Definitions) +-- dear imgui, v1.93.0 WIP +-- (headers) + +-- Help: +-- - Call and read ImGui.ShowDemoWindow() in imgui_demo.lua. All applications in examples/ are doing that. +-- - Read top of imgui.lua for more details, links and comments. + +-- Resources: +-- - FAQ ........................ https://dearimgui.com/faq +-- - Homepage ................... https://github.com/ocornut/imgui +-- - Releases & Changelog ....... https://github.com/ocornut/imgui/releases +-- - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) +-- - Issues & support ........... https://github.com/ocornut/imgui/issues + +-- Index of this file: +-- [SECTION] Forward declarations and basic types +-- [SECTION] METATABLE MANAGEMENT +-- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> +-- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) +-- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +-- [SECTION] Texture identifiers (ImTextureID, ImTextureRef) +-- [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) +-- [SECTION] ImGuiIO +-- [SECTION] Viewports +-- [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) +-- [SECTION] Flags & Enumerations +-- [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) +-- [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +-- [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) --- @meta @@ -31179,6 +35649,11 @@ local rawget = rawget; local rawset = rawset local bitAnd = bit32.band; local bitOr = bit32.bor local bitLShift = bit32.lshift +------------------------------------------------------------------------------- +-- [SECTION] Forward declarations and basic types +------------------------------------------------------------------------------- + +-- Scalar data types --- @class char : integer --- @class unsigned_char : integer @@ -31223,25 +35698,42 @@ function ImS32(val) return bitAnd(val, 0xFFFFFFFF) end --- @alias size_t unsigned_int +-- 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) --- @alias ImWchar16 unsigned_short --- @alias ImWchar ImWchar16 --- @alias bool boolean +-- A unique ID used by widgets (typically the result of hashing a stack of string) --- @alias ImGuiID unsigned_int +-- 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. --- @alias ImTextureID integer +-- ImGuiKey | ImGuiMod_XXX: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. --- @alias ImGuiKeyChord int +-- ImDrawIdx: vertex index. [Compile-time configurable type] --- @alias ImDrawIdx unsigned_int +-- Library Version +-- (Integer encoded as XYYZZ for use in conditionals, e.g. 'if IMGUI_VERSION_NUM >= 12345') IMGUI_VERSION = "1.93.0 WIP" IMGUI_VERSION_NUM = 19298 -IM_UNICODE_CODEPOINT_INVALID = 0xFFFD -IM_UNICODE_CODEPOINT_MAX = 0xFFFF +-- Helper: Unicode defines +IM_UNICODE_CODEPOINT_INVALID = 0xFFFD -- Invalid Unicode code point (standard value). +IM_UNICODE_CODEPOINT_MAX = 0xFFFF -- Maximum Unicode code point supported by this build. +-- IM_ALLOC(), IM_FREE(), IM_DELETE() IM_ALLOC = ImGui.MemAlloc IM_FREE = ImGui.MemFree @@ -31249,9 +35741,9 @@ IM_FREE = ImGui.MemFree --- @param field string|int IM_DELETE = function(owner, field) if owner[field] ~= nil then owner[field] = nil; ImGui.MemFree(owner, field); end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] METATABLE MANAGEMENT ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- File-scope metatable storage local MT = {} @@ -31264,11 +35756,12 @@ function IM_ASSERT(_EXPR, _MSG) assert((_EXPR), _MSG) end IM_ASSERT_PARANOID = IM_ASSERT +-- A primary data type --- Note that `S64` and `U64` are not supported --- @enum ImGuiDataType ImGuiDataType = { - S8 = 0, -- signed char / char + S8 = 0, -- signed char / char (with sensible compilers) U8 = 1, -- unsigned char S16 = 2, -- short U16 = 3, -- unsigned short @@ -31280,37 +35773,43 @@ ImGuiDataType = String = 9, -- string (provided for user convenience, not supported by scalar widgets) COUNT = 10 } +-- Extend ImGuiDataType_ ImGuiDataType.Pointer = 11 -- [internal] ImGuiDataType.ID = 12 -- [internal] ImTextureID_Invalid = -1 +-- 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 = 0, - Alpha8 = 1, + RGBA32 = 0, -- 4 components per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + Alpha8 = 1, -- 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 = 0, - Destroyed = 1, - WantCreate = 2, - WantUpdates = 3, - WantDestroy = 4, + Destroyed = 1, -- Backend destroyed the texture. + WantCreate = 2, -- Requesting backend to create the texture. Set status OK when done. + WantUpdates = 3, -- Requesting backend to update specific blocks of pixels (write to texture portions which have never been used before). Set status OK when done. + WantDestroy = 4, -- Requesting backend to destroy the texture. Set status to Destroyed when done. } +-- Flags for ImFontAtlas build --- @enum ImFontAtlasFlags ImFontAtlasFlags = { None = 0, - NoPowerOfTwoHeight = bitLShift(1, 0), - NoMouseCursors = bitLShift(1, 1), - NoBakedLines = bitLShift(1, 2) + NoPowerOfTwoHeight = bitLShift(1, 0), -- Don't round the height to next power of two + NoMouseCursors = bitLShift(1, 1), -- Don't build software mouse cursors into the atlas (save a little texture memory) + NoBakedLines = bitLShift(1, 2) -- Don't build anti-aliased line textures into the atlas (save a little texture memory). SINCE 1.93.0 THIS PREVENTS ANTI-ALIASED LINES FROM WORKING AND WILL DISABLE THEM. } +-- A cardinal direction --- @enum ImGuiDir ImGuiDir = { @@ -31322,6 +35821,8 @@ ImGuiDir = COUNT = 4 } +-- Identify a mouse button. +-- Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. --- @enum ImGuiMouseButton ImGuiMouseButton = { @@ -31331,24 +35832,29 @@ ImGuiMouseButton = COUNT = 5 } +-- Enumeration for GetMouseCursor() +-- User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here --- @enum ImGuiMouseCursor ImGuiMouseCursor = { None = -1, Arrow = 0, - TextInput = 1, - ResizeAll = 2, - ResizeNS = 3, - ResizeEW = 4, - ResizeNESW = 5, - ResizeNWSE = 6, - Hand = 7, - Wait = 8, - Progress = 9, - NotAllowed = 10, + TextInput = 1, -- When hovering over InputText, etc. + ResizeAll = 2, -- (Unused by Dear ImGui functions) + ResizeNS = 3, -- When hovering over a horizontal border + ResizeEW = 4, -- When hovering over a vertical border or a column + ResizeNESW = 5, -- When hovering over the bottom-left corner of a window + ResizeNWSE = 6, -- When hovering over the bottom-right corner of a window + Hand = 7, -- (Unused by Dear ImGui functions. Use for e.g. hyperlinks) + Wait = 8, -- When waiting for something to process/load. + Progress = 9, -- When waiting for something to process/load, but application is still interactive. + NotAllowed = 10, -- When hovering something with disallowed interaction. Usually a crossed circle. COUNT = 11 } +-- 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. --- @class ImTextureRect --- @field x unsigned_short --- @field y unsigned_short @@ -31362,6 +35868,7 @@ ImGuiMouseCursor = --- @return ImTextureRect function ImTextureRect(x, y, w, h) return { x = x, y = y, w = w, h = h } end +-- ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type] -- [Luau] Stored as named fields {x=, y=} so the common `.x`/`.y` access is a plain table read (no metamethod call). -- Numeric keys 1, 2 still work through the metatable, but are slower: prefer .x/.y in hot code. --- @class ImVec2 @@ -31431,6 +35938,7 @@ function ImVec2_MulVX(a, scalar) return a.x * scalar, a.y * scalar end --- An inlined version of `ImVec2_Copy` currently for use in certain ImVector `push_back` local function ImVec2_TCopy(t, k, v) local dest = t[k]; dest.x = v.x; dest.y = v.y; end +-- ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] -- [Luau] Same layout as ImVec2: named fields x, y, z, w; numeric keys 1..4 go through the metatable. --- @class ImVec4 --- @operator add(ImVec4): ImVec4 @@ -31471,6 +35979,11 @@ function IM_VEC4:__tostring() return string.format("ImVec4(%g, %g, %g, %g)", sel function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z; dest.w = src.w end +------------------------------------------------------------------------------- +-- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> +------------------------------------------------------------------------------- + +-- ImVector<> --- A compact ImVector clone --- @class ImVector --- @field Data T[] # 1-based table @@ -31577,6 +36090,16 @@ function IM_VECTOR:index_from_ptr(p) IM_ASSERT(false, "index_from_ptr failed!") end +------------------------------------------------------------------------------- +-- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) +------------------------------------------------------------------------------- + +-- Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. + +-- Typically, 1 command = 1 GPU draw call (unless command is a callback) +-- - 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. --- @class ImDrawCmd --- @field ClipRect ImVec4 --- @field TexRef ImTextureRef @@ -31594,15 +36117,15 @@ IM_DRAWCMD.__index = IM_DRAWCMD --- @nodiscard function ImDrawCmd() return setmetatable({ - ClipRect = ImVec4(), - TexRef = nil, - VtxOffset = 0, - IdxOffset = 0, - ElemCount = 0, - UserCallback = nil, - UserCallbackData = nil, - UserCallbackDataSize = 0, - UserCallbackDataOffset = 0 + ClipRect = ImVec4(), -- 4*4 -- Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates + TexRef = nil, -- 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. + VtxOffset = 0, -- 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. + IdxOffset = 0, -- 4 -- Start offset in index buffer. + ElemCount = 0, -- 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[]. + UserCallback = nil, -- 4-8 -- If != nil, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + UserCallbackData = nil, -- 4-8 -- Callback user data (when UserCallback != nil). If called AddCallback() with size == 0, this is a copy of the AddCallback() argument. If called AddCallback() with size > 0, this is pointing to a buffer where data is stored. + UserCallbackDataSize = 0, -- 4 -- Size of callback user data when using storage, otherwise 0. + UserCallbackDataOffset = 0 -- 4 -- [Internal] Offset of callback user data when using storage, otherwise -1. }, IM_DRAWCMD) end @@ -31615,6 +36138,7 @@ function IM_DRAWCMD:GetTexID() return tex_id end +-- Vertex layout --- @class ImDrawVert --- @field [1] ImVec2 # pos --- @field [2] ImVec2 # uv @@ -31648,6 +36172,7 @@ function IM_VTXBUF:clear() self.Size = 0; self.Capacity = 0; self.Buf = buffer.c function ImDrawVtx_Pos(b, i) local o = (i - 1) * VTX_STRIDE; return buffer.readf64(b, o), buffer.readf64(b, o + 8) end function ImDrawVtx_Col(b, i) return buffer.readu32(b, (i - 1) * VTX_STRIDE + 32) end +-- [Internal] For use by ImDrawList --- @class ImDrawCmdHeader --- @field ClipRect ImVec4 --- @field TexRef ImTextureRef @@ -31657,6 +36182,7 @@ function ImDrawVtx_Col(b, i) return buffer.readu32(b, (i - 1) * VTX_STRIDE + 32) --- @nodiscard function ImDrawCmdHeader() return { ClipRect = ImVec4(), TexRef = nil, VtxOffset = 0 } end +-- [Internal] For use by ImDrawListSplitter --- @class ImDrawChannel --- @field _CmdBuffer ImVector --- @field _IdxBuffer ImVector @@ -31665,6 +36191,8 @@ function ImDrawCmdHeader() return { ClipRect = ImVec4(), TexRef = nil, VtxOffset --- @nodiscard function ImDrawChannel() return { _CmdBuffer = ImVector(), _IdxBuffer = ImVector() } end +-- 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. --- @class ImDrawListSplitter --- @field _Current int --- @field _Count int @@ -31676,6 +36204,15 @@ MT.ImDrawListSplitter = {} -- methods in imgui_draw.lua MT.ImDrawListSplitter.__index = MT.ImDrawListSplitter function ImDrawListSplitter() return setmetatable({ _Current = 0, _Count = 0, _Channels = ImVector() }, MT.ImDrawListSplitter) end +-- Draw command list +-- This is the low-level list of polygons that ImGui.* functions are filling. At the end of the frame, +-- all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +-- Each dear imgui window contains its own ImDrawList. You can use ImGui.GetWindowDrawList() to +-- access the current window draw list and draw custom primitives. +-- You can interleave normal ImGui.* calls and adding primitives to the current draw list. +-- 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 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. --- @class ImDrawList --- @field CmdBuffer ImVector --- @field IdxBuffer ImVector @@ -31728,24 +36265,26 @@ end function ImDrawList(data) --- @type ImDrawList local this = setmetatable({ - CmdBuffer = ImVector(), - IdxBuffer = ImVector(), - VtxBuffer = ImDrawVtxBuffer(), - Flags = 0, + -- This is what you have to render + CmdBuffer = ImVector(), -- Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. + IdxBuffer = ImVector(), -- Index buffer. Each command consume ImDrawCmd::ElemCount of those + VtxBuffer = ImDrawVtxBuffer(), -- Vertex buffer. + Flags = 0, -- Current flags for drawing primitives. Alter with PushDrawFlag()/PopDrawFlags() to adjust defaults to a given scope. - _VtxCurrentIdx = 1, - _Data = nil, - _VtxWritePtr = 1, - _IdxWritePtr = 1, - _Path = ImVector(ImVec2, ImVec2_TCopy), - _CmdHeader = ImDrawCmdHeader(), - _Splitter = ImDrawListSplitter(), - _ClipRectStack = ImVector(), - _TextureStack = ImVector(), - _CallbacksDataBuf = nil, + -- [Internal, used while building lists] + _VtxCurrentIdx = 1, -- [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. + _Data = nil, -- Pointer to shared draw data (you can use ImGui.GetDrawListSharedData() to get the one from current ImGui context) + _VtxWritePtr = 1, -- [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + _IdxWritePtr = 1, -- [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + _Path = ImVector(ImVec2, ImVec2_TCopy), -- [Internal] current path building + _CmdHeader = ImDrawCmdHeader(), -- [Internal] template of active commands. Fields should match those of CmdBuffer.back(). + _Splitter = ImDrawListSplitter(), -- [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) + _ClipRectStack = ImVector(), -- [Internal] + _TextureStack = ImVector(), -- [Internal] + _CallbacksDataBuf = nil, -- [Internal] - _FringeScale = 0, - _OwnerName = nil + _FringeScale = 0, -- [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content + _OwnerName = nil -- Pointer to owner window's name for debugging }, MT.ImDrawList) this:_SetDrawListSharedData(data) @@ -31753,6 +36292,9 @@ function ImDrawList(data) return this end +-- All draw data to render a Dear ImGui frame +-- (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, +-- as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) --- @class ImDrawData --- @field Valid bool --- @field FrameCount int @@ -31772,12 +36314,23 @@ function ImDrawData() --- @type ImDrawData local this = setmetatable({}, MT.ImDrawData) - this.CmdLists = ImVector() + this.CmdLists = ImVector() -- Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. this:Clear() return this end +------------------------------------------------------------------------------- +-- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +------------------------------------------------------------------------------- + +-- 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 --- @class ImTextureData --- @field UniqueID int --- @field Status ImTextureStatus @@ -31805,22 +36358,23 @@ function ImTextureData() --- @type ImTextureData local this = setmetatable({}, MT.ImTextureData) - this.UniqueID = 0 - this.Status = ImTextureStatus.Destroyed - this.BackendUserData = nil - this.TexID = ImTextureID_Invalid - this.Format = 0 - this.Width = 0 - this.Height = 0 - this.BytesPerPixel = 0 - this.Pixels = nil - this.UsedRect = ImTextureRect() - this.UpdateRect = ImTextureRect() - this.Updates = ImVector() - this.UnusedFrames = 0 - this.RefCount = 0 - this.UseColors = false - this.WantDestroyNextFrame = false + -------------------------------------------- core / backend --------------------------------------- + this.UniqueID = 0 -- w - -- [DEBUG] Sequential index to facilitate identifying a texture when debugging/printing. Unique per atlas. + this.Status = ImTextureStatus.Destroyed -- rw rw -- ImTextureStatus.OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! + this.BackendUserData = nil -- - rw -- Convenience storage for backend. Some backends may have enough with TexID. + this.TexID = ImTextureID_Invalid -- 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. + this.Format = 0 -- w r -- ImTextureFormat.RGBA32 (default) or ImTextureFormat.Alpha8 + this.Width = 0 -- w r -- Texture width + this.Height = 0 -- w r -- Texture height + this.BytesPerPixel = 0 -- w r -- 4 or 1 + this.Pixels = nil -- w r -- Pointer to whole texture buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. + this.UsedRect = ImTextureRect() -- w r -- Bounding box encompassing all past and queued Updates[]. + this.UpdateRect = ImTextureRect() -- w r -- Bounding box encompassing all queued Updates[]. + this.Updates = ImVector() -- w r -- Array of individual updates. + this.UnusedFrames = 0 -- 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. + this.RefCount = 0 -- w r -- Number of contexts using this texture. Used during backend shutdown. + this.UseColors = false -- w r -- Tell whether our texture data is known to use colors (rather than just white + alpha). + this.WantDestroyNextFrame = false -- rw - -- [Internal] Queued to set ImTextureStatus.WantDestroy next frame. May still be used in the current frame. return this end @@ -31840,6 +36394,14 @@ function MT.ImTextureData:SetTexID(tex_id) self.TexID = tex_id end --- @param status ImTextureStatus function MT.ImTextureData:SetStatus(status) self.Status = status if (status == ImTextureStatus.Destroyed and not self.WantDestroyNextFrame and self.Pixels ~= nil) then self.Status = ImTextureStatus.WantCreate end end +------------------------------------------------------------------------------- +-- [SECTION] Texture identifiers (ImTextureID, ImTextureRef) +------------------------------------------------------------------------------- + +-- 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. --- @class ImTextureRef --- @field _TexData? ImTextureData --- @field _TexID ImTextureID @@ -31850,11 +36412,18 @@ IM_TEXTURE_REF.__index = IM_TEXTURE_REF --- @nodiscard function ImTextureRef(tex_id) return setmetatable({ - _TexData = nil, - _TexID = tex_id or ImTextureID_Invalid + -- Members (either are set, never both!) + _TexData = nil, -- A texture, generally owned by a ImFontAtlas. Will convert to ImTextureID during render loop, after texture has been uploaded. + _TexID = tex_id or ImTextureID_Invalid -- _OR_ Low-level backend texture identifier, if already uploaded or created by user/app. Generally provided to e.g. ImGui.Image() calls. }, IM_TEXTURE_REF) end +------------------------------------------------------------------------------- +-- [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) +------------------------------------------------------------------------------- + +-- Font runtime data for a given size +-- Important: pointers to ImFontBaked are only valid for the current frame. --- @class ImFontBaked --- @field IndexAdvanceX ImVector # Glyphs->AdvanceX in a directly indexable way. Note that codepoint starts from 0, so IndexAdvanceX.Data[0 + 1] holds the advanceX of glyph at codepoint 0 --- @field FallbackAdvanceX float @@ -31882,29 +36451,37 @@ function ImFontBaked() --- @type ImFontBaked local this = setmetatable({}, MT.ImFontBaked) - this.IndexAdvanceX = ImVector() - this.FallbackAdvanceX = 0 - this.Size = 0 - this.RasterizerDensity = 0 + -- [Internal] Members: Hot ~20/24 bytes (for CalcTextSize) + this.IndexAdvanceX = ImVector() -- 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). + this.FallbackAdvanceX = 0 -- 4 -- out -- FindGlyph(FallbackChar)->AdvanceX + this.Size = 0 -- 4 -- in -- Height of characters/line, set during loading (doesn't change after loading) + this.RasterizerDensity = 0 -- 4 -- in -- Density this is baked at - this.IndexLookup = ImVector() - this.Glyphs = ImVector() - this.FallbackGlyphIndex = -1 + -- [Internal] Members: Hot ~28/36 bytes (for RenderText loop) + this.IndexLookup = ImVector() -- 12-16 -- out -- Sparse. Index glyphs by Unicode code-point. + this.Glyphs = ImVector() -- 12-16 -- out -- All glyphs. + this.FallbackGlyphIndex = -1 -- 4 -- out -- Index of FontFallbackChar - this.Ascent = 0 + -- [Internal] Members: Cold + this.Ascent = 0 -- 4+4 -- out -- Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) this.Descent = 0 this.MetricsTotalSurface = 0 this.WantDestroy = false this.LoadNoFallback = false this.LoadNoRenderOnLayout = false - this.LastUsedFrame = 0 - this.BakedId = 0 - this.OwnerFont = nil - this.FontLoaderDatas = nil + this.LastUsedFrame = 0 -- 4 -- -- Record of that time this was bounds + this.BakedId = 0 -- 4 -- -- Unique ID for this baked storage + this.OwnerFont = nil -- 4-8 -- in -- Parent font + this.FontLoaderDatas = nil -- 4-8 -- -- Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader. return this end +-- Font runtime data and rendering +-- - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually. +-- - Since 1.92.0 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). --- @class ImFont --- @field LastBaked ImFontBaked --- @field OwnerAtlas ImFontAtlas @@ -31931,23 +36508,27 @@ function ImFont() --- @type ImFont local this = setmetatable({}, MT.ImFont) - this.LastBaked = nil - this.OwnerAtlas = nil - this.Flags = 0 - this.CurrentRasterizerDensity = 0 - this.FontId = 0 - this.LegacySize = 0 - this.Sources = ImVector() - this.EllipsisChar = 0 - this.FallbackChar = 0 + -- [Internal] Members: Hot ~12-20 bytes + this.LastBaked = nil -- 4-8 -- Cache last bound baked. NEVER USE DIRECTLY. Use GetFontBaked(). + this.OwnerAtlas = nil -- 4-8 -- What we have been loaded into. + this.Flags = 0 -- 4 -- Font flags. + this.CurrentRasterizerDensity = 0 -- 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. + this.FontId = 0 -- Unique identifier for the font + this.LegacySize = 0 -- 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). + this.Sources = ImVector() -- 16 -- in -- List of sources. Pointers within OwnerAtlas->Sources[] + this.EllipsisChar = 0 -- 2-4 -- out -- Character used for ellipsis rendering ('...'). If you ever want to temporarily swap this for an alternative/dummy char, make sure to clear EllipsisAutoBake. + this.FallbackChar = 0 -- 2-4 -- out -- Character used if a glyph isn't found (U+FFFD, '?') this.Used8kPagesMap = {} - this.EllipsisAutoBake = false - this.RemapPairs = {} + this.EllipsisAutoBake = false -- 1 -- -- Mark when the "..." glyph (== EllipsisChar) needs to be generated by combining multiple '.'. + this.RemapPairs = {} -- 16 -- -- Remapping pairs when using AddRemapCodepointXXX(). this.Scale = 0 return this end +-- A font input/source (we may rename this to ImFontSource in the future) --- @class ImFontConfig --- @field Name string --- @field FontData table @@ -31983,37 +36564,49 @@ function ImFontConfig() --- @type ImFontConfig local this = setmetatable({}, IM_FONT_CONFIG) - this.Name = nil - this.FontData = nil - this.FontDataSize = 0 - this.FontDataOwnedByAtlas = true + -- Data Source + this.Name = nil -- -- Name (strictly to ease debugging, hence limited size buffer) + this.FontData = nil -- TTF/OTF data + this.FontDataSize = 0 -- TTF/OTF data size + this.FontDataOwnedByAtlas = true -- true -- TTF/OTF data ownership taken by the owner ImFontAtlas (will delete memory itself). SINCE 1.92, THE DATA NEEDS TO PERSIST FOR WHOLE DURATION OF ATLAS. - this.MergeMode = false - this.PixelSnapH = false - this.OversampleH = 0 - this.OversampleV = 0 - this.EllipsisChar = 0 - this.SizePixels = 0 - this.GlyphRanges = nil - this.GlyphExcludeRanges = nil - this.GlyphOffset = ImVec2() - this.GlyphMinAdvanceX = 0 - this.GlyphMaxAdvanceX = FLT_MAX - this.GlyphExtraAdvanceX = 0 - this.FontNo = 0 - this.FontLoaderFlags = 0 - this.RasterizerMultiply = 1.0 - this.RasterizerDensity = 1.0 - this.ExtraSizeScale = 1.0 + -- Options + this.MergeMode = false -- 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. + this.PixelSnapH = false -- false -- Align every glyph AdvanceX to pixel boundaries. Prevents fractional font size from working correctly! Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, OversampleH/V will default to 1. + this.OversampleH = 0 -- 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. + this.OversampleV = 0 -- 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. + this.EllipsisChar = 0 -- 0 -- Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. + this.SizePixels = 0 -- Output size in pixels for rasterizer (more or less maps to the resulting font height). + this.GlyphRanges = nil -- nil -- *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). + this.GlyphExcludeRanges = nil -- nil -- 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. + this.GlyphOffset = ImVec2() -- 0, 0 -- Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. + this.GlyphMinAdvanceX = 0 -- 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. + this.GlyphMaxAdvanceX = FLT_MAX -- FLT_MAX -- Maximum AdvanceX for glyphs + this.GlyphExtraAdvanceX = 0 -- 0 -- Extra spacing (in pixels) between glyphs. Please contact us if you are using this. -- FIXME-NEWATLAS: Intentionally unscaled + this.FontNo = 0 -- 0 -- Index of font within TTF/OTF file + this.FontLoaderFlags = 0 -- 0 -- Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. + this.RasterizerMultiply = 1.0 -- 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. + this.RasterizerDensity = 1.0 -- 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. + this.ExtraSizeScale = 1.0 -- 1.0f -- Extra rasterizer scale over SizePixels. - this.Flags = 0 - this.DstFont = nil - this.FontLoader = nil - this.FontLoaderData = nil + -- [Internal] + this.Flags = 0 -- Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates) + this.DstFont = nil -- Target font (as we merging fonts, multiple ImFontConfig may target the same font) + this.FontLoader = nil -- Custom font backend for this source (default source is the one stored in ImFontAtlas) + this.FontLoaderData = nil -- Font loader opaque storage (per font config) return this end +-- Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: +-- - 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). +-- - 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. --- @class ImFontAtlas --- @field Flags ImFontAtlasFlags --- @field TexDesiredFormat ImTextureFormat @@ -32052,41 +36645,46 @@ function ImFontAtlas() --- @type ImFontAtlas local this = setmetatable({}, MT.ImFontAtlas) - this.Flags = 0 - this.TexDesiredFormat = ImTextureFormat.RGBA32 - this.TexGlyphPadding = 1 - this.TexMinWidth = 512 - this.TexMinHeight = 128 - this.TexMaxWidth = 8192 - this.TexMaxHeight = 8192 + -- Input + this.Flags = 0 -- Build flags (see ImFontAtlasFlags_) + this.TexDesiredFormat = ImTextureFormat.RGBA32 -- Desired texture format (default to ImTextureFormat.RGBA32 but may be changed to ImTextureFormat.Alpha8). + this.TexGlyphPadding = 1 -- FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method never relies on bilinear filtering you may set this to 0. + this.TexMinWidth = 512 -- Minimum desired texture width. Must be a power of two. Default to 512. + this.TexMinHeight = 128 -- Minimum desired texture height. Must be a power of two. Default to 128. + this.TexMaxWidth = 8192 -- Maximum desired texture width. Must be a power of two. Default to 8192. + this.TexMaxHeight = 8192 -- Maximum desired texture height. Must be a power of two. Default to 8192. this.TexRef = ImTextureRef() - this.TexData = nil + this.TexData = nil -- Latest texture. - this.TexList = ImVector() - this.Locked = false - this.RendererHasTextures = false - this.TexPixelsUseColors = nil - this.TexUvScale = nil - this.TexUvWhitePixel = nil - this.Fonts = ImVector() - this.Sources = ImVector() + -- [Internal] + this.TexList = ImVector() -- Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! + this.Locked = false -- Marked as locked during ImGui.NewFrame()..EndFrame() scope if TexUpdates are not supported. Any attempt to modify the atlas will assert. + this.RendererHasTextures = false -- Copy of (BackendFlags & ImGuiBackendFlags.RendererHasTextures) from supporting context. + this.TexPixelsUseColors = nil -- 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. + this.TexUvScale = nil -- = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight). May change as new texture gets created. + this.TexUvWhitePixel = nil -- Texture coordinates to a white pixel. May change as new texture gets created. + this.Fonts = ImVector() -- 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. + this.Sources = ImVector() -- Source/configuration data this.TexUvLines = {} - this.TexNextUniqueID = 1 - this.FontNextUniqueID = 1 - this.DrawListSharedDatas = ImVector() - this.Builder = nil - this.FontLoader = nil - this.FontLoaderName = nil - this.FontLoaderData = nil - this.FontLoaderFlags = nil - this.RefCount = 0 - this.OwnerContext = nil + this.TexNextUniqueID = 1 -- Next value to be stored in TexData->UniqueID + this.FontNextUniqueID = 1 -- Next value to be stored in ImFont->FontID + this.DrawListSharedDatas = ImVector() -- List of users for this atlas. Typically one per Dear ImGui context. + this.Builder = nil -- Opaque interface to our data that doesn't need to be public and may be discarded when rebuilding. + this.FontLoader = nil -- 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. + this.FontLoaderName = nil -- Font loader name (for display e.g. in About box) == FontLoader->Name + this.FontLoaderData = nil -- Font backend opaque storage + this.FontLoaderFlags = nil -- Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. Per-font override is also available in ImFontConfig). + this.RefCount = 0 -- Number of contexts using this atlas + this.OwnerContext = nil -- Context which own the atlas will be in charge of updating and destroying it. return this end +-- 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) --- @class ImFontAtlasRect --- @field x unsigned_short --- @field y unsigned_short @@ -32095,6 +36693,8 @@ end --- @field uv0 ImVec2 --- @field uv1 ImVec2 +-- 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. --- @alias ImFontAtlasRectId int ImFontAtlasRectId_Invalid = -1 @@ -32103,13 +36703,14 @@ ImFontAtlasRectId_Invalid = -1 --- @nodiscard function ImFontAtlasRect() return { - x = nil, y = nil, - w = nil, h = nil, - uv0 = ImVec2(), + x = nil, y = nil, -- Position (in current texture) + w = nil, h = nil, -- Size + uv0 = ImVec2(), -- UV coordinates (in current texture) uv1 = ImVec2() } end +-- Hold rendering data for one glyph. --- @class ImFontGlyph --- @field Colored boolean --- @field Visible boolean @@ -32134,15 +36735,30 @@ function ImFontGlyph() Visible = false, SourceIdx = 0, Codepoint = 0, - AdvanceX = 0, + AdvanceX = 0, -- Horizontal distance to advance cursor/layout position. - X0 = 0, Y0 = 0, X1 = 0, Y1 = 0, - U0 = 0, V0 = 0, U1 = 0, V1 = 0, + X0 = 0, Y0 = 0, X1 = 0, Y1 = 0, -- Glyph corners. Offsets from current cursor/layout position. + U0 = 0, V0 = 0, U1 = 0, V1 = 0, -- Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRect() with PackId. - PackId = -1 + PackId = -1 -- [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?) } end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiIO +------------------------------------------------------------------------------- + +-- Communicate most settings and inputs/outputs to Dear ImGui using this structure. +-- Access via ImGui.GetIO(). Read 'Programmer guide' section in .cpp file for general usage. +-- It is generally expected that: +-- - initialization: backends and user code writes to ImGuiIO. +-- - main loop: backends writes to ImGuiIO, user code and imgui code reads from ImGuiIO. +------------------------------------------------------------------------------- +-- Also see ImGui.GetPlatformIO() and ImGuiPlatformIO struct for OS/platform related functions: clipboard, IME etc. +------------------------------------------------------------------------------- + +-- [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions. +-- If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and *NOT* io.KeysData[key]->DownDuration. --- @class ImGuiKeyData --- @field Down bool --- @field DownDuration float @@ -32153,6 +36769,8 @@ end --- @nodiscard function ImGuiKeyData() return { Down = false, DownDuration = 0.0, DownDurationPrev = 0.0, AnalogValue = 0.0 } end +-- Configuration flags stored in io.ConfigFlags. Set by user/application. +-- Note that nowadays most of our configuration options are in other ImGuiIO fields, e.g. io.ConfigWindowsMoveFromTitleBarOnly. --- @enum ImGuiConfigFlags ImGuiConfigFlags = { None = 0, @@ -32174,126 +36792,157 @@ MT.ImGuiIO.__index = MT.ImGuiIO --- @return ImGuiIO function ImGuiIO() local this = { - Ctx = nil, + Ctx = nil, -- Parent UI context (needs to be set explicitly by parent). - KeyCtrl = false, - KeyShift = false, - KeyAlt = false, - KeySuper = false, + KeyCtrl = false, -- Keyboard modifier down: Ctrl (non-macOS), Cmd (macOS) + KeyShift = false, -- Keyboard modifier down: Shift + KeyAlt = false, -- Keyboard modifier down: Alt + KeySuper = false, -- Keyboard modifier down: Windows/Super (non-macOS), Ctrl (macOS) - KeyMods = nil, + -- Other state maintained from data above + IO function calls + KeyMods = nil, -- 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() - BackendFlags = ImGuiBackendFlags.None, - ConfigFlags = ImGuiConfigFlags.None, - DisplaySize = ImVec2(-1.0, -1.0), + BackendFlags = ImGuiBackendFlags.None, -- = 0 -- See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. + ConfigFlags = ImGuiConfigFlags.None, -- = 0 -- See ImGuiConfigFlags_ enum. Set by user/application. Keyboard/Gamepad navigation options, etc. + DisplaySize = ImVec2(-1.0, -1.0), -- -- Main display size, in pixels (== GetMainViewport()->Size). May change every frame. - DeltaTime = 1.0 / 60.0, + DeltaTime = 1.0 / 60.0, -- = 1.0f/60.0f -- Time elapsed since last frame, in seconds. May change every frame. - DisplayFramebufferScale = ImVec2(1.0, 1.0), + DisplayFramebufferScale = ImVec2(1.0, 1.0), -- = (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. - MousePos = ImVec2(), - MousePosPrev = ImVec2(), + -- Main Input State + -- (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead) + -- (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere) + MousePos = ImVec2(), -- Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) + MousePosPrev = ImVec2(), -- Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) - WantSetMousePos = false, + WantSetMousePos = false, -- MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when io.ConfigNavMoveSetMousePos is enabled. - MouseDelta = ImVec2(), + MouseDelta = ImVec2(), -- Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. - MouseDown = {[0] = false, [1] = false, [2] = false}, + MouseDown = {[0] = false, [1] = false, [2] = false}, -- Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton.COUNT == 5). Dear ImGui mostly uses left and right buttons. Other buttons allow us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. - MouseWheel = 0, - MouseWheelH = 0, + MouseWheel = 0, -- Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold Shift to turn vertical scroll into horizontal scroll. + MouseWheelH = 0, -- 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. - MouseCtrlLeftAsRightClick = false, + MouseCtrlLeftAsRightClick = false, -- (OSX) Set to true when the current click was a Ctrl+Click that spawned a simulated right click - MouseWheelRequestAxisSwap = false, + MouseWheelRequestAxisSwap = false, -- 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. - ConfigColorEditFlags = ImGuiColorEditFlags.DefaultOptions_, + ConfigColorEditFlags = ImGuiColorEditFlags.DefaultOptions_, -- = -- Current settings for ColorEdit/ColorPicker widgets. Must have one bit of ImGuiColorEditFlags.DisplayMask_, one bit of ImGuiColorEditFlags.DataTypeMask_, one bit of ImGuiColorEditFlags.PickerMask_, one bit of ImGuiColorEditFlags.InputMask_. Defaults to ImGuiColorEditFlags.DefaultOptions_. May be further edited by users, unless you also set ImGuiColorEditFlags.NoOptions. - ConfigMacOSXBehaviors = false, - ConfigNavCursorVisibleAuto = true, - ConfigNavCursorVisibleAlways = false, - ConfigInputTrickleEventQueue = true, - ConfigWindowsResizeFromEdges = true, + -- Widget options + ConfigMacOSXBehaviors = false, -- Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl. + ConfigNavCursorVisibleAuto = true, -- = true -- Using directional navigation key makes the cursor visible. Mouse click hides the cursor. + ConfigNavCursorVisibleAlways = false, -- = false -- Navigation cursor is always visible. + ConfigInputTrickleEventQueue = true, -- = true -- Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates. + ConfigWindowsResizeFromEdges = true, -- = 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) - ConfigDebugIniSettings = false, - ConfigWindowsCopyContentsWithCtrlC = false, - ConfigWindowsMoveFromTitleBarOnly = false, - ConfigErrorRecovery = true, - ConfigErrorRecoveryEnableAssert = true, - ConfigErrorRecoveryEnableDebugLog = true, - ConfigErrorRecoveryEnableTooltip = true, - ConfigDebugHighlightIdConflicts = false, - ConfigDebugHighlightIdConflictsShowItemPicker = true, + ConfigDebugIniSettings = false, -- = false -- Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower) + ConfigWindowsCopyContentsWithCtrlC = false, -- = 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. + ConfigWindowsMoveFromTitleBarOnly = false, -- = false -- Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar. + -- Options to configure Error Handling and how we handle recoverable errors [EXPERIMENTAL] + -- - Error recovery is provided as a way to facilitate: + -- - Recovery after a programming error (native code or scripting language - the latter tends to facilitate iterating on code while running). + -- - Recovery after running an exception handler or any error processing which may skip code after an error has been detected. + -- - Error recovery is not perfect nor guaranteed! It is a feature to ease development. + -- You not are not supposed to rely on it in the course of a normal application run. + -- - Functions that support error recovery are using IM_ASSERT_USER_ERROR() instead of IM_ASSERT(). + -- - By design, we do NOT allow error recovery to be 100% silent. One of the three options needs to be checked! + -- - Always ensure that on programmers seats you have at minimum Asserts or Tooltips enabled when making direct imgui API calls! + -- Otherwise it would severely hinder your ability to catch and correct mistakes! + -- Read https://github.com/ocornut/imgui/wiki/Error-Handling for details. + -- - Programmer seats: keep asserts (default), or disable asserts and keep error tooltips (new and nice!) + -- - Non-programmer seats: maybe disable asserts, but make sure errors are resurfaced (tooltips, visible log entries, use callback etc.) + -- - Recovery after error/exception: record stack sizes with ErrorRecoveryStoreState(), disable assert, set log callback (to e.g. trigger high-level breakpoint), recover with ErrorRecoveryTryToRecoverState(), restore settings. + ConfigErrorRecovery = true, -- = true -- Enable error recovery support. Some errors won't be detected and lead to direct crashes if recovery is disabled. + ConfigErrorRecoveryEnableAssert = true, -- = true -- Enable asserts on recoverable error. By default call IM_ASSERT() when returning from a failing IM_ASSERT_USER_ERROR() + ConfigErrorRecoveryEnableDebugLog = true, -- = true -- Enable debug log output on recoverable errors. + ConfigErrorRecoveryEnableTooltip = true, -- = true -- Enable tooltip on recoverable errors. The tooltip include a way to enable asserts if they were disabled. + -- 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 + ConfigDebugHighlightIdConflicts = false, -- Highlight and show an error message popup when multiple items have conflicting identifiers. + ConfigDebugHighlightIdConflictsShowItemPicker = true, -- =true -- Show "Item Picker" button in aforementioned popup. IniFilename = "imgui.ini", -- Roblox: no disk access, only used as a flag (nil disables .ini handling) - IniSavingRate = 5.0, - LogFilename = "imgui_log.txt", - WantSaveIniSettings = false, + IniSavingRate = 5.0, -- = 5.0f -- Minimum time between saving positions/sizes to .ini file, in seconds. + LogFilename = "imgui_log.txt", -- = "imgui_log.txt"-- Path to .log file (default parameter to ImGui.LogToFile when no file is specified). + WantSaveIniSettings = false, -- When manual .ini load/save is active (io.IniFilename == nil), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! - ConfigDockingNoSplit = false, - ConfigDockingNoDockingOver = false, - ConfigDockingWithShift = false, - ConfigDockingAlwaysTabBar = false, - ConfigDockingTransparentPayload = false, - ConfigViewportsNoAutoMerge = false, - ConfigViewportsNoTaskBarIcon = false, - ConfigViewportsNoDecoration = true, - ConfigViewportsNoDefaultParent = true, - ConfigViewportsPlatformFocusSetsImGuiFocus = true, + -- Docking options (when ImGuiConfigFlags.DockingEnable is set) + ConfigDockingNoSplit = false, -- = false -- Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars. + ConfigDockingNoDockingOver = false, -- = false -- Simplified docking mode: disable window merging into a same tab-bar, so docking is limited to splitting windows. + ConfigDockingWithShift = false, -- = false -- Enable docking with holding Shift key (reduce visual noise, allows dropping in wider space) + ConfigDockingAlwaysTabBar = false, -- = false -- [BETA] [FIXME: This currently creates regression with auto-sizing and general overhead] Make every single floating window display within a docking node. + ConfigDockingTransparentPayload = false, -- = false -- [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge. + -- Viewport options (when ImGuiConfigFlags.ViewportsEnable is set) + -- (sorry for the amount of "NoXXXX" flags, which may be harder to reason about! may rework someday) + ConfigViewportsNoAutoMerge = false, -- = false; -- Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set ImGuiViewportFlags.NoAutoMerge on individual viewport. + ConfigViewportsNoTaskBarIcon = false, -- = 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. + ConfigViewportsNoDecoration = true, -- = 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). + ConfigViewportsNoDefaultParent = true, -- = true -- Disable setting OS window parent to main viewport by default. The platform backend is expected to honor `viewport->ParentViewportID` to setup a parent/child relationship between the OS windows (supported if ImGuiBackendFlags.HasParentViewport is set). When parented: child windows always appear in front of their parent. Set to false if you want viewports to automatically be parent of main viewport, otherwise all viewports will be top-level OS windows. Parent/child relationship may be set on a per-window basis using ImGuiWindowClass. + ConfigViewportsPlatformFocusSetsImGuiFocus = true, -- = 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). - ConfigMemoryCompactTimer = 60.0, + ConfigMemoryCompactTimer = 60.0, -- = 60.0f -- Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. - MouseDrawCursor = false, + -- Miscellaneous options + -- (you can visualize and interact with all options in 'Demo->Configuration') + MouseDrawCursor = false, -- = false -- Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. - MouseClicked = {[0] = false, [1] = false, [2] = false}, - MouseReleased = {[0] = false, [1] = false, [2] = false}, - MouseClickedCount = {[0] = 0, [1] = 0, [2] = 0}, - MouseClickedLastCount = {[0] = 0, [1] = 0, [2] = 0}, - MouseDownDuration = {[0] = -1, [1] = -1, [2] = -1}, - MouseDownDurationPrev = {[0] = -1, [1] = -1, [2] = -1}, + MouseClicked = {[0] = false, [1] = false, [2] = false}, -- Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0) + MouseReleased = {[0] = false, [1] = false, [2] = false}, -- Mouse button went from Down to !Down + MouseClickedCount = {[0] = 0, [1] = 0, [2] = 0}, -- == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down + MouseClickedLastCount = {[0] = 0, [1] = 0, [2] = 0}, -- Count successive number of clicks. Stays valid after mouse release. Reset after another click is done. + MouseDownDuration = {[0] = -1, [1] = -1, [2] = -1}, -- Duration the mouse button has been down (0.0f == just clicked) + MouseDownDurationPrev = {[0] = -1, [1] = -1, [2] = -1}, -- Previous time the mouse button has been down - MouseDragMaxDistanceAbs = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, - MouseDragMaxDistanceSqr = {[0] = 0, [1] = 0, [2] = 0}, + MouseDragMaxDistanceAbs = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, -- Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point + MouseDragMaxDistanceSqr = {[0] = 0, [1] = 0, [2] = 0}, -- Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) - MouseDownOwned = {[0] = nil, [1] = nil, [2] = nil}, - MouseDownOwnedUnlessPopupClose = {[0] = nil, [1] = nil, [2] = nil}, - MouseClickedTime = {[0] = 0, [1] = 0, [2] = 0}, - MouseReleasedTime = {[0] = 0, [1] = 0, [2] = 0}, - MouseClickedPos = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, + MouseDownOwned = {[0] = nil, [1] = nil, [2] = nil}, -- 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. + MouseDownOwnedUnlessPopupClose = {[0] = nil, [1] = nil, [2] = nil}, -- Track if button was clicked inside a dear imgui window. + MouseClickedTime = {[0] = 0, [1] = 0, [2] = 0}, -- Time of last click (used to figure out double-click) + MouseReleasedTime = {[0] = 0, [1] = 0, [2] = 0}, -- Time of last released (rarely used! but useful to handle delayed single-click when trying to disambiguate them from double-click). + MouseClickedPos = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, -- Position at time of clicking - MouseDoubleClicked = {[0] = false, [1] = false, [2] = false}, + MouseDoubleClicked = {[0] = false, [1] = false, [2] = false}, -- Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2) - MouseDoubleClickTime = 0.30, - MouseSingleClickDelay = 0.50, - MouseDoubleClickMaxDist = 6.0, - MouseDragThreshold = 6.0, - KeyRepeatDelay = 0.275, - KeyRepeatRate = 0.050, + -- Inputs Behaviors + -- (other variables, ones which are expected to be tweaked within UI code, are exposed in ImGuiStyle) + MouseDoubleClickTime = 0.30, -- = 0.30f -- Time for consecutive clicks to account as a double-click, in seconds. + MouseSingleClickDelay = 0.50, -- Time for a delayed click when using GetItemClickedCountWithSingleClickDelay() or IsMouseReleasedWithDelay(), in seconds. Must be > io.MouseDoubleClickTime. + MouseDoubleClickMaxDist = 6.0, -- = 6.0f -- Distance threshold to stay in to validate a double-click or multiple clicks, in pixels. + MouseDragThreshold = 6.0, -- = 6.0f -- Distance threshold before considering we are dragging. + KeyRepeatDelay = 0.275, -- = 0.275f -- When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + KeyRepeatRate = 0.050, -- = 0.050f -- When holding a key/button, rate at which it repeats, in seconds. KeysData = {}, -- size = ImGuiKey.NamedKey_COUNT - WantCaptureMouse = nil, - WantCaptureKeyboard = nil, - WantTextInput = nil, + WantCaptureMouse = nil, -- Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). + WantCaptureKeyboard = nil, -- Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). + WantTextInput = nil, -- Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). - Framerate = 0, + Framerate = 0, -- Estimate of application framerate (rolling average over 60 frames, based on io.DeltaTime), in frame per second. Solely for convenience. Slow applications may not want to use a moving average or may want to reset underlying buffers occasionally. MetricsRenderVertices = 0, MetricsRenderIndices = 0, MetricsRenderWindows = 0, MetricsActiveWindows = 0, - NavActive = false, - NavVisible = false, + NavActive = false, -- Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey.NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags.NoNavInputs flag. + NavVisible = false, -- Keyboard/Gamepad navigation highlight is visible and allowed (will handle ImGuiKey.NavXXX events). - MetricsRenderWindows = 0, + MetricsRenderWindows = 0, -- Number of visible windows - Fonts = nil, - FontDefault = nil, + -- Font system + Fonts = nil, -- -- Font atlas: load, rasterize and pack one or more fonts into a single texture. + FontDefault = nil, -- = nil -- Font to use on NewFrame(). Use nil to uses Fonts->Fonts[0]. - BackendPlatformUserData = nil, - BackendRendererUserData = nil, + BackendPlatformUserData = nil, -- = nil -- User data for platform backend + BackendRendererUserData = nil, -- = nil -- User data for renderer backend - InputQueueCharacters = ImVector(), + InputQueueCharacters = ImVector(), -- Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper. - AppAcceptingEvents = true, - InputQueueSurrogate = 0 + AppAcceptingEvents = true, -- Only modify via SetAppAcceptingEvents() + InputQueueSurrogate = 0 -- For AddInputCharacterUTF16() } for i = 0, ImGuiKey.NamedKey_COUNT - 1 do @@ -32303,6 +36952,7 @@ function ImGuiIO() return setmetatable(this, MT.ImGuiIO) end +-- (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). --- @class ImGuiPlatformImeData --- @field WantVisible bool --- @field WantTextInput bool @@ -32314,11 +36964,11 @@ end --- @nodiscard function ImGuiPlatformImeData() return { - WantVisible = false, - WantTextInput = false, - InputPos = ImVec2(), - InputLineHeight = 0.0, - ViewportId = 0 + WantVisible = false, -- A widget wants the IME to be visible. + WantTextInput = false, -- A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput. + InputPos = ImVec2(), -- Position of input cursor (for IME). + InputLineHeight = 0.0, -- Line height (for IME). + ViewportId = 0 -- ID of platform window/viewport. } end @@ -32346,26 +36996,39 @@ function ImGuiPlatformImeData_Compare(data1, data2) return true end +------------------------------------------------------------------------------- +-- [SECTION] Viewports +------------------------------------------------------------------------------- + +-- Flags stored in ImGuiViewport::Flags, giving indications to the platform backends. --- @enum ImGuiViewportFlags ImGuiViewportFlags = { None = 0, - IsPlatformWindow = bitLShift(1, 0), - IsPlatformMonitor = bitLShift(1, 1), - OwnedByApp = bitLShift(1, 2), - NoDecoration = bitLShift(1, 3), - NoTaskBarIcon = bitLShift(1, 4), - NoFocusOnAppearing = bitLShift(1, 5), - NoFocusOnClick = bitLShift(1, 6), - NoInputs = bitLShift(1, 7), - NoRendererClear = bitLShift(1, 8), - NoAutoMerge = bitLShift(1, 9), - TopMost = bitLShift(1, 10), - CanHostOtherWindows = bitLShift(1, 11), + IsPlatformWindow = bitLShift(1, 0), -- Represent a Platform Window + IsPlatformMonitor = bitLShift(1, 1), -- Represent a Platform Monitor (unused yet) + OwnedByApp = bitLShift(1, 2), -- Platform Window: Is created/managed by the user application? (rather than our backend) + NoDecoration = bitLShift(1, 3), -- Platform Window: Disable platform decorations: title bar, borders, etc. (generally set all windows, but if ImGuiConfigFlags.ViewportsDecoration is set we only set this on popups/tooltips) + NoTaskBarIcon = bitLShift(1, 4), -- Platform Window: Disable platform task bar icon (generally set on popups/tooltips, or all windows if ImGuiConfigFlags.ViewportsNoTaskBarIcon is set) + NoFocusOnAppearing = bitLShift(1, 5), -- Platform Window: Don't take focus when created. + NoFocusOnClick = bitLShift(1, 6), -- Platform Window: Don't take focus when clicked on. + NoInputs = bitLShift(1, 7), -- Platform Window: Make mouse pass through so we can drag this window while peaking behind it. + NoRendererClear = bitLShift(1, 8), -- Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely). + NoAutoMerge = bitLShift(1, 9), -- Platform Window: Avoid merging this window into another host window. This can only be set via ImGuiWindowClass viewport flags override (because we need to now ahead if we are going to create a viewport in the first place!). + TopMost = bitLShift(1, 10), -- Platform Window: Display on top (for tooltips only). + CanHostOtherWindows = bitLShift(1, 11), -- Viewport can host multiple imgui windows (secondary viewports are associated to a single window). -- FIXME: In practice there's still probably code making the assumption that this is always and only on the MainViewport. Will fix once we add support for "no main viewport". - IsMinimized = bitLShift(1, 12), - IsFocused = bitLShift(1, 13) + -- Output status flags (from Platform) + IsMinimized = bitLShift(1, 12), -- Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. + IsFocused = bitLShift(1, 13) -- Platform Window: Window is focused (last call to Platform_GetWindowFocus() returned true) } +-- - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. +-- - With multi-viewport enabled, we extend this concept to have multiple active viewports. +-- - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. +-- - About Main Area vs Work Area: +-- - Main Area = entire viewport. +-- - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor). +-- - Windows are generally trying to stay within the Work Area of their host viewport. --- @class ImGuiViewport --- @field ID ImGuiID --- @field Flags ImGuiViewportFlags @@ -32401,21 +37064,26 @@ end --- @nodiscard function ImGuiViewport() return setmetatable({ - ID = 0, - Flags = 0, - Pos = ImVec2(), - Size = ImVec2(), - FramebufferScale = ImVec2(), - WorkPos = ImVec2(), - WorkSize = ImVec2(), - DpiScale = 0, + ID = 0, -- Unique identifier for the viewport + Flags = 0, -- See ImGuiViewportFlags_ + Pos = ImVec2(), -- Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) + Size = ImVec2(), -- Main Area: Size of the viewport. + FramebufferScale = ImVec2(), -- 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. + WorkPos = ImVec2(), -- Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) + WorkSize = ImVec2(), -- Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) + DpiScale = 0, -- 1.0f = 96 DPI = No extra scale. - PlatformHandle = nil, - PlatformHandleRaw = nil, - PlatformWindowCreated = false + PlatformHandle = nil, -- void* to hold higher-level, platform window handle (e.g. HWND for Win32 backend, Uint32 WindowID for SDL, GLFWWindow* for GLFW), for FindViewportByPlatformHandle(). + PlatformHandleRaw = nil, -- void* to hold lower-level, platform-native window handle (always HWND on Win32 platform, unused for other platforms). + PlatformWindowCreated = false -- Platform window has been created (Platform_CreateWindow() has been called). This is false during the first frame where a viewport is being created. }, MT.ImGuiViewport) end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) +------------------------------------------------------------------------------- + +-- Access via ImGui.GetPlatformIO() --- @class ImGuiPlatformIO --- @field Platform_GetClipboardTextFn fun(ctx?: ImGuiContext): string --- @field Platform_CreateWindow fun(vp: ImGuiViewport) @@ -32430,29 +37098,54 @@ MT.ImGuiPlatformIO.__index = MT.ImGuiPlatformIO --- @nodiscard function ImGuiPlatformIO() local this = { - Platform_GetClipboardTextFn = nil, + ------------------------------------------------------------------------------- + -- Input - Interface with OS and Platform backend (most common stuff) + ------------------------------------------------------------------------------- + + -- Optional: Access OS clipboard + -- (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + Platform_GetClipboardTextFn = nil, -- Should return nil on failure (e.g. clipboard data is not text). Platform_SetClipboardTextFn = nil, + -- Optional: Open link/folder/file in OS Shell + -- (default to use ShellExecuteW() on Windows, system() on Linux/Mac. expected to return false on failure, but some platforms may always return true) Platform_OpenInShellFn = nil, Platform_OpenInShellUserData = nil, + ------------------------------------------------------------------------------- + -- Input - Interface with Renderer Backend + ------------------------------------------------------------------------------- + + -- Optional: Maximum texture size supported by renderer (used to adjust how we size textures). 0 if not known. Renderer_TextureMaxWidth = 0, Renderer_TextureMaxHeight = 0, + -- Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure. Renderer_RenderState = nil, + -- (Optional) Monitor list + -- - Updated by: app/backend. Update every frame to dynamically support changing monitor or DPI configuration. + -- - Used by: dear imgui to query DPI info, clamp popups/tooltips within same monitor and not have them straddle monitors. Monitors = ImVector(), - Textures = ImVector(), - Viewports = ImVector(), + -- 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. + Textures = ImVector(), -- 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") + Viewports = ImVector(), -- Main viewports, followed by all secondary viewports. + -- Optional: Platform locale + -- [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point Platform_LocaleDecimalPoint = 46, -- '.' - Platform_OnChangedViewport = nil, + Platform_OnChangedViewport = nil, -- (Optional) [BETA] FIXME-DPI: DPI handling: Called during Begin() every time the viewport we are outputting into changes, so backend has a chance to swap fonts to adjust style. } return setmetatable(this, MT.ImGuiPlatformIO) end +-- (Optional) This is required when enabling multi-viewport. Represent the bounds of each connected monitor/display and their DPI. +-- We use this information for multiple DPI support + clamping the position of popups and tooltips so they don't straddle multiple monitors. --- @class ImGuiPlatformMonitor --- @field MainPos ImVec2 --- @field MainSize ImVec2 @@ -32465,45 +37158,52 @@ end --- @nodiscard function ImGuiPlatformMonitor() return { - MainPos = ImVec2(0, 0), + MainPos = ImVec2(0, 0), -- Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right) MainSize = ImVec2(0, 0), - WorkPos = ImVec2(0, 0), + WorkPos = ImVec2(0, 0), -- Coordinates without task bars / side bars / menu bars. Used to avoid positioning popups/tooltips inside this region. If you don't have this info, please copy the value for MainPos/MainSize. WorkSize = ImVec2(0, 0), - DpiScale = 1.0, + DpiScale = 1.0, -- 1.0f = 96 DPI - PlatformHandle = nil + PlatformHandle = nil -- Backend dependant data (e.g. HMONITOR, GLFWmonitor*, SDL Display Index, NSScreen*) } end +------------------------------------------------------------------------------- +-- [SECTION] Flags & Enumerations +------------------------------------------------------------------------------- + +-- Flags for ImGui.Begin() +-- (Those are per-window flags. There are shared flags in ImGuiIO: io.ConfigWindowsResizeFromEdges and io.ConfigWindowsMoveFromTitleBarOnly) --- @enum ImGuiWindowFlags ImGuiWindowFlags = { None = 0, - NoTitleBar = bitLShift(1, 0), - NoResize = bitLShift(1, 1), - NoMove = bitLShift(1, 2), - NoScrollbar = bitLShift(1, 3), - NoScrollWithMouse = bitLShift(1, 4), - NoCollapse = bitLShift(1, 5), - AlwaysAutoResize = bitLShift(1, 6), - NoBackground = bitLShift(1, 7), - NoSavedSettings = bitLShift(1, 8), - NoMouseInputs = bitLShift(1, 9), - MenuBar = bitLShift(1, 10), - HorizontalScrollbar = bitLShift(1, 11), - NoFocusOnAppearing = bitLShift(1, 12), - NoBringToFrontOnFocus = bitLShift(1, 13), - AlwaysVerticalScrollbar = bitLShift(1, 14), - AlwaysHorizontalScrollbar = bitLShift(1, 15), - NoNavInputs = bitLShift(1, 16), - NoNavFocus = bitLShift(1, 17), - UnsavedDocument = bitLShift(1, 18), - NoDocking = bitLShift(1, 19), - DockNodeHost = bitLShift(1, 23), - ChildWindow = bitLShift(1, 24), - Tooltip = bitLShift(1, 25), - Popup = bitLShift(1, 26), - Modal = bitLShift(1, 27), - ChildMenu = bitLShift(1, 28) + NoTitleBar = bitLShift(1, 0), -- Disable title-bar + NoResize = bitLShift(1, 1), -- Disable user resizing with the lower-right grip + NoMove = bitLShift(1, 2), -- Disable user moving the window + NoScrollbar = bitLShift(1, 3), -- Disable scrollbars (window can still scroll with mouse or programmatically) + NoScrollWithMouse = bitLShift(1, 4), -- Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. + NoCollapse = bitLShift(1, 5), -- Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node). + AlwaysAutoResize = bitLShift(1, 6), -- Resize every window to its content every frame + NoBackground = bitLShift(1, 7), -- Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). + NoSavedSettings = bitLShift(1, 8), -- Never load/save settings in .ini file + NoMouseInputs = bitLShift(1, 9), -- Disable catching mouse, hovering test with pass through. + MenuBar = bitLShift(1, 10), -- Has a menu-bar + HorizontalScrollbar = bitLShift(1, 11), -- Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + NoFocusOnAppearing = bitLShift(1, 12), -- Disable taking focus when transitioning from hidden to visible state + NoBringToFrontOnFocus = bitLShift(1, 13), -- Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) + AlwaysVerticalScrollbar = bitLShift(1, 14), -- Always show vertical scrollbar (even if ContentSize.y < Size.y) + AlwaysHorizontalScrollbar = bitLShift(1, 15), -- Always show horizontal scrollbar (even if ContentSize.x < Size.x) + NoNavInputs = bitLShift(1, 16), -- No keyboard/gamepad navigation within the window + NoNavFocus = bitLShift(1, 17), -- No focusing toward this window with keyboard/gamepad navigation (e.g. skipped by Ctrl+Tab) + UnsavedDocument = bitLShift(1, 18), -- Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + NoDocking = bitLShift(1, 19), -- Disable docking of this window + -- [Internal] + DockNodeHost = bitLShift(1, 23), -- Don't use! For internal use by Begin()/NewFrame() + ChildWindow = bitLShift(1, 24), -- Don't use! For internal use by BeginChild() + Tooltip = bitLShift(1, 25), -- Don't use! For internal use by BeginTooltip() + Popup = bitLShift(1, 26), -- Don't use! For internal use by BeginPopup() + Modal = bitLShift(1, 27), -- Don't use! For internal use by BeginPopupModal() + ChildMenu = bitLShift(1, 28) -- Don't use! For internal use by BeginMenu() } -- [Internal] @@ -32511,51 +37211,74 @@ ImGuiWindowFlags.NoNav = bitOr(ImGuiWindowFlags.NoNavInputs, ImGuiWindowF ImGuiWindowFlags.NoDecoration = bitOr(ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoCollapse) ImGuiWindowFlags.NoInputs = bitOr(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs, ImGuiWindowFlags.NoNavFocus) +-- Flags for ImGui.PushItemFlag() +-- (Those are shared by all submitted items) --- @enum ImGuiItemFlags ImGuiItemFlags = { - None = 0, - NoTabStop = bitLShift(1, 0), - NoNav = bitLShift(1, 1), - NoNavDefaultFocus = bitLShift(1, 2), - ButtonRepeat = bitLShift(1, 3), - AutoClosePopups = bitLShift(1, 4), - AllowDuplicateId = bitLShift(1, 5), - Disabled = bitLShift(1, 6), - LiveEditOnInputText = bitLShift(1, 7), - LiveEditOnInputScalar = bitLShift(1, 8) + None = 0, -- Default: + NoTabStop = bitLShift(1, 0), -- false -- Disable keyboard tabbing. This is a "lighter" version of ImGuiItemFlags.NoNav. + NoNav = bitLShift(1, 1), -- false -- Disable any form of focusing: keyboard/gamepad directional navigation and SetKeyboardFocusHere() calls. + NoNavDefaultFocus = bitLShift(1, 2), -- false -- Disable item being a candidate for default focus (e.g. used by title bar items). + ButtonRepeat = bitLShift(1, 3), -- false -- Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held. + AutoClosePopups = bitLShift(1, 4), -- true -- MenuItem()/Selectable() automatically close their parent popup window. + AllowDuplicateId = bitLShift(1, 5), -- false -- Allow submitting an item with the same identifier as an item already submitted this frame without triggering a warning tooltip if io.ConfigDebugHighlightIdConflicts is set. + Disabled = bitLShift(1, 6), -- false -- [Internal] Disable interactions. DOES NOT affect visuals. This is used by BeginDisabled()/EndDisabled() and only provided here so you can read back via GetItemFlags(). + ------------------------------------------------------------------------------- + -- LiveEdit refers to applying edits to backing variables _while_ typing a value using the keyboard. + -- Widget: | Input: | w/ LiveEdit: | Output: + -- InputText() | "123" | on(default) | "1" then "12" then "123" + -- InputText() | "123" | off | "123" after validating or tabbing out or losing focus. + -- DragFloat(), SliderInt(), etc. | "123" | on* | 1 then 12 then 123 + -- DragFloat(), SliderInt(), etc. | "123" | off(default)* | 123 after validation or tabbing out or losing focus. + -- (*) Since 1.92.9 (July 2026), ImGuiItemFlags.LiveEditOnInputScalar is OFF by default. In prior version it was ON for everything. + ------------------------------------------------------------------------------- + LiveEditOnInputText = bitLShift(1, 7), -- true -- InputText: apply keyboard edits to backing value while typing. Otherwise, edits are applied when validating, tabbing out or losing focus. + LiveEditOnInputScalar = bitLShift(1, 8) -- false -- DragXXX, SliderXXX, InputScalar: apply keyboard edits to backing value while typing. Otherwise, edits are applied when validating, tabbing out or losing focus. } ImGuiItemFlags.LiveEditOnInput = bitOr(ImGuiItemFlags.LiveEditOnInputText, ImGuiItemFlags.LiveEditOnInputScalar) +-- Status flags for an already submitted item +-- - output: stored in g.LastItemData.StatusFlags --- @enum ImGuiItemStatusFlags ImGuiItemStatusFlags = { None = 0, - HoveredRect = bitLShift(1, 0), - HasDisplayRect = bitLShift(1, 1), - Edited = bitLShift(1, 2), - ToggledSelection = bitLShift(1, 3), - ToggledOpen = bitLShift(1, 4), - HasDeactivated = bitLShift(1, 5), - Deactivated = bitLShift(1, 6), - HoveredWindow = bitLShift(1, 7), - Visible = bitLShift(1, 8), - HasClipRect = bitLShift(1, 9), - HasShortcut = bitLShift(1, 10), - EditedInternal = bitLShift(1, 11) + HoveredRect = bitLShift(1, 0), -- Mouse position is within item rectangle (does NOT mean that the window is in correct z-order and can be hovered!, this is only one part of the most-common IsItemHovered test) + HasDisplayRect = bitLShift(1, 1), -- g.LastItemData.DisplayRect is valid + Edited = bitLShift(1, 2), -- Value exposed by item was edited in the current frame (should match the bool return value of most widgets) + ToggledSelection = bitLShift(1, 3), -- Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected", only state changes, in order to easily handle clipping with less issues. + ToggledOpen = bitLShift(1, 4), -- Set when TreeNode() reports toggling their open state. + HasDeactivated = bitLShift(1, 5), -- Set if the widget/group is able to provide data for the ImGuiItemStatusFlags.Deactivated flag. + Deactivated = bitLShift(1, 6), -- Only valid if ImGuiItemStatusFlags.HasDeactivated is set. + HoveredWindow = bitLShift(1, 7), -- Override the HoveredWindow test to allow cross-window hover testing. + Visible = bitLShift(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()). + HasClipRect = bitLShift(1, 9), -- g.LastItemData.ClipRect is valid. + HasShortcut = bitLShift(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. + EditedInternal = bitLShift(1, 11) -- Similar to ImGuiItemStatusFlags.Edited but bypassing ImGuiItemFlags.NoMarkEdited. } +-- Flags for ImGui.BeginChild() +-- (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. +-- - This allows BeginChild() to return false when not within boundaries (e.g. when scrolling), which is more optimal. BUT it won't update its auto-size while clipped. +-- While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional "resizing after becoming visible again" glitch. +-- - You may also use ImGuiChildFlags.AlwaysAutoResize to force an update even when child window is not in view. +-- HOWEVER PLEASE UNDERSTAND THAT DOING SO WILL PREVENT BeginChild() FROM EVER RETURNING FALSE, disabling benefits of coarse clipping. --- @enum ImGuiChildFlags ImGuiChildFlags = { None = 0, - Borders = bitLShift(1, 0), - AlwaysUseWindowPadding = bitLShift(1, 1), - ResizeX = bitLShift(1, 2), - ResizeY = bitLShift(1, 3), - AutoResizeX = bitLShift(1, 4), - AutoResizeY = bitLShift(1, 5), - AlwaysAutoResize = bitLShift(1, 6), - FrameStyle = bitLShift(1, 7), - NavFlattened = bitLShift(1, 8) + Borders = bitLShift(1, 0), -- Show an outer border and enable WindowPadding. (IMPORTANT: this is always == 1 == true for legacy reason) + AlwaysUseWindowPadding = bitLShift(1, 1), -- Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) + ResizeX = bitLShift(1, 2), -- Allow resize from right border (layout direction). Enable .ini saving (unless ImGuiWindowFlags.NoSavedSettings passed to window flags) + ResizeY = bitLShift(1, 3), -- Allow resize from bottom border (layout direction). " + AutoResizeX = bitLShift(1, 4), -- Enable auto-resizing width. Read "IMPORTANT: Size measurement" details above. + AutoResizeY = bitLShift(1, 5), -- Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above. + AlwaysAutoResize = bitLShift(1, 6), -- Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. + FrameStyle = bitLShift(1, 7), -- Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. + NavFlattened = bitLShift(1, 8) -- [BETA] Share focus scope, allow keyboard/gamepad navigation to cross over parent border to this child or between sibling child windows. } ImGuiChildFlags.ResizeBoth = bitOr(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY) @@ -32572,25 +37295,30 @@ ImGuiNextItemDataFlags = { HasColorMarker = bitLShift(1, 5) } +-- Flags for ImDrawList functions --- @enum ImDrawFlags ImDrawFlags = { None = 0, - RoundCornersTopLeft = bitLShift(1, 4), - RoundCornersTopRight = bitLShift(1, 5), - RoundCornersBottomLeft = bitLShift(1, 6), - RoundCornersBottomRight = bitLShift(1, 7), - RoundCornersNone = bitLShift(1, 8), - Closed = bitLShift(1, 9) + -- - Rounding default to ImDrawFlags.RoundCornersAll when 'rounding > 0'. + -- - So you only need to use the ImDrawFlags.RoundCornersXXX flags if you want a special configuration (e.g. a rectangle with one rounded corner). + -- Rounding for AddRectXXX(), PathRect() ------ -- Prim/Scope? + RoundCornersTopLeft = bitLShift(1, 4), -- OK -- -- Round top-left corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersTopRight = bitLShift(1, 5), -- OK -- -- Round top-right corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersBottomLeft = bitLShift(1, 6), -- OK -- -- Round bottom-left corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersBottomRight = bitLShift(1, 7), -- OK -- -- Round bottom-right corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersNone = bitLShift(1, 8), -- OK -- -- Disable rounding even when 'rounding > 0.0f'. This value is NOT zero, it is NOT an implicit flag! + -- Stroke Options ----------------------------- -- Prim/Scope? + Closed = bitLShift(1, 9) -- OK -- -- PathStroke(), AddPolyline(): specify that shape should be closed. } ImDrawFlags.RoundCornersTop = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight) ImDrawFlags.RoundCornersBottom = bitOr(ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight) ImDrawFlags.RoundCornersLeft = bitOr(ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersTopLeft) ImDrawFlags.RoundCornersRight = bitOr(ImDrawFlags.RoundCornersBottomRight, ImDrawFlags.RoundCornersTopRight) -ImDrawFlags.RoundCornersAll = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight, ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight) +ImDrawFlags.RoundCornersAll = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight, ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight) -- (Default!!) ImDrawFlags.RoundCornersDefault_ = ImDrawFlags.RoundCornersAll -ImDrawFlags.RoundCornersMask_ = bitOr(ImDrawFlags.RoundCornersAll, ImDrawFlags.RoundCornersNone) -ImDrawFlags.InvalidMask_ = 0x8000000F +ImDrawFlags.RoundCornersMask_ = bitOr(ImDrawFlags.RoundCornersAll, ImDrawFlags.RoundCornersNone) -- [Internal] +ImDrawFlags.InvalidMask_ = 0x8000000F -- [Internal] == 0x8000000F. Reserved to detect misuses. --- @enum ImDrawListFlags ImDrawListFlags = { @@ -32602,155 +37330,195 @@ ImDrawListFlags = { TextNoPixelSnap = bitLShift(1, 4) } +-- 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, - NoLoadError = bitLShift(1, 1), - NoLoadGlyphs = bitLShift(1, 2), - LockBakedSizes = bitLShift(1, 3), - ImplicitRefSize = bitLShift(1, 4) + NoLoadError = bitLShift(1, 1), -- Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. + NoLoadGlyphs = bitLShift(1, 2), -- [Internal] Disable loading new glyphs. + LockBakedSizes = bitLShift(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. + ImplicitRefSize = bitLShift(1, 4) -- [Internal] Reference size was not set explicitly. } +-- Enumeration for AddMouseSourceEvent() actual source of Mouse Input data. +-- Historically we use "Mouse" terminology everywhere to indicate pointer data, e.g. MousePos, IsMousePressed(), io.AddMousePosEvent() +-- But that "Mouse" data can come from different source which occasionally may be useful for application to know about. +-- You can submit a change of pointer type using io.AddMouseSourceEvent(). --- @enum ImGuiMouseSource ImGuiMouseSource = { - Mouse = 0, - TouchScreen = 1, - Pen = 2, + Mouse = 0, -- Input is coming from an actual mouse. + TouchScreen = 1, -- Input is coming from a touch screen (no hovering prior to initial press, less precise initial press aiming, dual-axis wheeling possible). + Pen = 2, -- Input is coming from a pressure/magnetic pen (often used in conjunction with high-sampling rates). COUNT = 3 } +-- Enumeration for ImGui.SetNextWindow***(), SetWindow***(), SetNextItem***() functions +-- Represent a condition. +-- Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond.Always. --- @enum ImGuiCond ImGuiCond = { - None = 0, - Always = bitLShift(1, 0), - Once = bitLShift(1, 1), - FirstUseEver = bitLShift(1, 2), - Appearing = bitLShift(1, 3) + None = 0, -- No condition (always set the variable), same as _Always + Always = bitLShift(1, 0), -- No condition (always set the variable), same as _None + Once = bitLShift(1, 1), -- Set the variable once per runtime session (only the first call will succeed) + FirstUseEver = bitLShift(1, 2), -- Set the variable if the object/window has no persistently saved data (no entry in .ini file) + Appearing = bitLShift(1, 3) -- Set the variable if the object/window is appearing after being hidden/inactive (or the first time) } +-- Flags for Shortcut(), SetNextItemShortcut(), +-- (and for upcoming extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() that are still in imgui_internal.h) +-- Don't mistake with ImGuiInputTextFlags! (which is for ImGui.InputText() function) --- @enum ImGuiInputFlags ImGuiInputFlags = { None = 0, - Repeat = bitLShift(1, 0), - RouteActive = bitLShift(1, 10), - RouteFocused = bitLShift(1, 11), - RouteGlobal = bitLShift(1, 12), - RouteAlways = bitLShift(1, 13), - RouteOverFocused = bitLShift(1, 14), - RouteOverActive = bitLShift(1, 15), - RouteUnlessBgFocused = bitLShift(1, 16), - RouteFromRootWindow = bitLShift(1, 17), - Tooltip = bitLShift(1, 18) + Repeat = bitLShift(1, 0), -- Enable repeat. Return true on successive repeats. Default for legacy IsKeyPressed(). NOT Default for legacy IsMouseClicked(). MUST BE == 1. + -- Flags for Shortcut(), SetNextItemShortcut() + -- - Routing policies: RouteGlobal+OverActive >> RouteActive or RouteFocused (if owner is active item) >> RouteGlobal+OverFocused >> RouteFocused (if in focused window stack) >> RouteGlobal. + -- - Default policy is RouteFocused. Can select only 1 policy among all available. + RouteActive = bitLShift(1, 10), -- Route to active item only. + RouteFocused = bitLShift(1, 11), -- Route to windows in the focus stack (DEFAULT). Deep-most focused window takes inputs. Active item takes inputs over deep-most focused window. + RouteGlobal = bitLShift(1, 12), -- Global route (unless a focused window or active item registered the route). + RouteAlways = bitLShift(1, 13), -- Do not register route, poll keys directly. + -- - Routing options + RouteOverFocused = bitLShift(1, 14), -- Option: global route: higher priority than focused route (unless active item in focused route). + RouteOverActive = bitLShift(1, 15), -- Option: global route: higher priority than active item. Unlikely you need to use that: will interfere with every active items, e.g. Ctrl+A registered by InputText will be overridden by this. May not be fully honored as user/internal code is likely to always assume they can access keys when active. + RouteUnlessBgFocused = bitLShift(1, 16), -- Option: global route: will not be applied if underlying background/void is focused (== no Dear ImGui windows are focused). Useful for overlay applications. + RouteFromRootWindow = bitLShift(1, 17), -- Option: route evaluated from the point of view of root window rather than current window. + -- Flags for SetNextItemShortcut() + Tooltip = bitLShift(1, 18) -- Automatically display a tooltip when hovering item [BETA] Unsure of right api (opt-in/opt-out) } +-- Flags for InvisibleButton() [extended in imgui_internal.h] --- @enum ImGuiButtonFlags ImGuiButtonFlags = { None = 0, - MouseButtonLeft = bitLShift(1, 0), - MouseButtonRight = bitLShift(1, 1), - MouseButtonMiddle = bitLShift(1, 2), - EnableNav = bitLShift(1, 3), - PressedOnClick = bitLShift(1, 4), - PressedOnClickRelease = bitLShift(1, 5), - PressedOnClickReleaseAnywhere = bitLShift(1, 6), - PressedOnRelease = bitLShift(1, 7), - PressedOnDoubleClick = bitLShift(1, 8), - PressedOnDragDropHold = bitLShift(1, 9), - FlattenChildren = bitLShift(1, 11), - AllowOverlap = bitLShift(1, 12), - AlignTextBaseLine = bitLShift(1, 15), - NoKeyModsAllowed = bitLShift(1, 16), - NoHoldingActiveId = bitLShift(1, 17), - NoNavFocus = bitLShift(1, 18), - NoHoveredOnFocus = bitLShift(1, 19), - NoSetKeyOwner = bitLShift(1, 20), - NoTestKeyOwner = bitLShift(1, 21), - NoFocus = bitLShift(1, 22) + MouseButtonLeft = bitLShift(1, 0), -- React on left mouse button (default) + MouseButtonRight = bitLShift(1, 1), -- React on right mouse button + MouseButtonMiddle = bitLShift(1, 2), -- React on center mouse button + EnableNav = bitLShift(1, 3), -- InvisibleButton(): do not disable navigation/tabbing. Otherwise disabled by default. + PressedOnClick = bitLShift(1, 4), -- return true on click (mouse down event) + PressedOnClickRelease = bitLShift(1, 5), -- [Default] return true on click + release on same item <-- this is what the majority of Button are using + PressedOnClickReleaseAnywhere = bitLShift(1, 6), -- return true on click + release even if the release event is not done while hovering the item + PressedOnRelease = bitLShift(1, 7), -- return true on release (default requires click+release). Prior to 2026/03/20 this implied ImGuiButtonFlags.NoHoldingActiveId but they are separate now. + PressedOnDoubleClick = bitLShift(1, 8), -- return true on double-click (default requires click+release) + PressedOnDragDropHold = bitLShift(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 -> use ImGuiItemFlags.ButtonRepeat instead. + FlattenChildren = bitLShift(1, 11), -- allow interactions even if a child window is overlapping + AllowOverlap = bitLShift(1, 12), -- Hit testing will allow subsequent widgets to overlap this one. Require previous frame HoveredId to match before being usable. Shortcut to calling SetNextItemAllowOverlap(). + --ImGuiButtonFlags.DontClosePopups = 1 << 13, -- disable automatically closing parent popup on press + --ImGuiButtonFlags.Disabled = 1 << 14, -- disable interactions -> use BeginDisabled() or ImGuiItemFlags.Disabled + AlignTextBaseLine = bitLShift(1, 15), -- vertically align button to match text baseline - ButtonEx() only -- FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine + NoKeyModsAllowed = bitLShift(1, 16), -- disable mouse interaction if a key modifier is held + NoHoldingActiveId = bitLShift(1, 17), -- don't set ActiveId while holding the mouse (ImGuiButtonFlags.PressedOnClick only) + NoNavFocus = bitLShift(1, 18), -- don't override navigation focus when activated (FIXME: this is essentially used every time an item uses ImGuiItemFlags.NoNav, but because legacy specs don't requires LastItemData to be set ButtonBehavior(), we can't poll g.LastItemData.ItemFlags) + NoHoveredOnFocus = bitLShift(1, 19), -- don't report as hovered when nav focus is on this item + NoSetKeyOwner = bitLShift(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!) + NoTestKeyOwner = bitLShift(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!) + NoFocus = bitLShift(1, 22) -- [EXPERIMENTAL: Not very well specced]. Don't focus parent window when clicking. } -ImGuiButtonFlags.MouseButtonMask_ = bitOr(ImGuiButtonFlags.MouseButtonLeft, ImGuiButtonFlags.MouseButtonRight, ImGuiButtonFlags.MouseButtonMiddle) +ImGuiButtonFlags.MouseButtonMask_ = bitOr(ImGuiButtonFlags.MouseButtonLeft, ImGuiButtonFlags.MouseButtonRight, ImGuiButtonFlags.MouseButtonMiddle) -- [Internal] ImGuiButtonFlags.PressedOnMask_ = bitOr(ImGuiButtonFlags.PressedOnClick, ImGuiButtonFlags.PressedOnClickRelease, ImGuiButtonFlags.PressedOnClickReleaseAnywhere, ImGuiButtonFlags.PressedOnRelease, ImGuiButtonFlags.PressedOnDoubleClick, ImGuiButtonFlags.PressedOnDragDropHold) ImGuiButtonFlags.PressedOnDefault_ = ImGuiButtonFlags.PressedOnClickRelease ImGuiButtonFlags.NoKeyModifiers = ImGuiButtonFlags.NoKeyModsAllowed +-- Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. +-- - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. +-- During initialization or between frames, feel free to just poke into ImGuiStyle directly. +-- - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. --- @enum ImGuiStyleVar ImGuiStyleVar = { - Alpha = 0, - DisabledAlpha = 1, - WindowPadding = 2, - WindowRounding = 3, - WindowBorderSize = 4, - WindowMinSize = 5, - WindowTitleAlign = 6, - ChildRounding = 7, - ChildBorderSize = 8, - PopupRounding = 9, - PopupBorderSize = 10, - FramePadding = 11, - FrameRounding = 12, - FrameBorderSize = 13, - ItemSpacing = 14, - ItemInnerSpacing = 15, - IndentSpacing = 16, - CellPadding = 17, - ScrollbarSize = 18, - ScrollbarRounding = 19, - ScrollbarPadding = 20, - GrabMinSize = 21, - GrabRounding = 22, - ImageRounding = 23, - ImageBorderSize = 24, - TabRounding = 25, - TabBorderSize = 26, - TabMinWidthBase = 27, - TabMinWidthShrink = 28, - TabBarBorderSize = 29, - TabBarOverlineSize = 30, - TableAngledHeadersAngle = 31, - TableAngledHeadersTextAlign = 32, - TreeLinesSize = 33, - TreeLinesRounding = 34, - MenuItemRounding = 35, - SelectableRounding = 36, - DragDropTargetRounding = 37, - ButtonTextAlign = 38, - SelectableTextAlign = 39, - SeparatorTextBorderSize = 40, - SeparatorTextAlign = 41, - SeparatorTextPadding = 42, + -- Enum name -------------------------- -- Member in ImGuiStyle structure (see ImGuiStyle for descriptions) + Alpha = 0, -- float Alpha + DisabledAlpha = 1, -- float DisabledAlpha + WindowPadding = 2, -- ImVec2 WindowPadding + WindowRounding = 3, -- float WindowRounding + WindowBorderSize = 4, -- float WindowBorderSize + WindowMinSize = 5, -- ImVec2 WindowMinSize + WindowTitleAlign = 6, -- ImVec2 WindowTitleAlign + ChildRounding = 7, -- float ChildRounding + ChildBorderSize = 8, -- float ChildBorderSize + PopupRounding = 9, -- float PopupRounding + PopupBorderSize = 10, -- float PopupBorderSize + FramePadding = 11, -- ImVec2 FramePadding + FrameRounding = 12, -- float FrameRounding + FrameBorderSize = 13, -- float FrameBorderSize + ItemSpacing = 14, -- ImVec2 ItemSpacing + ItemInnerSpacing = 15, -- ImVec2 ItemInnerSpacing + IndentSpacing = 16, -- float IndentSpacing + CellPadding = 17, -- ImVec2 CellPadding + ScrollbarSize = 18, -- float ScrollbarSize + ScrollbarRounding = 19, -- float ScrollbarRounding + ScrollbarPadding = 20, -- float ScrollbarPadding + GrabMinSize = 21, -- float GrabMinSize + GrabRounding = 22, -- float GrabRounding + ImageRounding = 23, -- float ImageRounding + ImageBorderSize = 24, -- float ImageBorderSize + TabRounding = 25, -- float TabRounding + TabBorderSize = 26, -- float TabBorderSize + TabMinWidthBase = 27, -- float TabMinWidthBase + TabMinWidthShrink = 28, -- float TabMinWidthShrink + TabBarBorderSize = 29, -- float TabBarBorderSize + TabBarOverlineSize = 30, -- float TabBarOverlineSize + TableAngledHeadersAngle = 31, -- float TableAngledHeadersAngle + TableAngledHeadersTextAlign = 32, -- ImVec2 TableAngledHeadersTextAlign + TreeLinesSize = 33, -- float TreeLinesSize + TreeLinesRounding = 34, -- float TreeLinesRounding + MenuItemRounding = 35, -- float MenuItemRounding + SelectableRounding = 36, -- float SelectableRounding + DragDropTargetRounding = 37, -- float DragDropTargetRounding + ButtonTextAlign = 38, -- ImVec2 ButtonTextAlign + SelectableTextAlign = 39, -- ImVec2 SelectableTextAlign + SeparatorTextBorderSize = 40, -- float SeparatorTextBorderSize + SeparatorTextAlign = 41, -- ImVec2 SeparatorTextAlign + SeparatorTextPadding = 42, -- ImVec2 SeparatorTextPadding COUNT = 43 } +-- Flags for ImGui.IsItemHovered(), ImGui.IsWindowHovered() +-- Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ! +-- Note: windows with the ImGuiWindowFlags.NoInputs flag are ignored by IsWindowHovered() calls. --- @enum ImGuiHoveredFlags ImGuiHoveredFlags = { - None = 0, - ChildWindows = bitLShift(1, 0), - RootWindow = bitLShift(1, 1), - AnyWindow = bitLShift(1, 2), - NoPopupHierarchy = bitLShift(1, 3), - DockHierarchy = bitLShift(1, 4), - AllowWhenBlockedByPopup = bitLShift(1, 5), - AllowWhenBlockedByActiveItem = bitLShift(1, 7), - AllowWhenOverlappedByItem = bitLShift(1, 8), - AllowWhenOverlappedByWindow = bitLShift(1, 9), - AllowWhenDisabled = bitLShift(1, 10), - NoNavOverride = bitLShift(1, 11), - ForTooltip = bitLShift(1, 12), - Stationary = bitLShift(1, 13), - DelayNone = bitLShift(1, 14), - DelayShort = bitLShift(1, 15), - DelayNormal = bitLShift(1, 16), - NoSharedDelay = bitLShift(1, 17) + None = 0, -- Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. + ChildWindows = bitLShift(1, 0), -- IsWindowHovered() only: Return true if any children of the window is hovered + RootWindow = bitLShift(1, 1), -- IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) + AnyWindow = bitLShift(1, 2), -- IsWindowHovered() only: Return true if any window is hovered + NoPopupHierarchy = bitLShift(1, 3), -- IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + DockHierarchy = bitLShift(1, 4), -- IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + AllowWhenBlockedByPopup = bitLShift(1, 5), -- Return true even if a popup window is normally blocking access to this item/window + --ImGuiHoveredFlags.AllowWhenBlockedByModal = 1 << 6, -- Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. + AllowWhenBlockedByActiveItem = bitLShift(1, 7), -- Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. + AllowWhenOverlappedByItem = bitLShift(1, 8), -- IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item. + AllowWhenOverlappedByWindow = bitLShift(1, 9), -- IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window. + AllowWhenDisabled = bitLShift(1, 10), -- IsItemHovered() only: Return true even if the item is disabled + NoNavOverride = bitLShift(1, 11), -- IsItemHovered() only: Disable using keyboard/gamepad navigation state when active, always query mouse + -- Tooltips mode + -- - typically used in IsItemHovered() + SetTooltip() sequence. + -- - this is a shortcut to pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' where you can reconfigure desired behavior. + -- e.g. 'HoverFlagsForTooltipMouse' defaults to 'ImGuiHoveredFlags.Stationary | ImGuiHoveredFlags.DelayShort | ImGuiHoveredFlags.AllowWhenDisabled'. + -- - for frequently actioned or hovered items providing a tooltip, you want may to use ImGuiHoveredFlags.ForTooltip (stationary + delay) so the tooltip doesn't show too often. + -- - for items which main purpose is to be hovered, or items with low affordance, or in less consistent apps, prefer no delay or shorter delay. + ForTooltip = bitLShift(1, 12), -- Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence. + -- (Advanced) Mouse Hovering delays. + -- - generally you can use ImGuiHoveredFlags.ForTooltip to use application-standardized flags. + -- - use those if you need specific overrides. + Stationary = bitLShift(1, 13), -- Require mouse to be stationary for style.HoverStationaryDelay (~0.15 sec) _at least one time_. After this, can move on same item/window. Using the stationary test tends to reduces the need for a long delay. + DelayNone = bitLShift(1, 14), -- IsItemHovered() only: Return true immediately (default). As this is the default you generally ignore this. + DelayShort = bitLShift(1, 15), -- IsItemHovered() only: Return true after style.HoverDelayShort elapsed (~0.15 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). + DelayNormal = bitLShift(1, 16), -- IsItemHovered() only: Return true after style.HoverDelayNormal elapsed (~0.40 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). + NoSharedDelay = bitLShift(1, 17) -- IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) } +-- Flags for ImGui.IsWindowFocused() --- @enum ImGuiFocusedFlags ImGuiFocusedFlags = { None = 0, ChildWindows = bitLShift(1, 0), -- Return true if any children of the window is focused RootWindow = bitLShift(1, 1), -- Test from root window (top most parent of the current hierarchy) - AnyWindow = bitLShift(1, 2), -- Return true if any window is focused - NoPopupHierarchy = bitLShift(1, 3), -- Do not consider popup hierarchy - DockHierarchy = bitLShift(1, 4), -- Consider docking hierarchy + AnyWindow = bitLShift(1, 2), -- Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! + NoPopupHierarchy = bitLShift(1, 3), -- Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + DockHierarchy = bitLShift(1, 4), -- Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) } ImGuiFocusedFlags.RootAndChildWindows = bitOr(ImGuiFocusedFlags.RootWindow, ImGuiFocusedFlags.ChildWindows) @@ -32761,13 +37529,20 @@ ImGuiHoveredFlags.DelayMask_ = bitOr(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFl ImGuiHoveredFlags.AllowedMaskForIsWindowHovered = bitOr(ImGuiHoveredFlags.ChildWindows, ImGuiHoveredFlags.RootWindow, ImGuiHoveredFlags.AnyWindow, ImGuiHoveredFlags.NoPopupHierarchy, ImGuiHoveredFlags.DockHierarchy, ImGuiHoveredFlags.AllowWhenBlockedByPopup, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.Stationary) ImGuiHoveredFlags.AllowedMaskForIsItemHovered = bitOr(ImGuiHoveredFlags.AllowWhenBlockedByPopup, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, ImGuiHoveredFlags.AllowWhenOverlapped, ImGuiHoveredFlags.AllowWhenDisabled, ImGuiHoveredFlags.NoNavOverride, ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayMask_) +-- 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 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 latter 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 ImGuiKey = { + -- Keyboard None = 0, - NamedKey_BEGIN = 512, + NamedKey_BEGIN = 512, -- First valid key value (other than 0) - Tab = 512, + Tab = 512, -- == ImGuiKey.NamedKey_BEGIN LeftArrow = 513, RightArrow = 514, UpArrow = 515, @@ -32804,10 +37579,14 @@ ImGuiKey = { Keypad0 = 612, Keypad1 = 613, Keypad2 = 614, Keypad3 = 615, Keypad4 = 616, Keypad5 = 617, Keypad6 = 618, Keypad7 = 619, Keypad8 = 620, Keypad9 = 621, KeypadDecimal = 622, KeypadDivide = 623, KeypadMultiply = 624, KeypadSubtract = 625, KeypadAdd = 626, KeypadEnter = 627, KeypadEqual = 628, - AppBack = 629, + AppBack = 629, -- Available on some keyboard/mouses. Often referred as "Browser Back" AppForward = 630, - Oem102 = 631, + Oem102 = 631, -- Non-US backslash. + -- Gamepad + -- (analog values are 0.0f to 1.0f) + -- (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) + -- XBOX | SWITCH | PLAYSTA. | -> ACTION GamepadStart = 632, GamepadBack = 633, GamepadFaceLeft = 634, GamepadFaceRight = 635, GamepadFaceUp = 636, GamepadFaceDown = 637, GamepadDpadLeft = 638, GamepadDpadRight = 639, GamepadDpadUp = 640, GamepadDpadDown = 641, @@ -32821,121 +37600,138 @@ ImGuiKey = { ReservedForModCtrl = 663, ReservedForModShift = 664, ReservedForModAlt = 665, ReservedForModSuper = 666, + -- [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey.NamedKey_BEGIN..ImGuiKey.NamedKey_END. NamedKey_END = 667 } ImGuiKey.NamedKey_COUNT = ImGuiKey.NamedKey_END - ImGuiKey.NamedKey_BEGIN +-- Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) +-- - 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. +-- In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and +-- backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user... +-- - On macOS, we swap Cmd(Super) and Ctrl keys at the time of the io.AddKeyEvent() call. ImGuiMod_None = 0 -ImGuiMod_Ctrl = bitLShift(1, 12) -ImGuiMod_Shift = bitLShift(1, 13) -ImGuiMod_Alt = bitLShift(1, 14) -ImGuiMod_Super = bitLShift(1, 15) -ImGuiMod_Mask_ = 0xF000 +ImGuiMod_Ctrl = bitLShift(1, 12) -- Ctrl (non-macOS), Cmd (macOS) +ImGuiMod_Shift = bitLShift(1, 13) -- Shift +ImGuiMod_Alt = bitLShift(1, 14) -- Option/Menu +ImGuiMod_Super = bitLShift(1, 15) -- Windows/Super (non-macOS), Ctrl (macOS) +ImGuiMod_Mask_ = 0xF000 -- 4-bits +-- Enumeration for PushStyleColor() / PopStyleColor() --- @enum ImGuiCol ImGuiCol = { Text = 0, TextDisabled = 1, - WindowBg = 2, - ChildBg = 3, - PopupBg = 4, + WindowBg = 2, -- Background of normal windows + ChildBg = 3, -- Background of child windows + PopupBg = 4, -- Background of popups, menus, tooltips windows Border = 5, BorderShadow = 6, - FrameBg = 7, + FrameBg = 7, -- Background of checkbox, radio button, plot, slider, text input FrameBgHovered = 8, FrameBgActive = 9, - TitleBg = 10, - TitleBgActive = 11, - TitleBgCollapsed = 12, + TitleBg = 10, -- Title bar + TitleBgActive = 11, -- Title bar when focused + TitleBgCollapsed = 12, -- Title bar when collapsed MenuBarBg = 13, ScrollbarBg = 14, ScrollbarGrab = 15, ScrollbarGrabHovered = 16, ScrollbarGrabActive = 17, - CheckMark = 18, - CheckboxSelectedBg = 19, + CheckMark = 18, -- Checkbox tick and RadioButton circle + CheckboxSelectedBg = 19, -- Checkbox background when Selected, otherwise use FrameBg SliderGrab = 20, SliderGrabActive = 21, Button = 22, ButtonHovered = 23, ButtonActive = 24, - Header = 25, + Header = 25, -- Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem HeaderHovered = 26, HeaderActive = 27, Separator = 28, SeparatorHovered = 29, SeparatorActive = 30, - ResizeGrip = 31, + ResizeGrip = 31, -- Resize grip in lower-right and lower-left corners of windows. ResizeGripHovered = 32, ResizeGripActive = 33, - InputTextCursor = 34, - TabHovered = 35, - Tab = 36, - TabSelected = 37, - TabSelectedOverline = 38, - TabDimmed = 39, - TabDimmedSelected = 40, - TabDimmedSelectedOverline = 41, - DockingPreview = 42, - DockingEmptyBg = 43, + InputTextCursor = 34, -- InputText cursor/caret + TabHovered = 35, -- Tab background, when hovered + Tab = 36, -- Tab background, when tab-bar is focused & tab is unselected + TabSelected = 37, -- Tab background, when tab-bar is focused & tab is selected + TabSelectedOverline = 38, -- Tab horizontal overline, when tab-bar is focused & tab is selected + TabDimmed = 39, -- Tab background, when tab-bar is unfocused & tab is unselected + TabDimmedSelected = 40, -- Tab background, when tab-bar is unfocused & tab is selected + TabDimmedSelectedOverline = 41, -- ..horizontal overline, when tab-bar is unfocused & tab is selected + DockingPreview = 42, -- Preview overlay color when about to docking something + DockingEmptyBg = 43, -- Background color for empty node (e.g. CentralNode with no window docked into it) PlotLines = 44, PlotLinesHovered = 45, PlotHistogram = 46, PlotHistogramHovered = 47, - TableHeaderBg = 48, - TableBorderStrong = 49, - TableBorderLight = 50, - TableRowBg = 51, - TableRowBgAlt = 52, - TextLink = 53, - TextSelectedBg = 54, - TreeLines = 55, - DragDropTarget = 56, - DragDropTargetBg = 57, - UnsavedMarker = 58, - NavCursor = 59, - NavWindowingHighlight = 60, - NavWindowingDimBg = 61, - ModalWindowDimBg = 62, + TableHeaderBg = 48, -- Table header background + TableBorderStrong = 49, -- Table outer and header borders (prefer using Alpha=1.0 here) + TableBorderLight = 50, -- Table inner borders (prefer using Alpha=1.0 here) + TableRowBg = 51, -- Table row background (even rows) + TableRowBgAlt = 52, -- Table row background (odd rows) + TextLink = 53, -- Hyperlink color + TextSelectedBg = 54, -- Selected text inside an InputText + TreeLines = 55, -- Tree node hierarchy outlines when using ImGuiTreeNodeFlags.DrawLines + DragDropTarget = 56, -- Rectangle border highlighting a drop target + DragDropTargetBg = 57, -- Rectangle background highlighting a drop target + UnsavedMarker = 58, -- Unsaved Document marker (in window title and tabs) + NavCursor = 59, -- Color of keyboard/gamepad navigation cursor/rectangle, when visible + NavWindowingHighlight = 60, -- Highlight window when using Ctrl+Tab + NavWindowingDimBg = 61, -- Darken/colorize entire screen behind the Ctrl+Tab window list, when active + ModalWindowDimBg = 62, -- Darken/colorize entire screen behind a modal window, when one is active COUNT = 63 } +-- Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend. --- @enum ImGuiBackendFlags ImGuiBackendFlags = { None = 0, - HasGamepad = bitLShift(1, 0), - HasMouseCursors = bitLShift(1, 1), - HasSetMousePos = bitLShift(1, 2), - RendererHasVtxOffset = bitLShift(1, 3), - RendererHasTextures = bitLShift(1, 4), + HasGamepad = bitLShift(1, 0), -- Backend Platform supports gamepad and currently has one connected. + HasMouseCursors = bitLShift(1, 1), -- Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. + HasSetMousePos = bitLShift(1, 2), -- Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if io.ConfigNavMoveSetMousePos is set). + RendererHasVtxOffset = bitLShift(1, 3), -- Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. + RendererHasTextures = bitLShift(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] Multi-Viewports - RendererHasViewports = bitLShift(1, 10), - PlatformHasViewports = bitLShift(1, 11), - HasMouseHoveredViewport = bitLShift(1, 12), - HasParentViewport = bitLShift(1, 13) + RendererHasViewports = bitLShift(1, 10), -- Backend Renderer supports multiple viewports. + PlatformHasViewports = bitLShift(1, 11), -- Backend Platform supports multiple viewports. + HasMouseHoveredViewport = bitLShift(1, 12), -- Backend Platform supports calling io.AddMouseViewportEvent() with the viewport under the mouse. IF POSSIBLE, ignore viewports with the ImGuiViewportFlags.NoInputs flag (Win32 backend, GLFW 3.30+ backend can do this, SDL backend cannot). If this cannot be done, Dear ImGui needs to use a flawed heuristic to find the viewport under. + HasParentViewport = bitLShift(1, 13) -- Backend Platform supports honoring viewport->ParentViewport/ParentViewportId value, by applying the corresponding parent/child relationship at the Platform level. Child windows always appear in front of their parent window. } +-- Flags for ImGui.BeginDragDropSource(), ImGui.AcceptDragDropPayload() --- @enum ImGuiDragDropFlags ImGuiDragDropFlags = { None = 0, - SourceNoPreviewTooltip = bitLShift(1, 0), - SourceNoDisableHover = bitLShift(1, 1), - SourceNoHoldToOpenOthers = bitLShift(1, 2), - SourceAllowNullID = bitLShift(1, 3), - SourceExtern = bitLShift(1, 4), - PayloadAutoExpire = bitLShift(1, 5), - PayloadNoCrossContext = bitLShift(1, 6), - PayloadNoCrossProcess = bitLShift(1, 7), - AcceptBeforeDelivery = bitLShift(1, 10), - AcceptNoDrawDefaultRect = bitLShift(1, 11), - AcceptNoPreviewTooltip = bitLShift(1, 12), - AcceptDrawAsHovered = bitLShift(1, 13) + -- BeginDragDropSource() flags + SourceNoPreviewTooltip = bitLShift(1, 0), -- Disable preview tooltip. By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disables this behavior. + SourceNoDisableHover = bitLShift(1, 1), -- By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disables this behavior so you can still call IsItemHovered() on the source item. + SourceNoHoldToOpenOthers = bitLShift(1, 2), -- Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. + SourceAllowNullID = bitLShift(1, 3), -- Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. + SourceExtern = bitLShift(1, 4), -- External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. + PayloadAutoExpire = bitLShift(1, 5), -- Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) + PayloadNoCrossContext = bitLShift(1, 6), -- Hint to specify that the payload may not be copied outside current dear imgui context. + PayloadNoCrossProcess = bitLShift(1, 7), -- Hint to specify that the payload may not be copied outside current process. + -- AcceptDragDropPayload() flags + AcceptBeforeDelivery = bitLShift(1, 10), -- AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. + AcceptNoDrawDefaultRect = bitLShift(1, 11), -- Do not draw the default highlight rectangle when hovering over target. + AcceptNoPreviewTooltip = bitLShift(1, 12), -- Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. + AcceptDrawAsHovered = bitLShift(1, 13) -- Accepting item will render as if hovered. Useful for e.g. a Button() used as a drop target. } -ImGuiDragDropFlags.AcceptPeekOnly = bitOr(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoDrawDefaultRect) +ImGuiDragDropFlags.AcceptPeekOnly = bitOr(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoDrawDefaultRect) -- For peeking ahead and inspecting the payload before delivery. +-- Helpers macros to generate 32-bit encoded colors IM_COL32_R_SHIFT = 0 IM_COL32_G_SHIFT = 8 IM_COL32_B_SHIFT = 16 @@ -32951,121 +37747,145 @@ IM_COL32_WHITE = IM_COL32(255, 255, 255, 255) IM_COL32_BLACK = IM_COL32(0, 0, 0, 255) IM_COL32_BLACK_TRANS = IM_COL32(0, 0, 0, 0) +-- Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. +-- - IMPORTANT: If you ever used the left mouse button with BeginPopupContextXXX() helpers before 1.92.6: Read "API BREAKING CHANGES" 2026/01/07 (1.92.6) entry in imgui.cpp or GitHub topic #9157. +-- - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). --- @enum ImGuiPopupFlags ImGuiPopupFlags = { None = 0, - MouseButtonLeft = bitLShift(1, 2), - MouseButtonRight = bitLShift(2, 2), - MouseButtonMiddle = bitLShift(3, 2), - NoReopen = bitLShift(1, 5), - NoOpenOverExistingPopup = bitLShift(1, 7), - NoOpenOverItems = bitLShift(1, 8), - AnyPopupId = bitLShift(1, 10), - AnyPopupLevel = bitLShift(1, 11) + MouseButtonLeft = bitLShift(1, 2), -- For BeginPopupContext*(): open on Left Mouse release. Only one button allowed! + MouseButtonRight = bitLShift(2, 2), -- For BeginPopupContext*(): open on Right Mouse release. Only one button allowed! (default) + MouseButtonMiddle = bitLShift(3, 2), -- For BeginPopupContext*(): open on Middle Mouse release. Only one button allowed! + NoReopen = bitLShift(1, 5), -- For OpenPopup*(), BeginPopupContext*(): don't reopen same popup if already open (won't reposition, won't reinitialize navigation) + --ImGuiPopupFlags.NoReopenAlwaysNavInit = 1 << 6, -- For OpenPopup*(), BeginPopupContext*(): focus and initialize navigation even when not reopening. + NoOpenOverExistingPopup = bitLShift(1, 7), -- For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack + NoOpenOverItems = bitLShift(1, 8), -- For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space + AnyPopupId = bitLShift(1, 10), -- For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. + AnyPopupLevel = bitLShift(1, 11) -- For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) } ImGuiPopupFlags.AnyPopup = bitOr(ImGuiPopupFlags.AnyPopupId, ImGuiPopupFlags.AnyPopupLevel) -ImGuiPopupFlags.MouseButtonShift_ = 2 -ImGuiPopupFlags.MouseButtonMask_ = 0x0C -ImGuiPopupFlags.InvalidMask_ = 0x03 +ImGuiPopupFlags.MouseButtonShift_ = 2 -- [Internal] +ImGuiPopupFlags.MouseButtonMask_ = 0x0C -- [Internal] +ImGuiPopupFlags.InvalidMask_ = 0x03 -- [Internal] Reserve legacy bits 0-1 to detect incorrectly passing 1 or 2 to the function. +-- Flags for ImGui.BeginCombo() --- @enum ImGuiComboFlags ImGuiComboFlags = { None = 0, - PopupAlignLeft = bitLShift(1, 0), - HeightSmall = bitLShift(1, 1), - HeightRegular = bitLShift(1, 2), - HeightLarge = bitLShift(1, 3), - HeightLargest = bitLShift(1, 4), - NoArrowButton = bitLShift(1, 5), - NoPreview = bitLShift(1, 6), - WidthFitPreview = bitLShift(1, 7) + PopupAlignLeft = bitLShift(1, 0), -- Align the popup toward the left by default + HeightSmall = bitLShift(1, 1), -- Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() + HeightRegular = bitLShift(1, 2), -- Max ~8 items visible (default) + HeightLarge = bitLShift(1, 3), -- Max ~20 items visible + HeightLargest = bitLShift(1, 4), -- As many fitting items as possible + NoArrowButton = bitLShift(1, 5), -- Display on the preview box without the square arrow button + NoPreview = bitLShift(1, 6), -- Display only a square arrow button + WidthFitPreview = bitLShift(1, 7) -- Width dynamically calculated from preview contents } ImGuiComboFlags.HeightMask_ = bitOr(ImGuiComboFlags.HeightSmall, ImGuiComboFlags.HeightRegular, ImGuiComboFlags.HeightLarge, ImGuiComboFlags.HeightLargest) ImGuiComboFlags.CustomPreview = bitLShift(1, 20) +-- Flags for ImGui.Selectable() --- @enum ImGuiSelectableFlags ImGuiSelectableFlags = { None = 0, - NoAutoClosePopups = bitLShift(1, 0), - SpanAllColumns = bitLShift(1, 1), - AllowDoubleClick = bitLShift(1, 2), - Disabled = bitLShift(1, 3), - AllowOverlap = bitLShift(1, 4), - Highlight = bitLShift(1, 5), - SelectOnNav = bitLShift(1, 6), + NoAutoClosePopups = bitLShift(1, 0), -- Clicking this doesn't close parent popup window (overrides ImGuiItemFlags.AutoClosePopups) + SpanAllColumns = bitLShift(1, 1), -- Frame will span all columns of its container table (text will still fit in current column) + AllowDoubleClick = bitLShift(1, 2), -- Generate press events on double clicks too + Disabled = bitLShift(1, 3), -- Cannot be selected, display grayed out text + AllowOverlap = bitLShift(1, 4), -- Hit testing will allow subsequent widgets to overlap this one. Require previous frame HoveredId to match before being usable. Shortcut to calling SetNextItemAllowOverlap(). + Highlight = bitLShift(1, 5), -- Make the item be displayed as if it is hovered + SelectOnNav = bitLShift(1, 6), -- Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block. + -- NB: need to be in sync with last value of ImGuiSelectableFlags_ NoHoldingActiveID = bitLShift(1, 20), - SelectOnClick = bitLShift(1, 22), - SelectOnRelease = bitLShift(1, 23), - SpanAvailWidth = bitLShift(1, 24), - SetNavIdOnHover = bitLShift(1, 25), - NoPadWithHalfSpacing = bitLShift(1, 26), - NoSetKeyOwner = bitLShift(1, 27), + SelectOnClick = bitLShift(1, 22), -- Override button behavior to react on Click (default is Click+Release) + SelectOnRelease = bitLShift(1, 23), -- Override button behavior to react on Release (default is Click+Release) + SpanAvailWidth = bitLShift(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) + SetNavIdOnHover = bitLShift(1, 25), -- Set Nav/Focus ID on mouse hover (used by MenuItem) + NoPadWithHalfSpacing = bitLShift(1, 26), -- Disable padding each side with ItemSpacing * 0.5f + NoSetKeyOwner = bitLShift(1, 27), -- Don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey.MouseLeft!) } +-- Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() --- @enum ImGuiColorEditFlags ImGuiColorEditFlags = { None = 0, - NoAlpha = bitLShift(1, 1), - NoPicker = bitLShift(1, 2), - NoOptions = bitLShift(1, 3), - NoSmallPreview = bitLShift(1, 4), - NoInputs = bitLShift(1, 5), - NoTooltip = bitLShift(1, 6), - NoLabel = bitLShift(1, 7), - NoSidePreview = bitLShift(1, 8), - NoDragDrop = bitLShift(1, 9), - NoBorder = bitLShift(1, 10), - NoColorMarkers = bitLShift(1, 11), + NoAlpha = bitLShift(1, 1), -- ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). + NoPicker = bitLShift(1, 2), -- ColorEdit: disable picker when clicking on color square. + NoOptions = bitLShift(1, 3), -- ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. + NoSmallPreview = bitLShift(1, 4), -- ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) + NoInputs = bitLShift(1, 5), -- ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). + NoTooltip = bitLShift(1, 6), -- ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. + NoLabel = bitLShift(1, 7), -- ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). + NoSidePreview = bitLShift(1, 8), -- ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. + NoDragDrop = bitLShift(1, 9), -- ColorEdit: disable drag and drop target/source. ColorButton: disable drag and drop source. + NoBorder = bitLShift(1, 10), -- ColorButton: disable border (which is enforced by default) + NoColorMarkers = bitLShift(1, 11), -- ColorEdit: disable rendering R/G/B/A color marker. May also be disabled globally by setting style.ColorMarkerSize = 0. -- Alpha preview - AlphaOpaque = bitLShift(1, 12), - AlphaNoBg = bitLShift(1, 13), - AlphaPreviewHalf = bitLShift(1, 14), + AlphaOpaque = bitLShift(1, 12), -- 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. + AlphaNoBg = bitLShift(1, 13), -- ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color. + AlphaPreviewHalf = bitLShift(1, 14), -- ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview. -- User Options (right-click on widget to change some of them) - AlphaBar = bitLShift(1, 18), - HDR = bitLShift(1, 19), - DisplayRGB = bitLShift(1, 20), - DisplayHSV = bitLShift(1, 21), - DisplayHex = bitLShift(1, 22), - Uint8 = bitLShift(1, 23), - Float = bitLShift(1, 24), - PickerHueBar = bitLShift(1, 25), - PickerHueWheel = bitLShift(1, 26), - PickerNoRotate = bitLShift(1, 27), - InputRGB = bitLShift(1, 28), - InputHSV = bitLShift(1, 29) + AlphaBar = bitLShift(1, 18), -- ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. + HDR = bitLShift(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). + DisplayRGB = bitLShift(1, 20), -- [Display] -- ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. + DisplayHSV = bitLShift(1, 21), -- [Display] -- " + DisplayHex = bitLShift(1, 22), -- [Display] -- " + Uint8 = bitLShift(1, 23), -- [DataType] -- ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. + Float = bitLShift(1, 24), -- [DataType] -- ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. + PickerHueBar = bitLShift(1, 25), -- [Picker] -- ColorPicker: bar for Hue, rectangle for Sat/Value. + PickerHueWheel = bitLShift(1, 26), -- [Picker] -- ColorPicker: wheel for Hue, triangle for Sat/Value. + PickerNoRotate = bitLShift(1, 27), -- [Picker] -- ColorPicker: disable rotating Sat/Value triangle. Best set in io.ConfigColorEditFlags once. + InputRGB = bitLShift(1, 28), -- [Input] -- ColorEdit, ColorPicker: input and output data in RGB format. + InputHSV = bitLShift(1, 29) -- [Input] -- ColorEdit, ColorPicker: input and output data in HSV format. } +-- Defaults Options copied to io.ConfigColorEditFlags during initialization. +-- The intent is that you probably don't want to override them in most of your calls. +-- Let the user choose via the option menu and/or modify io.ConfigColorEditFlags directly during startup if you want. ImGuiColorEditFlags.DefaultOptions_ = bitOr(ImGuiColorEditFlags.Uint8, ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.InputRGB, ImGuiColorEditFlags.PickerHueBar) +-- [Internal] Masks ImGuiColorEditFlags.AlphaMask_ = bitOr( ImGuiColorEditFlags.NoAlpha, ImGuiColorEditFlags.AlphaOpaque, ImGuiColorEditFlags.AlphaNoBg, ImGuiColorEditFlags.AlphaPreviewHalf ) ImGuiColorEditFlags.DisplayMask_ = bitOr( ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.DisplayHSV, ImGuiColorEditFlags.DisplayHex ) ImGuiColorEditFlags.DataTypeMask_ = bitOr( ImGuiColorEditFlags.Uint8, ImGuiColorEditFlags.Float ) ImGuiColorEditFlags.PickerMask_ = bitOr( ImGuiColorEditFlags.PickerHueWheel, ImGuiColorEditFlags.PickerHueBar ) ImGuiColorEditFlags.InputMask_ = bitOr( ImGuiColorEditFlags.InputRGB, ImGuiColorEditFlags.InputHSV ) +-- Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +-- We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. +-- (Those are per-item flags. There is shared behavior flag too: ImGuiIO: io.ConfigDragClickToInputText) --- @enum ImGuiSliderFlags ImGuiSliderFlags = { None = 0, - Logarithmic = bitLShift(1, 5), - NoRoundToFormat = bitLShift(1, 6), - NoInput = bitLShift(1, 7), - WrapAround = bitLShift(1, 8), - ClampOnInput = bitLShift(1, 9), - ClampZeroRange = bitLShift(1, 10), - NoSpeedTweaks = bitLShift(1, 11), - ColorMarkers = bitLShift(1, 12), - InvalidMask_ = 0x7000000F, + Logarithmic = bitLShift(1, 5), -- Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags.NoRoundToFormat with this if using a format-string with small amount of digits. + NoRoundToFormat = bitLShift(1, 6), -- Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). + NoInput = bitLShift(1, 7), -- Disable Ctrl+Click or Enter key allowing to input text directly into the widget. + WrapAround = bitLShift(1, 8), -- Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now. + ClampOnInput = bitLShift(1, 9), -- Clamp value to min/max bounds when input manually with Ctrl+Click. By default Ctrl+Click allows going out of bounds. + ClampZeroRange = bitLShift(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. + NoSpeedTweaks = bitLShift(1, 11), -- Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. + ColorMarkers = bitLShift(1, 12), -- DragScalarN(), SliderScalarN(): Draw R/G/B/A color markers on each component. + --ImGuiSliderFlags.LiveEditOnInput = 1 << 13, -- Shortcut to enable LiveEdit for this field. + --ImGuiSliderFlags.NoLiveEditOnInput= 1 << 14, -- Shortcut to disable LiveEdit for this field. + InvalidMask_ = 0x7000000F, -- [Internal] We treat using those bits as being potentially a 'float power' argument from legacy API (obsoleted 2020-08) that has got miscast to this enum, and will trigger an assert if needed. } ImGuiSliderFlags.AlwaysClamp = bitOr(ImGuiSliderFlags.ClampOnInput, ImGuiSliderFlags.ClampZeroRange) -ImGuiSliderFlags.Vertical = bitLShift(1, 20) -ImGuiSliderFlags.ReadOnly = bitLShift(1, 21) +ImGuiSliderFlags.Vertical = bitLShift(1, 20) -- Should this slider be orientated vertically? +ImGuiSliderFlags.ReadOnly = bitLShift(1, 21) -- Consider using g.NextItemData.ItemFlags |= ImGuiItemFlags.ReadOnly instead. +-- [ALPHA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions. +-- Important: the content of this class is still highly WIP and likely to change and be refactored +-- before we stabilize Docking features. Please be mindful if using this. +-- Provide hints: +-- - To the platform backend via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) +-- - To the platform backend for OS level parent/child relationships of viewport (otherwise: default is configured via io.ConfigViewportsNoDefaultParent) +-- - To the docking system for various options and filtering. --- @class ImGuiWindowClass --- @field ClassId ImGuiID --- @field ParentViewportId ImGuiID @@ -33077,66 +37897,82 @@ ImGuiSliderFlags.ReadOnly = bitLShift(1, 21) --- @nodiscard function ImGuiWindowClass() return { - ClassId = 0, - ParentViewportId = 0xFFFFFFFF, - FocusRouteParentWindowId = 0, - ViewportFlagsOverrideSet = 0, - ViewportFlagsOverrideClear = 0, + ClassId = 0, -- User data. 0 = Default class (unclassed). Windows of different classes cannot be docked with each others. + ParentViewportId = 0xFFFFFFFF, -- Hint for the platform backend. -1: use default. 0: request platform backend to not parent the platform. != 0: request platform backend to create a parent<>child relationship between the platform windows. Not conforming backends are free to e.g. parent every viewport to the main viewport or not. + FocusRouteParentWindowId = 0, -- ID of parent window for shortcut focus route evaluation, e.g. Shortcut() call from Parent Window will succeed when this window is focused. + ViewportFlagsOverrideSet = 0, -- Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ViewportFlagsOverrideClear = 0, -- Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. - TabItemFlagsOverrideSet = 0, - DockNodeFlagsOverrideSet = 0, - DockingAlwaysTabBar = false, - DockingAllowUnclassed = true + TabItemFlagsOverrideSet = 0, -- [EXPERIMENTAL] TabItem flags to set when a window of this class gets submitted into a dock node tab bar. May use with ImGuiTabItemFlags.Leading or ImGuiTabItemFlags.Trailing. + DockNodeFlagsOverrideSet = 0, -- [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) + DockingAlwaysTabBar = false, -- Set to true to enforce single floating windows of this class always having their own docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar) + DockingAllowUnclassed = true -- Set to true to allow windows of this class to be docked/merged with an unclassed window. -- FIXME-DOCK: Move to DockNodeFlags override? } end +-- Flags for ImGui.InputText() +-- (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigInputTextCursorBlink and io.ConfigInputTextEnterKeepActive) --- @enum ImGuiInputTextFlags ImGuiInputTextFlags = { + -- Basic filters (also see ImGuiInputTextFlags.CallbackCharFilter) None = 0, -- Basic filters (also see ImGuiInputTextFlags.CallbackCharFilter) - CharsDecimal = bitLShift(1, 0), - CharsHexadecimal = bitLShift(1, 1), - CharsScientific = bitLShift(1, 2), - CharsUppercase = bitLShift(1, 3), - CharsNoBlank = bitLShift(1, 4), + CharsDecimal = bitLShift(1, 0), -- Allow 0123456789.+-*/ + CharsHexadecimal = bitLShift(1, 1), -- Allow 0123456789ABCDEFabcdef + CharsScientific = bitLShift(1, 2), -- Allow 0123456789.+-*/eE (Scientific notation input) + CharsUppercase = bitLShift(1, 3), -- Turn a..z into A..Z + CharsNoBlank = bitLShift(1, 4), -- Filter out spaces, tabs -- Inputs - AllowTabInput = bitLShift(1, 5), - EnterReturnsTrue = bitLShift(1, 6), - EscapeClearsAll = bitLShift(1, 7), - CtrlEnterForNewLine = bitLShift(1, 8), + AllowTabInput = bitLShift(1, 5), -- Pressing TAB input a '\t' character into the text field + EnterReturnsTrue = bitLShift(1, 6), -- Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider disabling LiveEdit! or using IsItemDeactivatedAfterEdit() instead! + EscapeClearsAll = bitLShift(1, 7), -- Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) + CtrlEnterForNewLine = bitLShift(1, 8), -- In multi-line mode: validate with Enter, add new line with Ctrl+Enter (default is opposite: validate with Ctrl+Enter, add line with Enter). Note that Shift+Enter always enter a new line either way. -- Other options - ReadOnly = bitLShift(1, 9), - Password = bitLShift(1, 10), - AlwaysOverwrite = bitLShift(1, 11), - AutoSelectAll = bitLShift(1, 12), - ParseEmptyRefVal = bitLShift(1, 13), - DisplayEmptyRefVal = bitLShift(1, 14), - NoHorizontalScroll = bitLShift(1, 15), - NoUndoRedo = bitLShift(1, 16), + ReadOnly = bitLShift(1, 9), -- Read-only mode + Password = bitLShift(1, 10), -- Password mode, display all characters as '*', disable copy + AlwaysOverwrite = bitLShift(1, 11), -- Overwrite mode + AutoSelectAll = bitLShift(1, 12), -- Select entire text when first taking mouse focus + ParseEmptyRefVal = bitLShift(1, 13), -- InputFloat(), InputInt(), InputScalar() etc. only: parse empty string as zero value. + DisplayEmptyRefVal = bitLShift(1, 14), -- InputFloat(), InputInt(), InputScalar() etc. only: when value is zero, do not display it. Generally used with ImGuiInputTextFlags.ParseEmptyRefVal. + NoHorizontalScroll = bitLShift(1, 15), -- Disable following the cursor horizontally + NoUndoRedo = bitLShift(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 - ElideLeft = bitLShift(1, 17), + ElideLeft = bitLShift(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 - CallbackCompletion = bitLShift(1, 18), - CallbackHistory = bitLShift(1, 19), - CallbackAlways = bitLShift(1, 20), - CallbackCharFilter = bitLShift(1, 21), - CallbackResize = bitLShift(1, 22), - CallbackEdit = bitLShift(1, 23), + CallbackCompletion = bitLShift(1, 18), -- Callback on pressing TAB (for completion handling) + CallbackHistory = bitLShift(1, 19), -- Callback on pressing Up/Down arrows (for history handling) + CallbackAlways = bitLShift(1, 20), -- Callback on each iteration. User code may query cursor position, modify text buffer. + CallbackCharFilter = bitLShift(1, 21), -- Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. + CallbackResize = bitLShift(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) + CallbackEdit = bitLShift(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] - WordWrap = bitLShift(1, 24), + WordWrap = bitLShift(1, 24), -- InputTextMultiline(): word-wrap lines that are too long. -- [Internal] - Multiline = bitLShift(1, 26), - TempInput = bitLShift(1, 27), - LocalizeDecimalPoint = bitLShift(1, 28), + Multiline = bitLShift(1, 26), -- For internal use by InputTextMultiline() + TempInput = bitLShift(1, 27), -- For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match. + LocalizeDecimalPoint = bitLShift(1, 28), -- For internal use by InputScalar() and TempInputScalar() } +------------------------------------------------------------------------------- +-- [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) +------------------------------------------------------------------------------- + +-- 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 + 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 +-- - ImGuiInputTextFlags.CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. +-- - ImGuiInputTextFlags.CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. --- @class ImGuiInputTextCallbackData --- @return ImGuiInputTextCallbackData @@ -33197,40 +38033,51 @@ function MT.ImGuiInputTextCallbackData:SelectAll() self.SelectionStart = 0; self function MT.ImGuiInputTextCallbackData:ClearSelection() self.SelectionStart = self.BufTextLen; self.SelectionEnd = self.BufTextLen end function MT.ImGuiInputTextCallbackData:HasSelection() return self.SelectionStart ~= self.SelectionEnd end +-- Callback and functions types --- @alias ImGuiInputTextCallback fun(data: ImGuiInputTextCallbackData) --- @alias ImGuiMemAllocFunc fun(T: function, start_idx: int, end_idx: int, userdata: any): table --- @alias ImGuiMemFreeFunc fun(owner: table, field: string, userdata: any) +-- ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] +-- NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, +-- you can poke into the draw list for that! Draw callback may be useful for example to: +-- A) Change your GPU render state, +-- B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. +-- The expected behavior from your rendering function is 'if (cmd.UserCallback != nil) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' --- @alias ImDrawCallback fun(parent_list: ImDrawList, cmd: ImDrawCmd) +-- Flags for ImGui.TreeNodeEx(), ImGui.CollapsingHeader*() --- @enum ImGuiTreeNodeFlags ImGuiTreeNodeFlags = { None = 0, - Selected = bitLShift(1, 0), - Framed = bitLShift(1, 1), - AllowOverlap = bitLShift(1, 2), - NoTreePushOnOpen = bitLShift(1, 3), - NoAutoOpenOnLog = bitLShift(1, 4), - DefaultOpen = bitLShift(1, 5), - OpenOnDoubleClick = bitLShift(1, 6), - OpenOnArrow = bitLShift(1, 7), - Leaf = bitLShift(1, 8), - Bullet = bitLShift(1, 9), - FramePadding = bitLShift(1, 10), - SpanAvailWidth = bitLShift(1, 11), - SpanFullWidth = bitLShift(1, 12), - SpanLabelWidth = bitLShift(1, 13), - SpanAllColumns = bitLShift(1, 14), - LabelSpanAllColumns = bitLShift(1, 15), - NavLeftJumpsToParent = bitLShift(1, 17), - DrawLinesNone = bitLShift(1, 18), - DrawLinesFull = bitLShift(1, 19), - DrawLinesToNodes = bitLShift(1, 20), + Selected = bitLShift(1, 0), -- Draw as selected + Framed = bitLShift(1, 1), -- Draw frame with background (e.g. for CollapsingHeader) + AllowOverlap = bitLShift(1, 2), -- Hit testing will allow subsequent widgets to overlap this one. Require previous frame HoveredId to match before being usable. Shortcut to calling SetNextItemAllowOverlap(). + NoTreePushOnOpen = bitLShift(1, 3), -- Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + NoAutoOpenOnLog = bitLShift(1, 4), -- Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + DefaultOpen = bitLShift(1, 5), -- Default node to be open + OpenOnDoubleClick = bitLShift(1, 6), -- Open on double-click instead of simple click (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. + OpenOnArrow = bitLShift(1, 7), -- Open when clicking on the arrow part (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. + Leaf = bitLShift(1, 8), -- No collapsing, no arrow (use as a convenience for leaf nodes). Note: will always open a tree/id scope and return true. If you never use that scope, add ImGuiTreeNodeFlags.NoTreePushOnOpen. + Bullet = bitLShift(1, 9), -- Display a bullet instead of arrow. IMPORTANT: node can still be marked open/close if you don't set the _Leaf flag! + FramePadding = bitLShift(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. + SpanAvailWidth = bitLShift(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. + SpanFullWidth = bitLShift(1, 12), -- Extend hit box to the left-most and right-most edges (cover the indent area). + SpanLabelWidth = bitLShift(1, 13), -- Narrow hit box + narrow hovering highlight, will only cover the label text. + SpanAllColumns = bitLShift(1, 14), -- Frame will span all columns of its container table (label will still fit in current column) + LabelSpanAllColumns = bitLShift(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 + NavLeftJumpsToParent = bitLShift(1, 17), -- Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfulfilled Left nav request remaining. + -- [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920. + -- Default value is pulled from style.TreeLinesFlags. May be overridden in TreeNode calls. + DrawLinesNone = bitLShift(1, 18), -- No lines drawn + DrawLinesFull = bitLShift(1, 19), -- Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. Faster (for large trees). + DrawLinesToNodes = bitLShift(1, 20), -- Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). - NoNavFocus = bitLShift(1, 27), - ClipLabelForTrailingButton = bitLShift(1, 28), - UpsideDownArrow = bitLShift(1, 29), + NoNavFocus = bitLShift(1, 27), -- Don't claim nav focus when interacting with this item (#8551) + ClipLabelForTrailingButton = bitLShift(1, 28), -- FIXME-WIP: Hard-coded for CollapsingHeader() + UpsideDownArrow = bitLShift(1, 29), -- FIXME-WIP: Turn Down arrow into an Up arrow, for reversed trees (#6517) } ImGuiTreeNodeFlags.CollapsingHeader = bitOr(ImGuiTreeNodeFlags.Framed, ImGuiTreeNodeFlags.NoTreePushOnOpen, ImGuiTreeNodeFlags.NoAutoOpenOnLog) @@ -33238,94 +38085,152 @@ ImGuiTreeNodeFlags.CollapsingHeader = bitOr(ImGuiTreeNodeFlags.Framed, ImGuiTree ImGuiTreeNodeFlags.OpenOnMask_ = bitOr(ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.OpenOnArrow) ImGuiTreeNodeFlags.DrawLinesMask_ = bitOr(ImGuiTreeNodeFlags.DrawLinesNone, ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DrawLinesToNodes) +------------------------------------------------------------------------------- +-- [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +------------------------------------------------------------------------------- + +-- Flags for ImGui.BeginTable() +-- - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. +-- Read comments/demos carefully + experiment with live demos to get acquainted with them. +-- - The DEFAULT sizing policies are: +-- - Default to ImGuiTableFlags.SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags.AlwaysAutoResize. +-- - Default to ImGuiTableFlags.SizingStretchSame if ScrollX is off. +-- - When ScrollX is off: +-- - Table defaults to ImGuiTableFlags.SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags.WidthStretch with same weight. +-- - Columns sizing policy allowed: Stretch (default), Fixed/Auto. +-- - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). +-- - Stretch Columns will share the remaining width according to their respective weight. +-- - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. +-- The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +-- (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). +-- - When ScrollX is on: +-- - Table defaults to ImGuiTableFlags.SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags.WidthFixed +-- - Columns sizing policy allowed: Fixed/Auto mostly. +-- - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed. +-- - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. +-- - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). +-- If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. +-- - Read on documentation at the top of imgui_tables.cpp for details. --- @enum ImGuiTableFlags ImGuiTableFlags = { + -- Features None = 0, - Resizable = bitLShift(1, 0), - Reorderable = bitLShift(1, 1), - Hideable = bitLShift(1, 2), - Sortable = bitLShift(1, 3), - NoSavedSettings = bitLShift(1, 4), - ContextMenuInBody = bitLShift(1, 5), - RowBg = bitLShift(1, 6), - BordersInnerH = bitLShift(1, 7), - BordersOuterH = bitLShift(1, 8), - BordersInnerV = bitLShift(1, 9), - BordersOuterV = bitLShift(1, 10), - NoBordersInBody = bitLShift(1, 11), - NoBordersInBodyUntilResize = bitLShift(1, 12), - SizingFixedFit = bitLShift(1, 13), - SizingFixedSame = bitLShift(2, 13), - SizingStretchProp = bitLShift(3, 13), - SizingStretchSame = bitLShift(4, 13), - NoHostExtendX = bitLShift(1, 16), - NoHostExtendY = bitLShift(1, 17), - NoKeepColumnsVisible = bitLShift(1, 18), - PreciseWidths = bitLShift(1, 19), - NoClip = bitLShift(1, 20), - PadOuterX = bitLShift(1, 21), - NoPadOuterX = bitLShift(1, 22), - NoPadInnerX = bitLShift(1, 23), - ScrollX = bitLShift(1, 24), - ScrollY = bitLShift(1, 25), - SortMulti = bitLShift(1, 26), - SortTristate = bitLShift(1, 27), - HighlightHoveredColumn = bitLShift(1, 28), + Resizable = bitLShift(1, 0), -- Enable resizing columns. + Reorderable = bitLShift(1, 1), -- Enable reordering columns in header row. (Need calling TableSetupColumn() + TableHeadersRow() to display headers, or using ImGuiTableFlags.ContextMenuInBody to access context-menu without headers). + Hideable = bitLShift(1, 2), -- Enable hiding/disabling columns in context menu. + Sortable = bitLShift(1, 3), -- Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags.SortMulti and ImGuiTableFlags.SortTristate. + NoSavedSettings = bitLShift(1, 4), -- Disable persisting columns order, width, visibility and sort settings in the .ini file. + ContextMenuInBody = bitLShift(1, 5), -- Right-click on columns body/contents will also display table context menu. By default it is available in TableHeadersRow(). + -- Decorations + RowBg = bitLShift(1, 6), -- Set each RowBg color with ImGuiCol.TableRowBg or ImGuiCol.TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags.RowBg0 on each row manually) + BordersInnerH = bitLShift(1, 7), -- Draw horizontal borders between rows. + BordersOuterH = bitLShift(1, 8), -- Draw horizontal borders at the top and bottom. + BordersInnerV = bitLShift(1, 9), -- Draw vertical borders between columns. + BordersOuterV = bitLShift(1, 10), -- Draw vertical borders on the left and right sides. + NoBordersInBody = bitLShift(1, 11), -- [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style + NoBordersInBodyUntilResize = bitLShift(1, 12), -- [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style + -- Sizing Policy (read above for defaults) + SizingFixedFit = bitLShift(1, 13), -- Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. + SizingFixedSame = bitLShift(2, 13), -- Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags.NoKeepColumnsVisible. + SizingStretchProp = bitLShift(3, 13), -- Columns default to _WidthStretch with default weights proportional to each columns contents widths. + SizingStretchSame = bitLShift(4, 13), -- Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). + -- Sizing Extra Options + NoHostExtendX = bitLShift(1, 16), -- Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. + NoHostExtendY = bitLShift(1, 17), -- Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. + NoKeepColumnsVisible = bitLShift(1, 18), -- Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. + PreciseWidths = bitLShift(1, 19), -- Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. + -- Clipping + NoClip = bitLShift(1, 20), -- Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). + -- Padding + PadOuterX = bitLShift(1, 21), -- Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. + NoPadOuterX = bitLShift(1, 22), -- Default if BordersOuterV is off. Disable outermost padding. + NoPadInnerX = bitLShift(1, 23), -- Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). + -- Scrolling + ScrollX = bitLShift(1, 24), -- Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. + ScrollY = bitLShift(1, 25), -- Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + -- Sorting + SortMulti = bitLShift(1, 26), -- Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). + SortTristate = bitLShift(1, 27), -- Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). + -- Miscellaneous + HighlightHoveredColumn = bitLShift(1, 28), -- Highlight column headers when hovered (may evolve into a fuller highlight) } -ImGuiTableFlags.BordersH = bitOr(ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.BordersOuterH) -ImGuiTableFlags.BordersV = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersOuterV) -ImGuiTableFlags.BordersInner = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersInnerH) -ImGuiTableFlags.BordersOuter = bitOr(ImGuiTableFlags.BordersOuterV, ImGuiTableFlags.BordersOuterH) -ImGuiTableFlags.Borders = bitOr(ImGuiTableFlags.BordersInner, ImGuiTableFlags.BordersOuter) +ImGuiTableFlags.BordersH = bitOr(ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.BordersOuterH) -- Draw horizontal borders. +ImGuiTableFlags.BordersV = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersOuterV) -- Draw vertical borders. +ImGuiTableFlags.BordersInner = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersInnerH) -- Draw inner borders. +ImGuiTableFlags.BordersOuter = bitOr(ImGuiTableFlags.BordersOuterV, ImGuiTableFlags.BordersOuterH) -- Draw outer borders. +ImGuiTableFlags.Borders = bitOr(ImGuiTableFlags.BordersInner, ImGuiTableFlags.BordersOuter) -- Draw all borders. +-- [Internal] Combinations and masks ImGuiTableFlags.SizingMask_ = bitOr(ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.SizingFixedSame, ImGuiTableFlags.SizingStretchProp, ImGuiTableFlags.SizingStretchSame) +-- Flags for ImGui.TableSetupColumn() --- @enum ImGuiTableColumnFlags ImGuiTableColumnFlags = { + -- Input configuration flags None = 0, - Disabled = bitLShift(1, 0), - DefaultHide = bitLShift(1, 1), - DefaultSort = bitLShift(1, 2), - WidthStretch = bitLShift(1, 3), - WidthFixed = bitLShift(1, 4), - NoResize = bitLShift(1, 5), - NoReorder = bitLShift(1, 6), - NoHide = bitLShift(1, 7), - NoClip = bitLShift(1, 8), - NoSort = bitLShift(1, 9), - NoSortAscending = bitLShift(1, 10), - NoSortDescending = bitLShift(1, 11), - NoHeaderLabel = bitLShift(1, 12), - NoHeaderWidth = bitLShift(1, 13), - PreferSortAscending = bitLShift(1, 14), - PreferSortDescending = bitLShift(1, 15), - IndentEnable = bitLShift(1, 16), - IndentDisable = bitLShift(1, 17), - AngledHeader = bitLShift(1, 18), + Disabled = bitLShift(1, 0), -- Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) + DefaultHide = bitLShift(1, 1), -- Default as a hidden/disabled column. + DefaultSort = bitLShift(1, 2), -- Default as a sorting column. + WidthStretch = bitLShift(1, 3), -- Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). + WidthFixed = bitLShift(1, 4), -- Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). + NoResize = bitLShift(1, 5), -- Disable manual resizing. + NoReorder = bitLShift(1, 6), -- Disable manual reordering this column, this will also prevent other columns from crossing over this column. + NoHide = bitLShift(1, 7), -- Disable ability to hide/disable this column. + NoClip = bitLShift(1, 8), -- Disable clipping for this column (all NoClip columns will render in a same draw command). + NoSort = bitLShift(1, 9), -- Disable ability to sort on this field (even if ImGuiTableFlags.Sortable is set on the table). + NoSortAscending = bitLShift(1, 10), -- Disable ability to sort in the ascending direction. + NoSortDescending = bitLShift(1, 11), -- Disable ability to sort in the descending direction. + NoHeaderLabel = bitLShift(1, 12), -- TableHeadersRow() will submit an empty label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. You may append into this cell by calling TableSetColumnIndex() right after the TableHeadersRow() call. + NoHeaderWidth = bitLShift(1, 13), -- Disable header text width contribution to automatic column width. + PreferSortAscending = bitLShift(1, 14), -- Make the initial sort direction Ascending when first sorting on this column (default). + PreferSortDescending = bitLShift(1, 15), -- Make the initial sort direction Descending when first sorting on this column. + IndentEnable = bitLShift(1, 16), -- Use current Indent value when entering cell (default for column 0). + IndentDisable = bitLShift(1, 17), -- Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. + AngledHeader = bitLShift(1, 18), -- TableHeadersRow() will submit an angled header row for this column. Note this will add an extra row. - IsEnabled = bitLShift(1, 24), - IsVisible = bitLShift(1, 25), - IsSorted = bitLShift(1, 26), - IsHovered = bitLShift(1, 27), + -- Output status flags, read-only via TableGetColumnFlags() + IsEnabled = bitLShift(1, 24), -- Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. + IsVisible = bitLShift(1, 25), -- Status: is visible == is enabled AND not clipped by scrolling. + IsSorted = bitLShift(1, 26), -- Status: is currently part of the sort specs + IsHovered = bitLShift(1, 27), -- Status: is hovered by mouse - NoDirectResize_ = bitLShift(1, 30), + NoDirectResize_ = bitLShift(1, 30), -- [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) } +-- [Internal] Combinations and masks ImGuiTableColumnFlags.WidthMask_ = bitOr(ImGuiTableColumnFlags.WidthStretch, ImGuiTableColumnFlags.WidthFixed) ImGuiTableColumnFlags.IndentMask_ = bitOr(ImGuiTableColumnFlags.IndentEnable, ImGuiTableColumnFlags.IndentDisable) ImGuiTableColumnFlags.StatusMask_ = bitOr(ImGuiTableColumnFlags.IsEnabled, ImGuiTableColumnFlags.IsVisible, ImGuiTableColumnFlags.IsSorted, ImGuiTableColumnFlags.IsHovered) +-- Flags for ImGui.TableNextRow() +-- - Headers: Identify header row (set default background color + width of its contents accounted differently for auto column width) --- @enum ImGuiTableRowFlags ImGuiTableRowFlags = { None = 0, Headers = bitLShift(1, 0) } +-- Enum for ImGui.TableSetBgColor() +-- Background colors are rendering in 3 layers: +-- - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. +-- - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. +-- - Layer 2: draw with CellBg color if set. +-- The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color. +-- When using ImGuiTableFlags.RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. +-- If you set the color of RowBg0 target, your color will override the existing RowBg0 color. +-- If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. +-- - RowBg0: Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags.RowBg is used) +-- - RowBg1: Set row background color 1 (generally used for selection marking) +-- - CellBg: Set cell background color (top-most color) --- @enum ImGuiTableBgTarget ImGuiTableBgTarget = { None = 0, RowBg0 = 1, RowBg1 = 2, CellBg = 3 } +-- A sorting direction +-- - Ascending = 0->9, A->Z etc. +-- - Descending = 9->0, Z->A etc. --- @enum ImGuiSortDirection ImGuiSortDirection = { None = 0, Ascending = 1, Descending = 2 } +-- Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() --- @class ImGuiPayload --- Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity. local IM_PAYLOAD = {} @@ -33342,6 +38247,12 @@ function ImGuiPayload_IsDataType(p, t) return p.DataFrameCount ~= -1 and p.DataT function ImGuiPayload_IsPreview(p) return p.Preview end function ImGuiPayload_IsDelivery(p) return p.Delivery end +------------------------------------------------------------------------------- +-- [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) +------------------------------------------------------------------------------- + +-- Helper: Growable text buffer for logging/accumulating text +-- (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') --- @class ImGuiTextBuffer # string builder: Buf is a list of string chunks local ImGuiTextBufferMT = {} ImGuiTextBufferMT.__index = ImGuiTextBufferMT @@ -33905,9 +38816,36 @@ return true end __FILES['imgui_internal.lua'] = function() ---- Dear ImGui WIP +-- dear imgui, v1.93.0 WIP -- (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. + +-- Index of this file: +-- +-- [SECTION] Context pointer +-- [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 +-- [SECTION] Inputs support +-- [SECTION] Navigation support +-- [SECTION] Viewport support +-- [SECTION] Settings support +-- [SECTION] Localization support +-- [SECTION] Metrics, Debug tools +-- [SECTION] ImGuiContext (main imgui context) +-- [SECTION] ImGuiWindowTempData, ImGuiWindow +-- [SECTION] Tab bar, Tab item support +-- [SECTION] ImGui internal API +-- [SECTION] ImFontLoader +-- [SECTION] ImFontAtlas internal API +-- +-- PORT: the order of declarations in this file does not strictly follow upstream's imgui_internal.h. + --- @meta local type = ImGui._GetTypeFunc() @@ -33941,6 +38879,9 @@ function ImGui._ByteArrayToString(buf, buf_begin, buf_end) end +-- 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, +-- Indexes have the same lifetime as the associated object. --- ImPool: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based). --- `ctor` creates a new element. Removed slots are recycled via FreeIdx (-1 = none; free slots chain through `_NextFree`). local IM_POOL = {} @@ -33978,8 +38919,13 @@ end function IM_POOL:Reserve(n) end -- NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end` +------------------------------------------------------------------------------- +-- [SECTION] Context pointer +-- See implementation of this variable in imgui.cpp for comments and details. +------------------------------------------------------------------------------- + --- @type ImGuiContext? -local GImGui +local GImGui -- Current implicit context pointer -- Sets local `GImGui` in this file(imgui_internal.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` @@ -33992,6 +38938,10 @@ local setmetatable = setmetatable local MT = ImGui.GetMetatables() +------------------------------------------------------------------------------- +-- [SECTION] Macros +------------------------------------------------------------------------------- + IM_TABSIZE = 4 FLT_MIN = 1.1754943508223e-38 @@ -34001,13 +38951,22 @@ INT_MIN = -0x7fffffff - 1 INT_MAX = 0x7fffffff UINT_MAX = 0x7fffffff * 2 + 1 -NAV_WINDOWING_HIGHLIGHT_DELAY = 0.5 -NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10 -NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY = 0.60 +NAV_WINDOWING_HIGHLIGHT_DELAY = 0.5 -- Time before the highlight and screen dimming starts fading in +NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10 -- Time to highlight an item activated by a shortcut. +NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY = 0.60 -- Time to hold activation button (e.g. FaceDown) to turn the activation into a text input. IM_PI = math.pi -ImPow = math.pow -ImLog = math.log + +------------------------------------------------------------------------------- +-- [SECTION] Generic helpers +-- Note that the ImXXX helpers functions are lower-level than ImGui functions. +-- ImGui functions or the ImGui context are never called/used from other ImXXX functions. +------------------------------------------------------------------------------- + +-- Helpers: Maths +-- - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy) +ImPow = math.pow -- DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision +ImLog = math.log -- DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision ImAbs = math.abs ImFabs = math.abs ImFmod = function(a, b) if b < 0 then b = -b end; if a < 0 then return -(-a % b) else return a % b end; end @@ -34045,6 +39004,7 @@ function ImSubClampOverflow(a, b, mn, mx) return a - b end +-- - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double --- @overload fun(lhs: number, rhs: number): number --- @overload fun(lhs: ImVec2, rhs: ImVec2): ImVec2 @@ -34061,6 +39021,7 @@ function ImMax(lhs, rhs) return ImVec2(mathMax(lhs.x, rhs.x), mathMax(lhs.y, rhs.y)) end +-- Helpers: Sorting --- @param base table --- @param count int --- @param cmp_func fun(lhs, rhs): bool @@ -34098,6 +39059,7 @@ end ImTrunc64 = _Trunc +-- Consider using the bit-hack version (search for "0x1p120f"). --- @param f float function ImCeilFast(f) local i @@ -34110,10 +39072,11 @@ function IM_ROUNDUP_TO_EVEN(n) return (ImCeil((n) / 2) * 2) end function ImRsqrt(x) return (1 / ImSqrt(x)) end function IM_TRUNC(VAL) return math.floor(VAL) end -- Positive values only! -function IM_ROUND(VAL) return math.floor(VAL + 0.5) end +function IM_ROUND(VAL) return math.floor(VAL + 0.5) end -- Positive values only! -function ImFloor(f) if f >= 0 or math.floor(f) == f then return math.floor(f) else return math.floor(f) - 1 end end +function ImFloor(f) if f >= 0 or math.floor(f) == f then return math.floor(f) else return math.floor(f) - 1 end end -- Decent replacement for floorf() +-- Helpers: Bit manipulation --- @param v int function ImIsPowerOfTwo(v) return (v ~= 0) and (bitAnd(v, (v - 1)) == 0) @@ -34233,8 +39196,8 @@ end function ImSaturate(f) return ((f < 0.0 and 0.0) or (f > 1.0 and 1.0) or f) end -IM_F32_TO_INT8_UNBOUND = function(val) return math.floor(val * 255.0 + (val >= 0 and 0.5 or -0.5)) end -IM_F32_TO_INT8_SAT = function(val) return math.floor(ImSaturate(val) * 255.0 + 0.5) end +IM_F32_TO_INT8_UNBOUND = function(val) return math.floor(val * 255.0 + (val >= 0 and 0.5 or -0.5)) end -- Unsaturated, for display purpose +IM_F32_TO_INT8_SAT = function(val) return math.floor(ImSaturate(val) * 255.0 + 0.5) end -- Saturated, always output 0..255 --- @param s ImString --- @param i int @@ -34247,6 +39210,7 @@ function ImStrByte(s, i) end end +-- Stacked color modifier, backup of modified data so we can restore it --- @class ImGuiColorMod --- @field Col ImGuiCol --- @field BackupValue ImVec4 @@ -34341,20 +39305,27 @@ IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE = 128.0 IMGUI_WINDOW_HARD_MIN_SIZE = 4.0 -IM_DRAWLIST_ARCFAST_TABLE_SIZE = 48 -IM_DRAWLIST_ARCFAST_SAMPLE_MAX = IM_DRAWLIST_ARCFAST_TABLE_SIZE +-- ImDrawList: Lookup tables +IM_DRAWLIST_ARCFAST_TABLE_SIZE = 48 -- Number of samples in adaptive arc drawing lookup table. +IM_DRAWLIST_ARCFAST_SAMPLE_MAX = IM_DRAWLIST_ARCFAST_TABLE_SIZE -- Sample index _PathArcToFastEx() for 360 angle. +-- Macros used by Recoverable Error handling +-- - Only dispatch error if _EXPR: evaluate as assert (similar to an assert macro). +-- - The message will always be a string literal, in order to increase likelihood of being display by an assert handler. +-- - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling. +-- - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling. -- Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert. -function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end +function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end -- Recoverable User Error function IM_ASSERT_USER_ERROR_RET(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end +-- Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam. local function DebugLogIf(flag, fmt, ...) local g = GImGui if g and bitAnd(g.DebugLogFlags, flag) ~= 0 then ImGui.DebugLog(fmt, ...) end end function IMGUI_DEBUG_LOG_ACTIVEID(...) DebugLogIf(ImGuiDebugLogFlags.EventActiveId, ...) end function IMGUI_DEBUG_LOG_POPUP(...) DebugLogIf(ImGuiDebugLogFlags.EventPopup, ...) end -function IMGUI_DEBUG_LOG_FONT(...) DebugLogIf(ImGuiDebugLogFlags.EventFont, ...) end +function IMGUI_DEBUG_LOG_FONT(...) DebugLogIf(ImGuiDebugLogFlags.EventFont, ...) end -- Called from ImFontAtlas function which may operate without a context. function IMGUI_DEBUG_LOG_VIEWPORT(...) DebugLogIf(ImGuiDebugLogFlags.EventViewport, ...) end function IMGUI_DEBUG_LOG_FOCUS(...) DebugLogIf(ImGuiDebugLogFlags.EventFocus, ...) end function IMGUI_DEBUG_LOG_NAV(...) DebugLogIf(ImGuiDebugLogFlags.EventNav, ...) end @@ -34369,9 +39340,17 @@ function IMGUI_DEBUG_LOG_ERROR(...) DebugLogIf(ImGuiDebugLogFlags.EventError, .. --- @alias ImGuiSelectionUserData any ImGuiSelectionUserData_Invalid = -1 -ImGuiKeyOwner_Any = 0 -ImGuiKeyOwner_NoOwner = 4294967295 +-- Input function taking an 'ImGuiID owner_id' argument defaults to (ImGuiKeyOwner_Any == 0) aka don't test ownership, which matches legacy behavior. +ImGuiKeyOwner_Any = 0 -- Accept key that have an owner, UNLESS a call to SetKeyOwner() explicitly used ImGuiInputFlags.LockThisFrame or ImGuiInputFlags.LockUntilRelease. +ImGuiKeyOwner_NoOwner = 4294967295 -- Require key to have no owner. +------------------------------------------------------------------------------- +-- [SECTION] ImGui internal API +-- No guarantee of forward compatibility here! +------------------------------------------------------------------------------- + +-- Inputs +-- FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. --- @param button ImGuiMouseButton --- @return ImGuiKey function ImGui.MouseButtonToKey(button) IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT) return ImGuiKey.MouseLeft + button end @@ -34427,6 +39406,17 @@ function ImGui.ConvertSingleModFlagToKey(key) return key end +-- [EXPERIMENTAL] Low-Level: Key/Input Ownership +-- - The idea is that instead of "eating" a given input, we can link to an owner id. +-- - Ownership is most often claimed as a result of reacting to a press/down event (but occasionally may be claimed ahead). +-- - Input queries can then read input by specifying ImGuiKeyOwner_Any (== 0), ImGuiKeyOwner_NoOwner (== -1) or a custom ID. +-- - Legacy input queries (without specifying an owner or _Any or _None) are equivalent to using ImGuiKeyOwner_Any (== 0). +-- - Input ownership is automatically released on the frame after a key is released. Therefore: +-- - for ownership registration happening as a result of a down/press event, the SetKeyOwner() call may be done once (common case). +-- - for ownership registration happening ahead of a down/press event, the SetKeyOwner() call needs to be made every frame (happens if e.g. claiming ownership on hover). +-- - SetItemKeyOwner() is a shortcut for common simple case. A custom widget will probably want to call SetKeyOwner() multiple times directly based on its interaction state. +-- - This is marked experimental because not all widgets are fully honoring the Set/Test idioms. We will need to move forward step by step. +-- Please open a GitHub Issue to submit your usage scenario or if there's a use case you need solved. --- @param ctx ImGuiContext --- @param key ImGuiKey function ImGui.GetKeyOwnerData(ctx, key) @@ -34435,6 +39425,8 @@ function ImGui.GetKeyOwnerData(ctx, key) return ctx.KeysOwnerData[key - ImGuiKey.NamedKey_BEGIN] end +-- This extends ImGuiKeyData but only for named keys (legacy keys don't support the new features) +-- Stored in main context (1 per named key). In the future it might be merged into ImGuiKeyData. --- @class ImGuiKeyOwnerData --- @return ImGuiKeyOwnerData @@ -34443,8 +39435,8 @@ function ImGuiKeyOwnerData() return { OwnerCurr = ImGuiKeyOwner_NoOwner, OwnerNext = ImGuiKeyOwner_NoOwner, - LockThisFrame = false, - LockUntilRelease = false + LockThisFrame = false, -- Reading this key requires explicit owner id (until end of frame). Set by ImGuiInputFlags.LockThisFrame. + LockUntilRelease = false -- Reading this key requires explicit owner id (until key is released). Set by ImGuiInputFlags.LockUntilRelease. When this is true LockThisFrame is always true as well. } end @@ -34487,22 +39479,22 @@ function ImCharIsBlankW(c) return c == 32 or c == 9 or c == 0x3000 end ImGuiNavMoveFlags = { None = 0, - LoopX = bitLShift(1, 0), + LoopX = bitLShift(1, 0), -- On failed request, restart from opposite side LoopY = bitLShift(1, 1), - WrapX = bitLShift(1, 2), - WrapY = bitLShift(1, 3), - AllowCurrentNavId = bitLShift(1, 4), - AlsoScoreVisibleSet = bitLShift(1, 5), - ScrollToEdgeY = bitLShift(1, 6), + WrapX = bitLShift(1, 2), -- On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left) + WrapY = bitLShift(1, 3), -- This is not super useful but provided for completeness + AllowCurrentNavId = bitLShift(1, 4), -- Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place) + AlsoScoreVisibleSet = bitLShift(1, 5), -- Store alternate result in NavMoveResultLocalVisible that only comprise elements that are already fully visible (used by PageUp/PageDown) + ScrollToEdgeY = bitLShift(1, 6), -- Force scrolling to min/max (used by Home/End) -- FIXME-NAV: Aim to remove or reword as ImGuiScrollFlags Forwarded = bitLShift(1, 7), - DebugNoResult = bitLShift(1, 8), - FocusApi = bitLShift(1, 9), - IsTabbing = bitLShift(1, 10), - IsPageMove = bitLShift(1, 11), - Activate = bitLShift(1, 12), - NoSelect = bitLShift(1, 13), - NoSetNavCursorVisible = bitLShift(1, 14), - NoClearActiveId = bitLShift(1, 15), + DebugNoResult = bitLShift(1, 8), -- Dummy scoring for debug purpose, don't apply result + FocusApi = bitLShift(1, 9), -- Requests from focus API can land/focus/activate items even if they are marked with _NoTabStop (see NavProcessItemForTabbingRequest() for details) + IsTabbing = bitLShift(1, 10), -- == Focus + Activate if item is Inputable + DontChangeNavHighlight + IsPageMove = bitLShift(1, 11), -- Identify a PageDown/PageUp request. + Activate = bitLShift(1, 12), -- Activate/select target item. + NoSelect = bitLShift(1, 13), -- Don't trigger selection by not setting g.NavJustMovedTo + NoSetNavCursorVisible = bitLShift(1, 14), -- Do not alter the nav cursor visible state + NoClearActiveId = bitLShift(1, 15), -- (Experimental) Do not clear active id when applying move result } ImGuiNavMoveFlags.WrapMask_ = bitOr(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.LoopY, ImGuiNavMoveFlags.WrapX, ImGuiNavMoveFlags.WrapY) @@ -34510,40 +39502,54 @@ ImGuiNavMoveFlags.WrapMask_ = bitOr(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.L --- @enum ImGuiNavLayer ImGuiNavLayer = { - Main = 0, - Menu = 1, + Main = 0, -- Main scrolling layer + Menu = 1, -- Menu layer (access with Alt) COUNT = 2 } -ImGuiItemFlags.ReadOnly = bitLShift(1, 11) +------------------------------------------------------------------------------- +-- [SECTION] Widgets support: flags, enums, data structures +------------------------------------------------------------------------------- + +-- Extend ImGuiItemFlags +-- - input: PushItemFlag() manipulates g.CurrentItemFlags, g.NextItemData.ItemFlags, ItemAdd() calls may add extra flags too. +-- - output: stored in g.LastItemData.ItemFlags + +-- Controlled by user +ImGuiItemFlags.ReadOnly = bitLShift(1, 11) -- false -- [ALPHA] Allow hovering interactions but underlying value is not changed. ImGuiItemFlags.MixedValue = bitLShift(1, 12) -ImGuiItemFlags.NoWindowHoverableCheck = bitLShift(1, 13) -ImGuiItemFlags.AllowOverlap = bitLShift(1, 14) -ImGuiItemFlags.NoNavDisableMouseHover = bitLShift(1, 15) -ImGuiItemFlags.NoMarkEdited = bitLShift(1, 16) -ImGuiItemFlags.NoFocus = bitLShift(1, 17) +ImGuiItemFlags.NoWindowHoverableCheck = bitLShift(1, 13) -- false -- Disable hoverable check in ItemHoverable() +ImGuiItemFlags.AllowOverlap = bitLShift(1, 14) -- false -- Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. +ImGuiItemFlags.NoNavDisableMouseHover = bitLShift(1, 15) -- false -- Nav keyboard/gamepad mode doesn't disable hover highlight (behave as if NavHighlightItemUnderNav==false). +ImGuiItemFlags.NoMarkEdited = bitLShift(1, 16) -- false -- Skip calling MarkItemEdited() +ImGuiItemFlags.NoFocus = bitLShift(1, 17) -- false -- [EXPERIMENTAL: Not very well specced] Clicking doesn't take focus. Automatically sets ImGuiButtonFlags.NoFocus + ImGuiButtonFlags.NoNavFocus in ButtonBehavior(). -ImGuiItemFlags.Inputable = bitLShift(1, 20) -ImGuiItemFlags.HasSelectionUserData = bitLShift(1, 21) -ImGuiItemFlags.IsMultiSelect = bitLShift(1, 22) +-- Controlled by widget code +ImGuiItemFlags.Inputable = bitLShift(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. +ImGuiItemFlags.HasSelectionUserData = bitLShift(1, 21) -- false -- Set by SetNextItemSelectionUserData() +ImGuiItemFlags.IsMultiSelect = bitLShift(1, 22) -- false -- Set by SetNextItemSelectionUserData() -ImGuiItemFlags.Default_ = bitOr(ImGuiItemFlags.AutoClosePopups, ImGuiItemFlags.LiveEditOnInputText) +ImGuiItemFlags.Default_ = bitOr(ImGuiItemFlags.AutoClosePopups, ImGuiItemFlags.LiveEditOnInputText) -- Please don't change, use PushItemFlag() instead. +-- Helpers: High-level text functions (DO NOT USE!!! THIS IS A MINIMAL SUBSET OF LARGER UPCOMING CHANGES) --- @enum ImDrawTextFlags ImDrawTextFlags = { None = 0, - CpuFineClip = bitLShift(1, 0), + CpuFineClip = bitLShift(1, 0), -- Must be == 1/true for legacy with 'bool cpu_fine_clip' arg to RenderText() WrapKeepBlanks = bitLShift(1, 1), StopOnNewLine = bitLShift(1, 2) } +-- Flags for FocusWindow(). This is not called ImGuiFocusFlags to avoid confusion with public-facing ImGuiFocusedFlags. +-- FIXME: Once we finishing replacing more uses of GetTopMostPopupModal()+IsWindowWithinBeginStackOf() +-- and FindBlockingModal() with this, we may want to change the flag to be opt-out instead of opt-in. --- @enum ImGuiFocusRequestFlags ImGuiFocusRequestFlags = { None = 0, - RestoreFocusedChild = bitLShift(1, 0), - UnlessBelowModal = bitLShift(1, 1) + RestoreFocusedChild = bitLShift(1, 0), -- Find last focused child (if any) and focus it instead. + UnlessBelowModal = bitLShift(1, 1) -- Do not set focus if the window is below a modal. } --- @enum ImGuiTextFlags @@ -34553,6 +39559,7 @@ ImGuiTextFlags = NoWidthForLargeClippedText = bitLShift(1, 0) } +-- Character classification for word-wrapping logic --- @enum ImWcharClass ImWcharClass = { @@ -34561,6 +39568,8 @@ ImWcharClass = Other = 2 } +-- Helper: ImVec1 (1D vector) +-- (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) --- @class ImVec1 --- @field x number local IM_VEC1 = {} @@ -34576,11 +39585,13 @@ function ImVec1_Copy(dest, src) dest.x = src.x end +-- Helper: ImRect (2D axis aligned bounding-box) +-- NB: we can't rely on ImVec2 math operators being available here! --- @class ImRect --- @field [1] ImVec2 --- @field [2] ImVec2 ---- @field Min ImVec2 ---- @field Max ImVec2 +--- @field Min ImVec2 # Upper-left +--- @field Max ImVec2 # Lower-right local IM_RECT = {} setmetatable(IM_RECT, { __index = function(_, k) if k ~= "Min" and k ~= "Max" then error("ImRect: unknown key " .. tostring(k), 2) end end }) @@ -34632,20 +39643,22 @@ function IM_RECT:GetHeight() return self.Max.y - self.Min.y end function IM_RECT:GetSize() return ImVec2(self.Max.x - self.Min.x, self.Max.y - self.Min.y) end --- @nodiscard -function IM_RECT:GetTL() return ImVec2(self.Min.x, self.Min.y) end +function IM_RECT:GetTL() return ImVec2(self.Min.x, self.Min.y) end -- Top-left --- @nodiscard -function IM_RECT:GetTR() return ImVec2(self.Max.x, self.Min.y) end +function IM_RECT:GetTR() return ImVec2(self.Max.x, self.Min.y) end -- Top-right --- @nodiscard -function IM_RECT:GetBL() return ImVec2(self.Min.x, self.Max.y) end +function IM_RECT:GetBL() return ImVec2(self.Min.x, self.Max.y) end -- Bottom-left --- @nodiscard -function IM_RECT:GetBR() return ImVec2(self.Max.x, self.Max.y) end +function IM_RECT:GetBR() return ImVec2(self.Max.x, self.Max.y) end -- Bottom-right +-- Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. --- @param r ImRect function IM_RECT:ClipWith(r) ImVec2_Copy(self.Min, ImMax(self.Min, r.Min)); ImVec2_Copy(self.Max, ImMin(self.Max, r.Max)) end +-- Full version, ensure both points are fully clipped. --- @param r ImRect function IM_RECT:ClipWithFull(r) @@ -34726,12 +39739,15 @@ function ImRect_CopyFromV4(dest, src) dest.Max.x = src.z; dest.Max.y = src.w end +-- Helper: ImBitArray +-- Macro version of ImBitArrayTestBit(): ensure args have side-effect or are costly! --- @param _ARRAY ImU32[] --- @param _N int function IM_BITARRAY_TESTBIT(_ARRAY, _N) return bitAnd(_ARRAY[bitRShift(_N - 1, 5) + 1], bitLShift(1, bitAnd(_N - 1, 31))) ~= 0 end +-- Macro version of ImBitArrayClearBit(): ensure args have side-effect or are costly! --- @param _ARRAY ImU32[] --- @param _N int function IM_BITARRAY_CLEARBIT(_ARRAY, _N) @@ -34747,8 +39763,11 @@ function ImBitArraySetBit(arr, n) arr[idx] = bitOr(arr[idx], mask) end +-- Bit array for named keys --- @alias ImBitArrayForNamedKeys ImBitArray +-- Helper: ImBitArray class (wrapper over ImBitArray functions) +-- Store 1-bit per value. --- NOTE: This struct is expensive to create --- @class ImBitArray --- @field Data ImU32[] @@ -34775,6 +39794,9 @@ function ImBitArray(BITCOUNT, OFFSET) return this end +-- 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. +-- so e.g. 'PathArcTo(center, radius, PI * -0.5, PI)' is ok, whereas 'PathArcTo(center, radius, PI, PI * -0.5)' won't have correct anti-aliasing when followed by PathFillConvex(). function MT.ImDrawList:PathClear() self._Path:clear() end --- @param pos ImVec2 @@ -34812,24 +39834,32 @@ function ImGui.SetNextItemColorMarker(col) g.NextItemData.ColorMarker = col end +------------------------------------------------------------------------------- +-- [SECTION] ImDrawList support +------------------------------------------------------------------------------- + +-- Data shared between all ImDrawList instances +-- 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. --- @class ImDrawListSharedData ---- @field TexUvWhitePixel ImVec2 ---- @field TexUvLines ImVec4[] ---- @field FontAtlas ImFontAtlas ---- @field Font ImFont ---- @field FontSize float ---- @field FontScale float +--- @field TexUvWhitePixel ImVec2 # UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) +--- @field TexUvLines ImVec4[] # UV of anti-aliased lines in the atlas (== FontAtlas->Builder->TexUvLines) +--- @field FontAtlas ImFontAtlas # Current font atlas +--- @field Font ImFont # Current font (used for simplified AddText overload) +--- @field FontSize float # Current font size (used for simplified AddText overload) +--- @field FontScale float # Current font scale (== FontSize / Font->FontSize) --- @field CurveTessellationTol float ---- @field CircleTessellationMaxError float +--- @field CircleTessellationMaxError float # Number of circle segments to use per pixel of radius for AddCircle() etc --- @field InitialFringeScale float --- @field InitialFlags ImDrawListFlags ---- @field ClipRectFullscreen? ImVec4 ---- @field TempBuffer ImVector ---- @field DrawLists ImVector ---- @field Context? ImGuiContext ---- @field ArcFastVtx table # 1-based table ---- @field ArcFastRadiusCutoff float ---- @field CircleSegmentCounts table # 1-based table +--- @field ClipRectFullscreen? ImVec4 # Value for PushClipRectFullscreen() +--- @field TempBuffer ImVector # Temporary write buffer +--- @field DrawLists ImVector # All draw lists associated to this ImDrawListSharedData +--- @field Context? ImGuiContext # [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case. +--- @field ArcFastVtx table # 1-based table. Sample points on the quarter of the circle. +--- @field ArcFastRadiusCutoff float # Cutoff radius after which arc drawing will fallback to slower PathArcTo() +--- @field CircleSegmentCounts table # 1-based table. Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) MT.ImDrawListSharedData = {} MT.ImDrawListSharedData.__index = MT.ImDrawListSharedData @@ -34837,28 +39867,29 @@ MT.ImDrawListSharedData.__index = MT.ImDrawListSharedData --- @nodiscard function ImDrawListSharedData() local this = setmetatable({ - TexUvWhitePixel = nil, - TexUvLines = nil, - FontAtlas = nil, + TexUvWhitePixel = nil, -- UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) + TexUvLines = nil, -- UV of anti-aliased lines in the atlas (== FontAtlas->Builder->TexUvLines) + FontAtlas = nil, -- Current font atlas - Font = nil, - FontSize = 0, - FontScale = 0, + Font = nil, -- Current font (used for simplified AddText overload) + FontSize = 0, -- Current font size (used for simplified AddText overload) + FontScale = 0, -- Current font scale (== FontSize / Font->FontSize) CurveTessellationTol = 0, - CircleTessellationMaxError = 0, + CircleTessellationMaxError = 0, -- Number of circle segments to use per pixel of radius for AddCircle() etc InitialFringeScale = 1, InitialFlags = 0, - ClipRectFullscreen = nil, - TempBuffer = ImVector(ImVec2), - DrawLists = ImVector(), + ClipRectFullscreen = nil, -- Value for PushClipRectFullscreen() + TempBuffer = ImVector(ImVec2), -- Temporary write buffer + DrawLists = ImVector(), -- All draw lists associated to this ImDrawListSharedData - ArcFastVtx = {}, - ArcFastRadiusCutoff = nil, - CircleSegmentCounts = {}, + -- Lookup tables + ArcFastVtx = {}, -- Sample points on the quarter of the circle. + ArcFastRadiusCutoff = nil, -- Cutoff radius after which arc drawing will fallback to slower PathArcTo() + CircleSegmentCounts = {}, -- Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) - Context = nil + Context = nil -- [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case. }, MT.ImDrawListSharedData) for i = 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE do @@ -34869,6 +39900,7 @@ function ImDrawListSharedData() return this end +-- Internal storage for incrementally packing and building a ImFontAtlas --- @class ImFontAtlasBuilder --- @field PackContext stbrp_context --- @field PackNodes ImVector @@ -34898,27 +39930,29 @@ function ImFontAtlasBuilder() --- @type ImFontAtlasBuilder local this = setmetatable({}, MT.ImFontAtlasBuilder) - this.PackContext = nil -- struct stbrp_context_opaque { char data[80]; }; + this.PackContext = nil -- struct stbrp_context_opaque { char data[80]; }; -- Actually 'stbrp_context' but we don't want to define this in the header file. this.PackNodes = ImVector() this.Rects = ImVector() - this.RectsIndex = ImVector() - this.TempBuffer = ImVector() - this.RectsIndexFreeListStart = -1 - this.RectsPackedCount = 0 - this.RectsPackedSurface = 0 + this.RectsIndex = ImVector() -- ImFontAtlasRectId -> index into Rects[] + this.TempBuffer = ImVector() -- Misc scratch buffer + this.RectsIndexFreeListStart = -1 -- First unused entry + this.RectsPackedCount = 0 -- Number of packed rectangles. + this.RectsPackedSurface = 0 -- Number of packed pixels. Used when compacting to heuristically find the ideal texture size. this.RectsDiscardedCount = 0 this.RectsDiscardedSurface = 0 - this.FrameCount = -1 - this.MaxRectSize = ImVec2() - this.MaxRectBounds = ImVec2() - this.LockDisableResize = false - this.PreloadedAllGlyphsRanges = false + this.FrameCount = -1 -- Current frame count + this.MaxRectSize = ImVec2() -- Largest rectangle to pack (de-facto used as a "minimum texture size") + this.MaxRectBounds = ImVec2() -- Bottom-right most used pixels + this.LockDisableResize = false -- Disable resizing texture + this.PreloadedAllGlyphsRanges = false -- Set when missing ImGuiBackendFlags.RendererHasTextures features forces atlas to preload everything. + -- Cache of all ImFontBaked this.BakedPool = ImVector() -- ImStableVector - this.BakedMap = {} + this.BakedMap = {} -- BakedId --> ImFontBaked this.BakedDiscardedCount = 0 - this.PackIdMouseCursors = -1 + -- Custom rectangle identifiers + this.PackIdMouseCursors = -1 -- White pixel + mouse cursors. Also happen to be fallback in case of packing failure. this.PackIdLinesTexData = -1 return this @@ -34926,8 +39960,8 @@ end --- @class ImFontStackData --- @field Font ImFont ---- @field FontSizeBeforeScaling float ---- @field FontSizeAfterScaling float +--- @field FontSizeBeforeScaling float # ~~ style.FontSizeBase +--- @field FontSizeAfterScaling float # ~~ g.FontSize --- @return ImFontStackData --- @param font ImFont @@ -34937,14 +39971,18 @@ end function ImFontStackData(font, font_size_before_scaling, font_size_after_scaling) return { Font = font, - FontSizeBeforeScaling = font_size_before_scaling, - FontSizeAfterScaling = font_size_after_scaling + FontSizeBeforeScaling = font_size_before_scaling, -- ~~ style.FontSizeBase + FontSizeAfterScaling = font_size_after_scaling -- ~~ g.FontSize } end +------------------------------------------------------------------------------- +-- [SECTION] Style support +------------------------------------------------------------------------------- + --- `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers! --- @class ImGuiStyleVarInfo ---- @field Count ImU32 +--- @field Count ImU32 # 1+ --- @field DataType ImGuiDataType --- @field Key string # key in parent structure. Note that the cpp Dear ImGui uses `ImU32 Offset`! @@ -34957,6 +39995,7 @@ function ImGuiStyleVarInfo(count, data_type, key) return { Count = count, DataType = data_type, Key = key } end +-- Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. --- @class ImGuiStyleMod --- @field VarIdx ImGuiStyleVar --- @field BackupVal table @@ -34976,36 +40015,42 @@ function ImGuiStyleMod(idx, v) return this end ---- Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo() +------------------------------------------------------------------------------- +-- [SECTION] Data types support +------------------------------------------------------------------------------- + +-- Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). --- @class ImGuiDataTypeInfo --- @field Size size_t # Size in bytes --- @field Name string # Short descriptive name for the type, for debugging --- @field PrintFmt string # Default printf format for the type --- @field ScanFmt string # Default scanf format for the type +-- Status storage for the last submitted item --- @class ImGuiLastItemData --- @field ID ImGuiID ---- @field ItemFlags ImGuiItemFlags ---- @field StatusFlags ImGuiItemStatusFlags ---- @field Rect ImRect ---- @field NavRect ImRect ---- @field DisplayRect ImRect ---- @field ClipRect ImRect ---- @field Shortcut ImGuiKeyChord +--- @field ItemFlags ImGuiItemFlags # See ImGuiItemFlags (called 'InFlags' before v1.91.4). +--- @field StatusFlags ImGuiItemStatusFlags # See ImGuiItemStatusFlags +--- @field Rect ImRect # Full rectangle +--- @field NavRect ImRect # Navigation scoring rectangle (not displayed) +--- @field DisplayRect ImRect # Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasDisplayRect) is set. +--- @field ClipRect ImRect # Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasClipRect) is set.. +--- @field Shortcut ImGuiKeyChord # Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasShortcut) is set.. --- @return ImGuiLastItemData --- @nodiscard function ImGuiLastItemData() return { ID = 0, - ItemFlags = 0, - StatusFlags = 0, - Rect = ImRect(), - NavRect = ImRect(), + ItemFlags = 0, -- See ImGuiItemFlags (called 'InFlags' before v1.91.4). + StatusFlags = 0, -- See ImGuiItemStatusFlags + Rect = ImRect(), -- Full rectangle + NavRect = ImRect(), -- Navigation scoring rectangle (not displayed) - DisplayRect = ImRect(), - ClipRect = ImRect(), - Shortcut = 0 + -- Rarely used fields are not explicitly cleared, only valid when the corresponding ImGuiItemStatusFlags are set. + DisplayRect = ImRect(), -- Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasDisplayRect) is set. + ClipRect = ImRect(), -- Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasClipRect) is set.. + Shortcut = 0 -- Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasShortcut) is set.. } end @@ -35022,6 +40067,10 @@ function ImGuiLastItemData_Copy(dest, src) dest.Shortcut = src.Shortcut end +-- Store data emitted by TreeNode() for usage by TreePop() +-- - 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. --- @class ImGuiTreeNodeStackData --- @field ID ImGuiID --- @field TreeFlags ImGuiTreeNodeFlags @@ -35037,14 +40086,15 @@ local function ImGuiTreeNodeStackData() return { ID = nil, TreeFlags = nil, - ItemFlags = nil, - NavRect = ImRect(), + ItemFlags = nil, -- Used for nav landing + NavRect = ImRect(), -- Used for nav landing DrawLinesX1 = nil, DrawLinesToNodesY2 = nil, DrawLinesTableColumn = nil } end +-- Storage for SetNextItem** functions --- @class ImGuiNextItemData --- @field HasFlags ImGuiNextItemDataFlags --- @field ItemFlagsSet ImGuiItemFlags @@ -35061,6 +40111,7 @@ end local IMGUI_NEXT_ITEM_DATA = {} IMGUI_NEXT_ITEM_DATA.__index = IMGUI_NEXT_ITEM_DATA +-- Also cleared manually by ItemAdd()! function IMGUI_NEXT_ITEM_DATA:ClearFlags() self.HasFlags = ImGuiNextItemDataFlags.None self.ItemFlagsSet = ImGuiItemFlags.None @@ -35070,22 +40121,24 @@ end --- @nodiscard function ImGuiNextItemData() return setmetatable({ - HasFlags = 0, - ItemFlagsSet = 0, + HasFlags = 0, -- Called HasFlags instead of Flags to avoid mistaking this + ItemFlagsSet = 0, -- Currently only tested/used for ImGuiItemFlags.AllowOverlap and ImGuiItemFlags.HasSelectionUserData. - FocusScopeId = 0, - SelectionUserData = -1, - Width = 0.0, - Shortcut = 0, - ShortcutFlags = 0, - OpenVal = false, - OpenCond = 0, - RefVal = 0, - StorageId = 0, - ColorMarker = 0 + -- Members below are NOT cleared by ItemAdd() meaning they are still valid during e.g. NavProcessItem(). Always rely on HasFlags. + FocusScopeId = 0, -- Set by SetNextItemSelectionUserData() + SelectionUserData = -1, -- Set by SetNextItemSelectionUserData() (note that nil/0 is a valid value, we use -1 == ImGuiSelectionUserData_Invalid to mark invalid values) + Width = 0.0, -- Set by SetNextItemWidth() + Shortcut = 0, -- Set by SetNextItemShortcut() + ShortcutFlags = 0, -- Set by SetNextItemShortcut() + OpenVal = false, -- Set by SetNextItemOpen() + OpenCond = 0, -- Set by SetNextItemOpen() + RefVal = 0, -- Not exposed yet, for ImGuiInputTextFlags.ParseEmptyAsRefVal + StorageId = 0, -- Set by SetNextItemStorageID() + ColorMarker = 0 -- Set by SetNextItemColorMarker(). Not exposed yet, supported by DragScalar,SliderScalar and for ImGuiSliderFlags.ColorMarkers. }, IMGUI_NEXT_ITEM_DATA) end +-- Storage for SetNexWindow** functions --- @class ImGuiNextWindowData --- @field HasFlags ImGuiNextWindowDataFlags --- @field PosCond ImGuiCond @@ -35118,6 +40171,7 @@ function ImGuiNextWindowData() return setmetatable({ HasFlags = 0, + -- Members below are NOT cleared. Always rely on HasFlags. PosCond = 0, SizeCond = 0, CollapsedCond = 0, @@ -35128,9 +40182,9 @@ function ImGuiNextWindowData() ScrollVal = ImVec2(), WindowFlags = nil, ChildFlags = nil, - WindowFlagsSet = 0, + WindowFlagsSet = 0, -- Flags to set. Use SetNextWindowFlags()! WindowFlagsClear = 0, - ChildFlagsSet = 0, + ChildFlagsSet = 0, -- Flags to set. Use SetNextWindowChildFlags(). ChildFlagsClear = 0, ViewportId = 0, DockId = 0, @@ -35141,8 +40195,8 @@ function ImGuiNextWindowData() SizeConstraintRect = nil, SizeCallback = nil, SizeCallbackUserData = nil, - BgAlphaVal = nil, - MenuBarOffsetMinVal = ImVec2(), + BgAlphaVal = nil, -- Override background alpha + MenuBarOffsetMinVal = ImVec2(), -- (Always on) This is not exposed publicly, so we don't clear it and it doesn't have a corresponding flag (could we? for consistency?) RefreshFlagsVal = nil, CacheKeySet = false, -- [Port] SetNextWindowCached() CacheKeyVal = nil @@ -35152,7 +40206,7 @@ end --- @enum ImGuiWindowBgClickFlags ImGuiWindowBgClickFlags = { None = 0, - Move = bitLShift(1, 0), + Move = bitLShift(1, 0), -- Click on bg/void + drag to move window. Cleared by default when using io.ConfigWindowsMoveFromTitleBarOnly. } --- @enum ImGuiNextWindowDataFlags @@ -35174,6 +40228,8 @@ ImGuiNextWindowDataFlags = { HasWindowClass = bitLShift(1, 13) } +-- FIXME: this is in development, not exposed/functional as a generic feature yet. +-- Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2 --- @enum ImGuiLayoutType ImGuiLayoutType = { @@ -35187,7 +40243,7 @@ ImGuiSeparatorFlags = None = 0, Horizontal = bitLShift(1, 0), -- Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar Vertical = bitLShift(1, 1), - SpanAllColumns = bitLShift(1, 2) -- Make separator cover all columns of a legacy Columns() set + SpanAllColumns = bitLShift(1, 2) -- Make separator cover all columns of a legacy Columns() set. } --- @class ImGuiStyle @@ -35199,111 +40255,114 @@ MT.ImGuiStyle.__index = MT.ImGuiStyle function ImGuiStyle() --- @type ImGuiStyle local this = { - FontSizeBase = 0.0, - FontScaleMain = 1.0, - FontScaleDpi = 1.0, + FontSizeBase = 0.0, -- Will default to io.Fonts.Fonts[0] on first frame. + FontScaleMain = 1.0, -- Main scale factor. May be set by application once, or exposed to end-user. + FontScaleDpi = 1.0, -- Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. - Alpha = 1.0, - DisabledAlpha = 0.60, + Alpha = 1.0, -- Global alpha applies to everything in Dear ImGui. + DisabledAlpha = 0.60, -- Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. - FramePadding = ImVec2(4, 3), - FrameRounding = 0.0, - FrameBorderSize = 0.0, - WindowPadding = ImVec2(8, 8), + FramePadding = ImVec2(4, 3), -- Padding within a framed rectangle (used by most widgets) + FrameRounding = 0.0, -- Radius of frame corners rounding. Set to 0.0 to have rectangular frames (used by most widgets). + FrameBorderSize = 0.0, -- Thickness of border around frames. Generally set to 0.0 or 1.0. Other values not well tested. + WindowPadding = ImVec2(8, 8), -- Padding within a window - TouchExtraPadding = ImVec2(0, 0), - IndentSpacing = 21.0, + TouchExtraPadding = ImVec2(0, 0), -- Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + IndentSpacing = 21.0, -- Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). - WindowRounding = 0, - WindowBorderSize = 1, + WindowRounding = 0, -- Radius of window corners rounding. Set to 0.0 to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. + WindowBorderSize = 1, -- Thickness of border around windows. Generally set to 0.0 or 1.0. Other values not well tested. - ScrollbarSize = 14.0, - ScrollbarRounding = 9.0, - ScrollbarPadding = 2.0, - GrabMinSize = 12.0, - GrabRounding = 0.0, - ImageRounding = 0.0, - ImageBorderSize = 0.0, + ScrollbarSize = 14.0, -- Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarRounding = 9.0, -- Radius of grab corners rounding for scrollbar + ScrollbarPadding = 2.0, -- Padding of scrollbar grab within its frame (same for both axes) + GrabMinSize = 12.0, -- Minimum width/height of a grab box for slider/scrollbar + GrabRounding = 0.0, -- Radius of grabs corners rounding. Set to 0.0 to have rectangular slider grabs. + ImageRounding = 0.0, -- Rounding of Image() calls. + ImageBorderSize = 0.0, -- Thickness of border around Image() calls. - WindowBorderHoverPadding = 4.0, + WindowBorderHoverPadding = 4.0, -- 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. TreeLinesFlags = ImGuiTreeNodeFlags.DrawLinesNone, - TreeLinesSize = 1.0, - TreeLinesRounding = 0.0, - MenuItemRounding = 0.0, - SelectableRounding = 0.0, + TreeLinesSize = 1.0, -- Thickness of outlines when using ImGuiTreeNodeFlags.DrawLines. + TreeLinesRounding = 0.0, -- Radius of lines connecting child nodes to the vertical line. + MenuItemRounding = 0.0, -- Radius of MenuItem, BeginMenu rounding. + SelectableRounding = 0.0, -- Radius of selectable rounding. MODIFYING THIS IS DISCOURAGED. CONTIGUOUS SELECTIONS WILL NOT LOOK RIGHT. (#7589) - ColorMarkerSize = 3.0, - ColorButtonPosition = ImGuiDir.Right, + ColorMarkerSize = 3.0, -- Size of R/G/B/A color markers for ColorEdit4() and for Drags/Sliders when using ImGuiSliderFlags.ColorMarkers. + ColorButtonPosition = ImGuiDir.Right, -- Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir.Right. - InputTextCursorSize = 1.0, - SeparatorSize = 1.0, - SeparatorTextBorderSize = 3.0, - SeparatorTextAlign = ImVec2(0.0, 0.5), - SeparatorTextPadding = ImVec2(20.0, 3.0), + InputTextCursorSize = 1.0, -- Thickness of cursor/caret in InputText(). + SeparatorSize = 1.0, -- Thickness of border in Separator(). + SeparatorTextBorderSize = 3.0, -- Thickness of border in SeparatorText(). + SeparatorTextAlign = ImVec2(0.0, 0.5), -- Alignment of text within the separator. Defaults to (0.0, 0.5) (left aligned, center). + SeparatorTextPadding = ImVec2(20.0, 3.0), -- Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. - DisplaySafeAreaPadding = ImVec2(3, 3), - DisplayWindowPadding = ImVec2(19, 19), + 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. + 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. - AntiAliasedLines = true, - AntiAliasedLinesUseTex = true, - AntiAliasedFill = true, + -- Rendering & Tessellation + AntiAliasedLines = true, -- Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawListFlags.AntiAliasedLines in all draw-lists. + AntiAliasedLinesUseTex = true, -- Enable anti-aliased lines/borders using textures for legacy strokes. Require backend to render with bilinear filtering (NOT point/nearest filtering). + AntiAliasedFill = true, -- Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Used at the beginning of the frame to set ImDrawListFlags.AntiAliasedFill in all draw-lists. - CurveTessellationTol = 1.25, - CircleTessellationMaxError = 0.30, + CurveTessellationTol = 1.25, -- Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + CircleTessellationMaxError = 0.30, -- 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. - HoverStationaryDelay = 0.15, - HoverDelayShort = 0.15, - HoverDelayNormal = 0.40, + -- Behaviors + HoverStationaryDelay = 0.15, -- Delay for IsItemHovered(ImGuiHoveredFlags.Stationary). Time required to consider mouse stationary. + HoverDelayShort = 0.15, -- Delay for IsItemHovered(ImGuiHoveredFlags.DelayShort). Usually used along with HoverStationaryDelay. + HoverDelayNormal = 0.40, -- Delay for IsItemHovered(ImGuiHoveredFlags.DelayNormal). " Colors = {}, - ButtonTextAlign = ImVec2(0.5, 0.5), - SelectableTextAlign = ImVec2(0.0, 0.0), + ButtonTextAlign = ImVec2(0.5, 0.5), -- Alignment of button text when button is larger than text. + SelectableTextAlign = ImVec2(0.0, 0.0), -- Alignment of selectable text. Defaults to (0.0, 0.0) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. - WindowMinSize = ImVec2(32, 32), - WindowTitleAlign = ImVec2(0.0, 0.5), - WindowMenuButtonPosition = ImGuiDir.Left, - ChildRounding = 0.0, - ChildBorderSize = 1.0, - PopupRounding = 0.0, - PopupBorderSize = 1.0, + WindowMinSize = ImVec2(32, 32), -- Minimum window size + WindowTitleAlign = ImVec2(0.0, 0.5), -- Alignment for title bar text + WindowMenuButtonPosition = ImGuiDir.Left, -- Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir.Left. + ChildRounding = 0.0, -- Radius of child window corners rounding. Set to 0.0 to have rectangular child windows + ChildBorderSize = 1.0, -- Thickness of border around child windows. Generally set to 0.0 or 1.0. Other values not well tested. + PopupRounding = 0.0, -- Radius of popup window corners rounding. Set to 0.0 to have rectangular child windows + PopupBorderSize = 1.0, -- Thickness of border around popup or tooltip windows. Generally set to 0.0 or 1.0. Other values not well tested. - DockingSeparatorSize = 2.0, - DockingNodeHasCloseButton = true, - MouseCursorScale = 1.0, + DockingSeparatorSize = 2.0, -- Thickness of resizing border between docked windows + DockingNodeHasCloseButton = true, -- Docking nodes have their own CloseButton() to close all docked windows. + MouseCursorScale = 1.0, -- Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. - ItemSpacing = ImVec2(8, 4), - ItemInnerSpacing = ImVec2(4, 4), - CellPadding = ImVec2(4, 2), + ItemSpacing = ImVec2(8, 4), -- Horizontal and vertical spacing between widgets/lines + ItemInnerSpacing = ImVec2(4, 4), -- Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + CellPadding = ImVec2(4, 2), -- Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows. - ColumnsMinSpacing = 6.0, + ColumnsMinSpacing = 6.0, -- Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). - LogSliderDeadzone = 4.0, + LogSliderDeadzone = 4.0, -- The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. - TabRounding = 5.0, - TabBorderSize = 0.0, - TabMinWidthBase = 1.0, - TabMinWidthShrink = 80.0, - TabCloseButtonMinWidthSelected = -1.0, - TabCloseButtonMinWidthUnselected = 0.0, - TabBarBorderSize = 1.0, - TabBarOverlineSize = 1.0, - TableAngledHeadersAngle = 35.0 * (IM_PI / 180.0), - TableAngledHeadersTextAlign = ImVec2(0.5, 0.0), + TabRounding = 5.0, -- Radius of upper corners of a tab. Set to 0.0 to have rectangular tabs. + TabBorderSize = 0.0, -- Thickness of border around tabs. + TabMinWidthBase = 1.0, -- Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected. + TabMinWidthShrink = 80.0, -- Minimum tab width after shrinking, when using ImGuiTabBarFlags.FittingPolicyMixed policy. FLT_MAX: never shrink, will behave like ImGuiTabBarFlags.FittingPolicyScroll. + TabCloseButtonMinWidthSelected = -1.0, -- -1: always visible. 0.0: visible when hovered. >0.0: visible when hovered if minimum width. + TabCloseButtonMinWidthUnselected = 0.0, -- -1: always visible. 0.0: visible when hovered. >0.0: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. + TabBarBorderSize = 1.0, -- Thickness of tab-bar separator, which takes on the tab active color to denote focus. + TabBarOverlineSize = 1.0, -- Thickness of tab-bar overline, which highlights the selected tab-bar. + TableAngledHeadersAngle = 35.0 * (IM_PI / 180.0), -- Angle of angled headers (supported values range from -50 degrees to +50 degrees). + TableAngledHeadersTextAlign = ImVec2(0.5, 0.0), -- Alignment of angled headers within the cell - DragDropTargetRounding = 0.0, - DragDropTargetBorderSize = 2.0, - DragDropTargetPadding = 3.0, + DragDropTargetRounding = 0.0, -- Radius of the drag and drop target frame. + DragDropTargetBorderSize = 2.0, -- Thickness of the drag and drop target border. + DragDropTargetPadding = 3.0, -- Size to expand the drag and drop target from actual target item size. - HoverFlagsForTooltipMouse = bitOr(ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.AllowWhenDisabled), - HoverFlagsForTooltipNav = bitOr(ImGuiHoveredFlags.NoSharedDelay, ImGuiHoveredFlags.DelayNormal, ImGuiHoveredFlags.AllowWhenDisabled), + HoverFlagsForTooltipMouse = bitOr(ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.AllowWhenDisabled), -- Default flags when using IsItemHovered(ImGuiHoveredFlags.ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. + HoverFlagsForTooltipNav = bitOr(ImGuiHoveredFlags.NoSharedDelay, ImGuiHoveredFlags.DelayNormal, ImGuiHoveredFlags.AllowWhenDisabled), -- Default flags when using IsItemHovered(ImGuiHoveredFlags.ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. -- [Internal] _MainScale = 1.0, _NextFrameFontSizeBase = 0.0 } + -- Default theme ImGui.StyleColorsDark(this) setmetatable(this, MT.ImGuiStyle) @@ -35311,6 +40370,7 @@ function ImGuiStyle() return this end +-- Storage for each window pushed into the stack. --- @class ImGuiWindowStackData --- @return ImGuiWindowStackData @@ -35319,12 +40379,13 @@ function ImGuiWindowStackData() return { Window = nil, ParentLastItemDataBackup = ImGuiLastItemData(), - StackSizesInBegin = nil, - DisabledOverrideReenable = nil, + StackSizesInBegin = nil, -- Store size of various stacks for asserting + DisabledOverrideReenable = nil, -- Non-child window override disabled flag DisabledOverrideReenableAlphaBackup = nil } end +-- Storage data for BeginComboPreview()/EndComboPreview() --- @class ImGuiComboPreviewData --- @field PreviewRect ImRect --- @field BackupCursorPos ImVec2 @@ -35350,10 +40411,12 @@ end --- @alias ImStbTexteditState STB_TexteditState +-- Internal state of the currently focused/edited text input box +-- For a given item ID, access with ImGui.GetInputTextState() --- @class ImGuiInputTextState --- @field Ctx ImGuiContext # parent UI context (needs to be set explicitly by parent) --- @field Stb ImStbTexteditState # State for stb_textedit.lua ---- @field Flags ImGuiInputTextFlags +--- @field Flags ImGuiInputTextFlags # copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags.Password is set. --- @field ID ImGuiID # widget id owning the text state --- @field TextLen int # UTF-8 length of the string in TextA (in bytes) --- @field TextSrc ImStringBuffer # == TextA.Data unless read-only, in which case == buf passed to InputText(). For _ReadOnly fields, pointer will be null outside the InputText() call @@ -35375,33 +40438,35 @@ MT.ImGuiInputTextState.__index = MT.ImGuiInputTextState local function ImGuiInputTextState() local this = { - Ctx = nil, - Stb = STB_TexteditState(), -- FIXME: no global! - Flags = 0, - ID = 0, + Ctx = nil, -- parent UI context (needs to be set explicitly by parent). + Stb = STB_TexteditState(), -- FIXME: no global! -- State for stb_textedit.h + Flags = 0, -- copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags.Password is set. + ID = 0, -- widget id owning the text state - TextLen = 0, - TextSrc = nil, - TextA = ImVector(), - TextToRevertTo = ImVector(), - CallbackTextBackup = ImVector(), + TextLen = 0, -- UTF-8 length of the string in TextA (in bytes) + TextSrc = nil, -- == TextA.Data unless read-only, in which case == buf passed to InputText(). For _ReadOnly fields, pointer will be null outside the InputText() call. + TextA = ImVector(), -- main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1). + TextToRevertTo = ImVector(), -- value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered) + CallbackTextBackup = ImVector(), -- temporary storage for callback to support automatic reconcile of undo-stack - BufCapacity = 0, - Scroll = ImVec2(), - LineCount = 0, - WrapWidth = 0.0, + BufCapacity = 0, -- end-user buffer capacity (include zero terminator) + Scroll = ImVec2(), -- horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) + LineCount = 0, -- last line count (solely for debugging) + WrapWidth = 0.0, -- word-wrapping width - CursorAnim = 0.0, - CursorFollow = false, - CursorCenterY = false, - SelectedAllMouseLock = false, - EditedBefore = false, - EditedThisFrame = false, + CursorAnim = 0.0, -- timer for cursor blink, reset on every user action so the cursor reappears immediately + CursorFollow = false, -- set when we want scrolling to follow the current cursor position (not always!) + CursorCenterY = false, -- set when we want scrolling to be centered over the cursor position (while resizing a word-wrapping field) + SelectedAllMouseLock = false, -- after a double-click to select all, we ignore further mouse drags to update selection + EditedBefore = false, -- edited since activated + EditedThisFrame = false, -- edited this frame } return setmetatable(this, MT.ImGuiInputTextState) end +-- Internal temporary state for deactivating InputText() instances. +-- Store as part of ImGuiDeactivatedItemData? --- @class ImGuiInputTextDeactivatedState --- @field ID ImGuiID # widget id owning the text state (which just got deactivated) --- @field ElapseFrame int @@ -35419,19 +40484,20 @@ end --- @nodiscard local function ImGuiInputTextDeactivatedState() return setmetatable({ - ID = 0, + ID = 0, -- widget id owning the text state (which just got deactivated) ElapseFrame = 0, - TextA = ImVector() + TextA = ImVector() -- text buffer }, IMGUI_INPUT_TEXT_DEACTIVATED_STATE) end --- @alias ImGuiKeyRoutingIndex ImS16 +-- Routing table entry (sizeof() == 16 bytes) --- @class ImGuiKeyRoutingData --- @field NextEntryIndex ImGuiKeyRoutingIndex ---- @field Mods ImU16 ---- @field RoutingCurrScore ImU16 ---- @field RoutingNextScore ImU16 +--- @field Mods ImU16 # Technically we'd only need 4-bits but for simplify we store ImGuiMod_ values which need 16-bits. +--- @field RoutingCurrScore ImU16 # [DEBUG] For debug display +--- @field RoutingNextScore ImU16 # Lower is better (0: perfect score) --- @field RoutingCurr ImGuiID --- @field RoutingNext ImGuiID @@ -35440,18 +40506,20 @@ end function ImGuiKeyRoutingData() return { NextEntryIndex = -1, - Mods = 0, - RoutingCurrScore = 0, - RoutingNextScore = 0, + Mods = 0, -- Technically we'd only need 4-bits but for simplify we store ImGuiMod_ values which need 16-bits. + RoutingCurrScore = 0, -- [DEBUG] For debug display + RoutingNextScore = 0, -- Lower is better (0: perfect score) RoutingCurr = ImGuiKeyOwner_NoOwner, RoutingNext = ImGuiKeyOwner_NoOwner } end +-- Routing table: maintain a desired owner for each possible key-chord (key + mods), and setup owner in NewFrame() when mods are matching. +-- Stored in main context (1 instance) --- @class ImGuiKeyRoutingTable ---- @field Index ImGuiKeyRoutingIndex[] +--- @field Index ImGuiKeyRoutingIndex[] # Index of first entry in Entries[] --- @field Entries ImVector ---- @field EntriesNext ImVector +--- @field EntriesNext ImVector # Double-buffer to avoid reallocation (could use a shared buffer) local _ImGuiKeyRoutingTable = {} _ImGuiKeyRoutingTable.__index = _ImGuiKeyRoutingTable @@ -35464,9 +40532,9 @@ end --- @return ImGuiKeyRoutingTable local function ImGuiKeyRoutingTable() local this = setmetatable({ - Index = {}, + Index = {}, -- Index of first entry in Entries[] Entries = ImVector(), - EntriesNext = ImVector() + EntriesNext = ImVector() -- Double-buffer to avoid reallocation (could use a shared buffer) }, _ImGuiKeyRoutingTable) this:Clear() @@ -35474,9 +40542,11 @@ local function ImGuiKeyRoutingTable() return this end +-- Helper: ImGuiTextIndex +-- Maintain a line index for a text buffer. This is a strong candidate to be moved into the public API. --- @class ImGuiTextIndex --- @field Offsets ImVector ---- @field EndOffset int +--- @field EndOffset int # Because we don't own text buffer we need to maintain EndOffset (may bake in LineOffsets?) local IMGUI_TEXT_INDEX = {} IMGUI_TEXT_INDEX.__index = IMGUI_TEXT_INDEX @@ -35506,18 +40576,18 @@ local function ImGuiDebugAllocEntry() end --- @class ImGuiDebugAllocInfo ---- @field TotalAllocCount int +--- @field TotalAllocCount int # Number of call to MemAlloc(). --- @field TotalFreeCount int ---- @field LastEntriesIdx ImS16 ---- @field LastEntriesBuf ImGuiDebugAllocEntry[] +--- @field LastEntriesIdx ImS16 # Current index in buffer +--- @field LastEntriesBuf ImGuiDebugAllocEntry[] # Track last 6 frames that had allocations --- @return ImGuiDebugAllocInfo local function ImGuiDebugAllocInfo() local this = { - TotalAllocCount = 0, + TotalAllocCount = 0, -- Number of call to MemAlloc(). TotalFreeCount = 0, - LastEntriesIdx = 1, - LastEntriesBuf = {nil, nil, nil, nil, nil, nil}, + LastEntriesIdx = 1, -- Current index in buffer + LastEntriesBuf = {nil, nil, nil, nil, nil, nil}, -- Track last 6 frames that had allocations } for i = 1, 6 do @@ -35538,16 +40608,17 @@ local function ImGuiMetricsConfig() } end +-- Storage for navigation query/results --- @class ImGuiNavItemData ---- @field Window ImGuiWindow? ---- @field ID ImGuiID ---- @field FocusScopeId ImGuiID ---- @field RectRel ImRect ---- @field ItemFlags ImGuiItemFlags ---- @field SelectionUserData ImGuiSelectionUserData ---- @field DistBox float ---- @field DistCenter float ---- @field DistAxial float +--- @field Window ImGuiWindow? # Init,Move -- Best candidate window (result->ItemWindow->RootWindowForNav == request->Window) +--- @field ID ImGuiID # Init,Move -- Best candidate item ID +--- @field FocusScopeId ImGuiID # Init,Move -- Best candidate focus scope ID +--- @field RectRel ImRect # Init,Move -- Best candidate bounding box in window relative space +--- @field ItemFlags ImGuiItemFlags # ????,Move -- Best candidate item flags +--- @field SelectionUserData ImGuiSelectionUserData # I+Mov -- Best candidate SetNextItemSelectionUserData() value. Valid if (ItemFlags & ImGuiItemFlags.HasSelectionUserData) +--- @field DistBox float # Move -- Best candidate box distance to current NavId +--- @field DistCenter float # Move -- Best candidate center distance to current NavId +--- @field DistAxial float # Move -- Best candidate axial distance to current NavId local IMGUI_NAV_ITEM_DATA = {} IMGUI_NAV_ITEM_DATA.__index = IMGUI_NAV_ITEM_DATA @@ -35570,10 +40641,14 @@ local function ImGuiNavItemData() return this end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiContext (main Dear ImGui context) +------------------------------------------------------------------------------- + --- @class ImGuiContext --- @field Initialized bool ---- @field WithinFrameScope bool ---- @field WithinFrameScopeWithImplicitWindow bool +--- @field WithinFrameScope bool # Set by NewFrame(), cleared by EndFrame() +--- @field WithinFrameScopeWithImplicitWindow bool # Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed --- @field FrameCount int --- @field FrameCountEnded int --- @field CurrentWindow ImGuiWindow @@ -35633,49 +40708,54 @@ end --- @field DebugAllocInfo ImGuiDebugAllocInfo --- @field TempBuffer ImVector ----------------------------------------------------------------- --- [SECTION] Tab bar, Tab item support (public flags from imgui.h + private extensions) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Tab bar, Tab item support +-- PORT: public flags from imgui.h + private extensions +------------------------------------------------------------------------------- +-- Flags for ImGui.BeginTabBar() --- @enum ImGuiTabBarFlags ImGuiTabBarFlags = { None = 0, - Reorderable = bitLShift(1, 0), - AutoSelectNewTabs = bitLShift(1, 1), - TabListPopupButton = bitLShift(1, 2), - NoCloseWithMiddleMouseButton = bitLShift(1, 3), - NoTabListScrollingButtons = bitLShift(1, 4), - NoTooltip = bitLShift(1, 5), - DrawSelectedOverline = bitLShift(1, 6), - FittingPolicyMixed = bitLShift(1, 7), - FittingPolicyShrink = bitLShift(1, 8), - FittingPolicyScroll = bitLShift(1, 9), + Reorderable = bitLShift(1, 0), -- Allow manually dragging tabs to re-order them + New tabs are appended at the end of list + AutoSelectNewTabs = bitLShift(1, 1), -- Automatically select new tabs when they appear + TabListPopupButton = bitLShift(1, 2), -- Disable buttons to open the tab list popup + NoCloseWithMiddleMouseButton = bitLShift(1, 3), -- Disable behavior of closing tabs (that are submitted with p_open ~= nil) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) p_open = false. + NoTabListScrollingButtons = bitLShift(1, 4), -- Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags.FittingPolicyScroll) + NoTooltip = bitLShift(1, 5), -- Disable tooltips when hovering a tab + DrawSelectedOverline = bitLShift(1, 6), -- Draw selected overline markers over selected tab + + -- Fitting/Resize policy + FittingPolicyMixed = bitLShift(1, 7), -- Shrink down tabs when they don't fit, until width is style.TabMinWidthShrink, then enable scrolling. Setting TabMinWidthShrink to FLT_MAX makes this behave like ImGuiTabBarFlags.FittingPolicyScroll. + FittingPolicyShrink = bitLShift(1, 8), -- Shrink down tabs when they don't fit + FittingPolicyScroll = bitLShift(1, 9), -- Enable scrolling buttons when tabs don't fit -- Private - DockNode = bitLShift(1, 20), + DockNode = bitLShift(1, 20), -- Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around] IsFocused = bitLShift(1, 21), - SaveSettings = bitLShift(1, 22), + SaveSettings = bitLShift(1, 22), -- FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs } ImGuiTabBarFlags.FittingPolicyMask_ = bitOr(ImGuiTabBarFlags.FittingPolicyMixed, ImGuiTabBarFlags.FittingPolicyShrink, ImGuiTabBarFlags.FittingPolicyScroll) ImGuiTabBarFlags.FittingPolicyDefault_ = ImGuiTabBarFlags.FittingPolicyMixed -ImGuiTabBarFlags.FittingPolicyResizeDown = ImGuiTabBarFlags.FittingPolicyShrink +ImGuiTabBarFlags.FittingPolicyResizeDown = ImGuiTabBarFlags.FittingPolicyShrink -- Renamed in 1.92.2 +-- Flags for ImGui.BeginTabItem() --- @enum ImGuiTabItemFlags ImGuiTabItemFlags = { None = 0, - UnsavedDocument = bitLShift(1, 0), - SetSelected = bitLShift(1, 1), - NoCloseWithMiddleMouseButton = bitLShift(1, 2), - NoPushId = bitLShift(1, 3), - NoTooltip = bitLShift(1, 4), - NoReorder = bitLShift(1, 5), - Leading = bitLShift(1, 6), - Trailing = bitLShift(1, 7), - NoAssumedClosure = bitLShift(1, 8), + UnsavedDocument = bitLShift(1, 0), -- Display a dot next to the title + set ImGuiTabItemFlags.NoAssumedClosure. + SetSelected = bitLShift(1, 1), -- Trigger flag to programmatically make the tab selected when calling BeginTabItem() + NoCloseWithMiddleMouseButton = bitLShift(1, 2), -- Disable behavior of closing tabs (that are submitted with p_open ~= nil) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) p_open = false. + NoPushId = bitLShift(1, 3), -- Don't call PushID()/PopID() on BeginTabItem()/EndTabItem() + NoTooltip = bitLShift(1, 4), -- Disable tooltip for the given tab + NoReorder = bitLShift(1, 5), -- Disable reordering this tab or having another tab cross over this tab + Leading = bitLShift(1, 6), -- Enforce the tab position to the left of the tab bar (after the tab list popup button) + Trailing = bitLShift(1, 7), -- Enforce the tab position to the right of the tab bar (before the scrolling buttons) + NoAssumedClosure = bitLShift(1, 8), -- Tab is selected when trying to close + closure is not immediately assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. -- Private - NoCloseButton = bitLShift(1, 20), - Button = bitLShift(1, 21), - Invisible = bitLShift(1, 22), - Unsorted = bitLShift(1, 23), + NoCloseButton = bitLShift(1, 20), -- Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) + Button = bitLShift(1, 21), -- Used by TabItemButton, change the tab item behavior to mimic a button + Invisible = bitLShift(1, 22), -- To reserve space e.g. with ImGuiTabItemFlags.Leading + Unsorted = bitLShift(1, 23), -- [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window. } ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing) @@ -35684,13 +40764,17 @@ ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFl --- @return ImGuiTabItem function ImGuiTabItem() return { - ID = 0, Flags = 0, Window = nil, - LastFrameVisible = -1, LastFrameSelected = -1, + ID = 0, Flags = 0, Window = nil, -- Window: When TabItem is part of a DockNode's TabBar, we hold on to a window. + LastFrameVisible = -1, LastFrameSelected = -1, -- LastFrameSelected: This allows us to infer an ordered list of the last activated tabs with little maintenance + -- Offset: Position relative to beginning of tab bar + -- Width: Width currently displayed + -- ContentWidth: Width of label + padding, stored during BeginTabItem() call (misnamed as "Content" would normally imply width of label only) + -- RequestedWidth: Width optionally requested by caller, -1.0 is unused Offset = 0.0, Width = 0.0, ContentWidth = 0.0, RequestedWidth = -1.0, NameOffset = -1, Name = nil, - BeginOrder = -1, -- 0-based - IndexDuringLayout = -1, -- 0-based - WantClose = false, + BeginOrder = -1, -- 0-based -- BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags.Reorderable + IndexDuringLayout = -1, -- 0-based -- Index only used during TabBarLayout(). Tabs gets reordered so 'Tabs[n].IndexDuringLayout == n' but may mismatch during additions. + WantClose = false, -- Marked as closed by SetTabItemClosed() } end @@ -35699,19 +40783,24 @@ end --- @return ImGuiTabBar function ImGuiTabBar() return { - Window = nil, Tabs = ImVector(), Flags = 0, ID = 0, + Window = nil, Tabs = ImVector(), Flags = 0, ID = 0, -- ID: Zero for tab-bars used by docking + -- SelectedTabId: Selected tab/window + -- NextSelectedTabId: Next selected tab/window. Will also trigger a scrolling animation + -- VisibleTabId: Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) SelectedTabId = 0, NextSelectedTabId = 0, NextScrollToTabId = 0, VisibleTabId = 0, CurrFrameVisible = -1, PrevFrameVisible = -1, - BarRect = ImRect(), BarRectPrevWidth = 0.0, - CurrTabsContentsHeight = 0.0, PrevTabsContentsHeight = 0.0, + BarRect = ImRect(), BarRectPrevWidth = 0.0, -- BarRectPrevWidth: Backup of previous width. When width change we enforce keep horizontal scroll on focused tab. + CurrTabsContentsHeight = 0.0, PrevTabsContentsHeight = 0.0, -- PrevTabsContentsHeight: Record the height of contents submitted below the tab bar + -- WidthAllTabs: Actual width of all tabs (locked during layout) + -- WidthAllTabsIdeal: Ideal width if all tabs were visible and not clipped WidthAllTabs = 0.0, WidthAllTabsIdeal = 0.0, ScrollingAnim = 0.0, ScrollingTarget = 0.0, ScrollingTargetDistToVisibility = 0.0, ScrollingSpeed = 0.0, ScrollingRectMinX = 0.0, ScrollingRectMaxX = 0.0, SeparatorMinX = 0.0, SeparatorMaxX = 0.0, ReorderRequestTabId = 0, ReorderRequestOffset = 0, BeginCount = 0, - WantLayout = false, VisibleTabWasSubmitted = false, TabsAddedNew = false, ScrollButtonEnabled = false, - TabsActiveCount = 0, - LastTabItemIdx = -1, -- 0-based - ItemSpacingY = 0.0, FramePadding = ImVec2(), BackupCursorPos = ImVec2(), + WantLayout = false, VisibleTabWasSubmitted = false, TabsAddedNew = false, ScrollButtonEnabled = false, -- TabsAddedNew: Set to true when a new tab item or button has been added to the tab bar during last frame + TabsActiveCount = 0, -- Number of tabs submitted this frame. + LastTabItemIdx = -1, -- 0-based -- Index of last BeginTabItem() tab for use by EndTabItem() + ItemSpacingY = 0.0, FramePadding = ImVec2(), BackupCursorPos = ImVec2(), -- FramePadding: style.FramePadding locked at the time of BeginTabBar() } end @@ -35724,86 +40813,86 @@ function ImGuiShrinkWidthItem() return { Index = 0, Width = 0.0, InitialWidth = function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this structure local this = { Style = ImGuiStyle(), - ColorStack = ImVector(), - StyleVarStack = ImVector(), + ColorStack = ImVector(), -- Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() + StyleVarStack = ImVector(), -- Stack for PushStyleVar()/PopStyleVar() - inherited by Begin() Config = nil, Initialized = false, - WithinFrameScope = false, - WithinFrameScopeWithImplicitWindow = false, + WithinFrameScope = false, -- Set by NewFrame(), cleared by EndFrame() + WithinFrameScopeWithImplicitWindow = false, -- Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed Windows = ImVector(), -- Windows sorted in display order, back to front WindowsById = {}, -- Map window's ID to window ref - WindowsBorderHoverPadding = 0, + WindowsBorderHoverPadding = 0, -- 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. - WindowsActiveCount = 0, + WindowsActiveCount = 0, -- Number of unique windows submitted by frame - WindowsTempSortBuffer = ImVector(), + WindowsTempSortBuffer = ImVector(), -- Temporary buffer used in EndFrame() to reorder windows so parents are kept before their child CurrentWindowStack = ImVector(), - CurrentWindow = nil, + CurrentWindow = nil, -- Window being drawn into - WindowsFocusOrder = ImVector(), + WindowsFocusOrder = ImVector(), -- Root windows, sorted in focus order, back to front. IO = ImGuiIO(), PlatformIO = ImGuiPlatformIO(), - ConfigFlagsCurrFrame = ImGuiConfigFlags.None, + ConfigFlagsCurrFrame = ImGuiConfigFlags.None, -- = g.IO.ConfigFlags at the time of NewFrame() ConfigFlagsLastFrame = ImGuiConfigFlags.None, MouseLastValidPos = ImVec2(), - KeysMayBeCharInput = ImBitArray(ImGuiKey.NamedKey_COUNT, -ImGuiKey.NamedKey_BEGIN), + KeysMayBeCharInput = ImBitArray(ImGuiKey.NamedKey_COUNT, -ImGuiKey.NamedKey_BEGIN), -- Lookup to tell if a key can emit char input, see IsKeyChordPotentiallyCharInput(). KeysOwnerData = {}, -- size = ImGuiKey.NamedKey_COUNT KeysRoutingTable = ImGuiKeyRoutingTable(), - InputEventsQueue = ImVector(), + InputEventsQueue = ImVector(), -- Input events which will be trickled/written into IO structure. InputEventsNextMouseSource = ImGuiMouseSource.Mouse, InputEventsNextEventId = 1, - MovingWindow = nil, + MovingWindow = nil, -- Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow.RootWindowDockTree. - WheelingWindow = nil, - WheelingWindowStartFrame = -1, WheelingWindowScrolledFrame = -1, + WheelingWindow = nil, -- Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. + WheelingWindowStartFrame = -1, WheelingWindowScrolledFrame = -1, -- This may be set one frame before WheelingWindow is ~= nil WheelingWindowReleaseTimer = 0.0, WheelingWindowRefMousePos = ImVec2(), WheelingWindowWheelRemainder = ImVec2(), WheelingAxisAvg = ImVec2(), - ActiveIdClickOffset = ImVec2(), + ActiveIdClickOffset = ImVec2(), -- Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) - HoveredWindow = nil, - HoveredWindowUnderMovingWindow = nil, - HoveredIdIsDisabled = false, + HoveredWindow = nil, -- Window the mouse is hovering. Will typically catch mouse inputs. + HoveredWindowUnderMovingWindow = nil, -- Hovered window ignoring MovingWindow. Only set if MovingWindow is set. + HoveredIdIsDisabled = false, -- At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. ActiveIdFromShortcut = false, AnyIdHasBeenEditedThisFrame = false, - ActiveId = 0, + ActiveId = 0, -- Active widget ActiveIdWindow = nil, ActiveIdMouseButton = -1, - ActiveIdIsJustActivated = false, + ActiveIdIsJustActivated = false, -- Set at the time of activation for one frame - ActiveIdWasSelected = false, ActiveIdWasSoleSelected = false, + ActiveIdWasSelected = false, ActiveIdWasSoleSelected = false, -- Active ID was selected at the time of activating LastActiveIdWasSelected = false, LastActiveIdWasSoleSelected = false, - ActiveIdNoClearOnFocusLoss = false, - ActiveIdHasBeenPressedBefore = false, + ActiveIdNoClearOnFocusLoss = false, -- Disable losing active id if the active id window gets unfocused. + ActiveIdHasBeenPressedBefore = false, -- Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. - ActiveIdIsAlive = nil, + ActiveIdIsAlive = nil, -- Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) ActiveIdPreviousFrame = 0, ActiveIdTimer = 0.0, - LastActiveId = 0, - LastActiveIdTimer = 0.0, + LastActiveId = 0, -- Store the last non-zero ActiveId, useful for animation. + LastActiveIdTimer = 0.0, -- Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. - ActiveIdUsingNavDirMask = 0x00, - ActiveIdUsingAllKeyboardKeys = false, + ActiveIdUsingNavDirMask = 0x00, -- Active widget will want to read those nav move requests (e.g. can activate a button and move away from it) + ActiveIdUsingAllKeyboardKeys = false, -- Active widget will want to read all keyboard keys inputs. (this is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations) DeactivatedItemData = { ID = 0, @@ -35812,64 +40901,64 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct IsAlive = false }, - HoveredId = 0, - HoveredIdTimer = 0.0, - HoveredIdNotActiveTimer = 0.0, + HoveredId = 0, -- Hovered widget, filled during the frame + HoveredIdTimer = 0.0, -- Measure contiguous hovering time + HoveredIdNotActiveTimer = 0.0, -- Measure contiguous hovering time where the item has not been active HoveredIdAllowOverlap = false, HoverItemDelayId = 0, HoverItemDelayIdPreviousFrame = 0, HoverItemUnlockedStationaryId = 0, HoverWindowUnlockedStationaryId = 0, - HoverItemDelayTimer = 0.0, HoverItemDelayClearTimer = 0.0, + HoverItemDelayTimer = 0.0, HoverItemDelayClearTimer = 0.0, -- Currently used by IsItemHovered() - ActiveIdAllowOverlap = false, + ActiveIdAllowOverlap = false, -- Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) - NavLayer = ImGuiNavLayer.Main, - NavId = 0, + NavLayer = ImGuiNavLayer.Main, -- Focused layer (main scrolling layer, or menu/title bar layer) + NavId = 0, -- Focused item for navigation NavOpenContextMenuItemId = 0, NavOpenContextMenuWindowId = 0, - NavWindow = nil, + NavWindow = nil, -- Focused window for navigation. Could be called 'FocusedWindow' NavHighlightActivatedId = 0, NavHighlightActivatedTimer = 0.0, - NavCursorVisible = false, + NavCursorVisible = false, -- Nav focus cursor/rectangle is visible? We hide it after a mouse click. We show it after a nav move. NavCursorHideFrames = 0, - NavHighlightItemUnderNav = false, - NavIdIsAlive = false, - NavInputSource = ImGuiInputSource.Keyboard, - NavWindowingTarget = nil, NavWindowingTargetAnim = nil, NavWindowingListWindow = nil, + NavHighlightItemUnderNav = false, -- Disable mouse hovering highlight. Highlight navigation focused item instead of mouse hovered item. + NavIdIsAlive = false, -- Nav widget has been seen this frame ~~ NavRectRel is valid + NavInputSource = ImGuiInputSource.Keyboard, -- Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource.Keyboard or ImGuiInputSource.Gamepad + NavWindowingTarget = nil, NavWindowingTargetAnim = nil, NavWindowingListWindow = nil, -- Target window when doing Ctrl+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! NavWindowingTimer = 0.0, NavWindowingHighlightAlpha = 0.0, - NavWindowingToggleLayer = false, - NavWindowingToggleKey = ImGuiKey.None, + NavWindowingToggleLayer = false, -- Set while Alt or GamepadMenu is held, may be cleared by other operations, and processed when releasing the key. + NavWindowingToggleKey = ImGuiKey.None, -- Keyboard/gamepad key used when toggling to menu layer. NavWindowingInputSource = ImGuiInputSource.None, NavWindowingAccumDeltaPos = ImVec2(0.0, 0.0), NavWindowingAccumDeltaSize = ImVec2(0.0, 0.0), - DimBgRatio = 0.0, - LastKeyboardKeyPressTime = -1.0, LastKeyModsChangeTime = -1.0, LastKeyModsChangeFromNoneTime = -1.0, - ConfigNavWindowingKeyNext = bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Tab), - ConfigNavWindowingKeyPrev = bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Tab), - ConfigNavWindowingWithGamepad = true, + DimBgRatio = 0.0, -- 0.0..1.0 animation when fading in a dimming background (for modal window and Ctrl+Tab list) + LastKeyboardKeyPressTime = -1.0, LastKeyModsChangeTime = -1.0, LastKeyModsChangeFromNoneTime = -1.0, -- Record the last time a keyboard key (ignore mouse/gamepad ones) was pressed. + ConfigNavWindowingKeyNext = bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Tab), -- = ImGuiMod_Ctrl | ImGuiKey.Tab (or ImGuiMod_Super | ImGuiKey.Tab on OS X). Set to 0 to disable. For reconfiguration (see #4828) + ConfigNavWindowingKeyPrev = bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Tab), -- = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey.Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey.Tab on OS X) + ConfigNavWindowingWithGamepad = true, -- = true. Enable Ctrl+Tab by holding ImGuiKey.GamepadFaceLeft (== ImGuiKey.NavGamepadMenu). When false, the button may still be used to toggle Menu layer. - NavFocusRoute = ImVector(), + NavFocusRoute = ImVector(), -- Reversed copy focus scope stack for NavId (should contains NavFocusScopeId). This essentially follow the window.ParentWindowForFocusRoute chain. - NavAnyRequest = false, - NavInitRequest = false, + NavAnyRequest = false, -- ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd() + NavInitRequest = false, -- Init request for appearing window to select first item NavInitRequestFromMove = false, - NavInitResult = ImGuiNavItemData(), - NavMoveSubmitted = false, - NavMoveScoringItems = false, + NavInitResult = ImGuiNavItemData(), -- Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) + NavMoveSubmitted = false, -- Move request submitted, will process result on next NewFrame() + NavMoveScoringItems = false, -- Move request submitted, still scoring incoming items NavMoveForwardToNextFrame = false, NavMoveFlags = ImGuiNavMoveFlags.None, NavMoveScrollFlags = ImGuiScrollFlags.None, NavMoveKeyMods = ImGuiMod_None, - NavMoveDir = ImGuiDir.None, NavMoveDirForDebug = ImGuiDir.None, NavMoveClipDir = ImGuiDir.None, - NavMoveResultLocal = ImGuiNavItemData(), - NavMoveResultOther = ImGuiNavItemData(), - NavMoveResultLocalVisible = ImGuiNavItemData(), - NavTabbingResultFirst = ImGuiNavItemData(), - NavScoringRect = ImRect(), - NavScoringNoClipRect = ImRect(), - ConfigNavEnableTabbing = true, - NavTabbingCounter = 0, - NavTabbingDir = 0, - NavNextActivateId = 0, + NavMoveDir = ImGuiDir.None, NavMoveDirForDebug = ImGuiDir.None, NavMoveClipDir = ImGuiDir.None, -- Direction of the move request (left/right/up/down) + NavMoveResultLocal = ImGuiNavItemData(), -- Best move request candidate within NavWindow + NavMoveResultOther = ImGuiNavItemData(), -- Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags.NavFlattened flag) + NavMoveResultLocalVisible = ImGuiNavItemData(), -- Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags.AlsoScoreVisibleSet flag) + NavTabbingResultFirst = ImGuiNavItemData(), -- First tabbing request candidate within NavWindow and flattened hierarchy + NavScoringRect = ImRect(), -- Rectangle used for scoring, in screen space. Based of window.NavRectRel[], modified for directional navigation scoring. + NavScoringNoClipRect = ImRect(), -- Some nav operations (such as PageUp/PageDown) enforce a region which clipper will attempt to always keep submitted. Unset/invalid if inverted. + ConfigNavEnableTabbing = true, -- = true. Enable tabbing (Tab, Shift+Tab). PLEASE LET ME KNOW IF YOU USE THIS. + NavTabbingCounter = 0, -- >0 when counting items for tabbing + NavTabbingDir = 0, -- Generally -1 or +1, 0 when tabbing without a nav id + NavNextActivateId = 0, -- Set by ActivateItemByID(), queued until next frame. NavNextActivateFlags = ImGuiActivateFlags.None, - NavActivateId = 0, NavActivateDownId = 0, NavActivatePressedId = 0, + NavActivateId = 0, NavActivateDownId = 0, NavActivatePressedId = 0, -- ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey.Space) || IsKeyDown(ImGuiKey.Enter) || IsKeyPressed(ImGuiKey.NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItemByID() NavActivateFlags = ImGuiActivateFlags.None, FrameCount = -1, @@ -35880,67 +40969,67 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct Time = 0, - NextItemData = ImGuiNextItemData(), - LastItemData = ImGuiLastItemData(), - NextWindowData = ImGuiNextWindowData(), + NextItemData = ImGuiNextItemData(), -- Storage for SetNextItem** functions + LastItemData = ImGuiLastItemData(), -- Storage for last submitted item (setup by ItemAdd) + NextWindowData = ImGuiNextWindowData(), -- Storage for SetNextWindow** functions - Viewports = ImVector(), + Viewports = ImVector(), -- Active viewports (always 1+, and generally 1 unless multi-viewports are enabled). Each viewports hold their copy of ImDrawData. - FallbackMonitor = nil, + FallbackMonitor = nil, -- Virtual monitor used as fallback if backend doesn't provide monitor information. - GcCompactAll = false, + GcCompactAll = false, -- Request full GC CurrentViewport = nil, MouseViewport = nil, MouseLastHoveredViewport = nil, PlatformLastFocusedViewportId = 1, - ViewportCreatedCount = 0, PlatformWindowsCreatedCount = 0, - ViewportFocusedStampCount = 0, + ViewportCreatedCount = 0, PlatformWindowsCreatedCount = 0, -- Unique sequential creation counter (mostly for testing/debugging) + ViewportFocusedStampCount = 0, -- Every time the front-most window changes, we stamp its viewport with an incrementing counter - Font = nil, - FontSize = 0.0, - FontSizeBase = 0.0, - CurrentDpiScale = 0.0, + Font = nil, -- Currently bound font. (== FontStack.back().Font) + FontSize = 0.0, -- Currently bound font size == line height (== FontSizeBase + externals scales applied in the UpdateCurrentFontSize() function). + FontSizeBase = 0.0, -- Font size before scaling == style.FontSizeBase == value passed to PushFont() when specified. + CurrentDpiScale = 0.0, -- Current window/viewport DpiScale == CurrentViewport.DpiScale FontRefSize = 0.0, FontRasterizerDensity = 1.0, - FontAtlases = ImVector(), + FontAtlases = ImVector(), -- List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas) - FontStack = ImVector(), + FontStack = ImVector(), -- Stack for PushFont()/PopFont() - inherited by Begin() - OpenPopupStack = ImVector(), - BeginPopupStack = ImVector(), + OpenPopupStack = ImVector(), -- Which popups are open (persistent) + BeginPopupStack = ImVector(), -- Which level of BeginPopup() we are in (reset every frame) TreeNodeStack = ImVector(ImGuiTreeNodeStackData), - WithinEndChildID = 0, WithinEndPopupID = 0, + WithinEndChildID = 0, WithinEndPopupID = 0, -- Set within EndChild() BeginMenuDepth = 0, BeginComboDepth = 0, - ColorEditCurrentID = 0, ColorEditSavedID = 0, - ColorEditSavedHue = 0.0, ColorEditSavedSat = 0.0, - ColorEditSavedColor = 0, - ColorPickerRef = ImVec4(), + ColorEditCurrentID = 0, ColorEditSavedID = 0, -- Set temporarily while inside of the parent-most ColorEdit4/ColorPicker4 (because they call each others). + ColorEditSavedHue = 0.0, ColorEditSavedSat = 0.0, -- Backup of last Hue associated to LastColor, so we can restore Hue in lossy RGB<>HSV round trips + ColorEditSavedColor = 0, -- RGB value with alpha set to 0. + ColorPickerRef = ImVec4(), -- Initial/reference color at the time of opening the color picker. - MenusIdSubmittedThisFrame = ImVector(), + MenusIdSubmittedThisFrame = ImVector(), -- A list of menu IDs that were rendered at least once DrawListSharedData = ImDrawListSharedData(), StackSizesInBeginForCurrentWindow = nil, MouseCursor = ImGuiMouseCursor.Arrow, - MouseStationaryTimer = 0.0, + MouseStationaryTimer = 0.0, -- Time the mouse has been stationary (with some loose heuristic) InputTextState = ImGuiInputTextState(), - InputTextLineIndex = ImGuiTextIndex(), + InputTextLineIndex = ImGuiTextIndex(), -- Temporary storage InputTextDeactivatedState = ImGuiInputTextDeactivatedState(), InputTextPasswordFontBackupBaked = ImFontBaked(), - InputTextReactivateId = 0, - TempInputId = 0, + InputTextReactivateId = 0, -- ID of InputText to reactivate on next frame (for io.ConfigInputTextEnterKeepActive behavior) + TempInputId = 0, -- Temporary text input when using Ctrl+Click on a slider, etc. - ActiveIdValueOnActivation = 0, - DataTypeZeroValue = 0, + ActiveIdValueOnActivation = 0, -- Backup of initial value at the time of activation. ONLY SET BY SPECIFIC WIDGETS: DragXXX and SliderXXX. + DataTypeZeroValue = 0, -- 0 for all data types ComboPreviewData = ImGuiComboPreviewData(), @@ -35949,97 +41038,97 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct -- Docking DockContext = ImGuiDockContext(), DockNodeWindowMenuHandler = nil, - DebugHoveredDockNode = nil, + DebugHoveredDockNode = nil, -- Hovered dock node. CurrentTabBarStack = ImVector(), -- holds ImGuiTabBar references directly (no ImGuiPtrOrIndex needed in Lua) ShrinkWidthBuffer = ImVector(), -- ImGuiShrinkWidthItem - WindowResizeBorderExpectedRect = ImRect(), + WindowResizeBorderExpectedRect = ImRect(), -- Expected border rect, switch to relative edit if moving WindowResizeRelativeMode = false, - ScrollbarSeekMode = 0, - ScrollbarClickDeltaToGrabCenter = 0.0, + ScrollbarSeekMode = 0, -- 0: scroll to clicked location, -1/+1: prev/next page. + ScrollbarClickDeltaToGrabCenter = 0.0, -- When scrolling to mouse location: distance between mouse and center of grab box, normalized in parent space. SliderGrabClickOffset = 0.0, - SliderCurrentAccum = 0.0, - SliderCurrentAccumDirty = false, + SliderCurrentAccum = 0.0, -- Accumulated slider delta when using navigation controls. + SliderCurrentAccumDirty = false, -- Has the accumulated slider delta changed since last time we tried to apply it? DragCurrentAccumDirty = false, - DragCurrentAccum = 0.0, - DragSpeedDefaultRatio = 1.0 / 100.0, + DragCurrentAccum = 0.0, -- Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings + DragSpeedDefaultRatio = 1.0 / 100.0, -- If speed == 0.0, uses (max-min) * DragSpeedDefaultRatio TooltipOverrideCount = 0, - TooltipPreviousWindow = nil, + TooltipPreviousWindow = nil, -- Window of last tooltip submitted during the frame - FocusScopeStack = ImVector(), - CurrentFocusScopeId = 0, - CurrentItemFlags = ImGuiItemFlags.None, + FocusScopeStack = ImVector(), -- Stack for PushFocusScope()/PopFocusScope() - inherited by BeginChild(), pushed into by Begin() + CurrentFocusScopeId = 0, -- Value for currently appending items == g.FocusScopeStack.back(). Not to be mistaken with g.NavFocusScopeId. + CurrentItemFlags = ImGuiItemFlags.None, -- Value for currently appending items == g.ItemFlagsStack.back() - DisabledAlphaBackup = 0.0, + DisabledAlphaBackup = 0.0, -- Backup for style.Alpha for BeginDisabled() DisabledStackSize = 0, - ItemFlagsStack = ImVector(), - GroupStack = ImVector(), + ItemFlagsStack = ImVector(), -- Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() + GroupStack = ImVector(), -- Stack for BeginGroup()/EndGroup() - not inherited by Begin() - PlatformImeData = ImGuiPlatformImeData(), - PlatformImeDataPrev = ImGuiPlatformImeData(), + PlatformImeData = ImGuiPlatformImeData(), -- 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. + PlatformImeDataPrev = ImGuiPlatformImeData(), -- Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. -- Extensions - UserTextures = ImVector(), + UserTextures = ImVector(), -- List of textures created/managed by user or third-party extension. Automatically appended into platform_io.Textures[]. -- Settings SettingsLoaded = false, - SettingsDirtyTimer = 0.0, + SettingsDirtyTimer = 0.0, -- Save .ini Settings to memory when time reaches zero SettingsIniData = "", -- In memory .ini settings (string) SettingsHandlers = ImVector(), -- List of .ini settings handlers - SettingsWindows = ImVector(), - SettingsTables = ImVector(), + SettingsWindows = ImVector(), -- ImGuiWindow .ini settings entries + SettingsTables = ImVector(), -- ImGuiTable .ini settings entries -- Hooks - Hooks = ImVector(), - HookIdNext = 0, + Hooks = ImVector(), -- Hooks for extensions (e.g. test engine) + HookIdNext = 0, -- Next available HookId -- Drag and Drop DragDropActive = false, - DragDropWithinSource = false, - DragDropWithinTarget = false, + DragDropWithinSource = false, -- Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source. + DragDropWithinTarget = false, -- Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target. DragDropSourceFlags = 0, DragDropSourceFrameCount = -1, DragDropMouseButton = -1, DragDropPayload = ImGuiPayload(), - DragDropTargetRect = ImRect(), - DragDropTargetClipRect = ImRect(), + DragDropTargetRect = ImRect(), -- Store rectangle of current target candidate (we favor small targets when overlapping) + DragDropTargetClipRect = ImRect(), -- Store ClipRect at the time of item's drawing DragDropTargetId = 0, DragDropTargetFullViewport = 0, DragDropAcceptFlagsCurr = 0, DragDropAcceptFlagsPrev = 0, - DragDropAcceptIdCurrRectSurface = 0.0, - DragDropAcceptFrameCount = -1, - DragDropHoldJustPressedId = 0, + DragDropAcceptIdCurrRectSurface = 0.0, -- Target item surface (we resolve overlapping targets by prioritizing the smaller surface) + DragDropAcceptFrameCount = -1, -- Last time a target expressed a desire to accept the source + DragDropHoldJustPressedId = 0, -- Set when holding a payload just made ButtonBehavior() return a press. - DragDropAcceptIdPrev = 0, DragDropAcceptIdCurr = 0, + DragDropAcceptIdPrev = 0, DragDropAcceptIdCurr = 0, -- Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets) -- Clipper ClipperTempDataStacked = 0, ClipperTempData = ImVector(), -- Logging - LogEnabled = false, + LogEnabled = false, -- Currently capturing LogLineFirstItem = false, - LogFlags = 0, + LogFlags = 0, -- Capture flags/type LogWindow = nil, - LogFile = nil, - LogBuffer = ImGuiTextBuffer(), - LogNextPrefix = nil, LogNextSuffix = nil, + LogFile = nil, -- If ~= nil log to stdout/ file + LogBuffer = ImGuiTextBuffer(), -- Accumulation buffer when log to clipboard. + LogNextPrefix = nil, LogNextSuffix = nil, -- See comment in LogSetNextTextDecoration(): doesn't copy underlying data, use carefully! LogLinePosY = FLT_MAX, LogDepthRef = 0, LogDepthToExpand = 2, LogDepthToExpandDefault = 2, -- Error handling - ErrorCallback = nil, ErrorCallbackUserData = nil, + ErrorCallback = nil, ErrorCallbackUserData = nil, -- = nil. May be exposed in public API eventually. ErrorTooltipLockedPos = ImVec2(), ErrorFirst = true, - ErrorCountCurrentFrame = 0, - StackSizesInNewFrame = nil, - ContextName = "", - DebugBreakInWindow = 0, + ErrorCountCurrentFrame = 0, -- [Internal] Number of errors submitted this frame. + StackSizesInNewFrame = nil, -- [Internal] + ContextName = "", -- Storage for a context name (to facilitate debugging multi-context setups) + DebugBreakInWindow = 0, -- Set to break in Begin() call. LocalizationTable = {}, @@ -36047,7 +41136,7 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct DebugFlashStyleColorIdx = nil, DebugMetricsConfig = ImGuiMetricsConfig(), - DebugHookIdInfoId = 0, + DebugHookIdInfoId = 0, -- Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool DebugAllocInfo = ImGuiDebugAllocInfo(), --- Misc @@ -36056,16 +41145,16 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct FramerateSecPerFrameCount = 0, FramerateSecPerFrameAccum = 0, - WantCaptureMouseNextFrame = -1, - WantCaptureKeyboardNextFrame = -1, - WantTextInputNextFrame = -1, - TempBuffer = ImVector(), + WantCaptureMouseNextFrame = -1, -- Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1. + WantCaptureKeyboardNextFrame = -1, -- " + WantTextInputNextFrame = -1, -- Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. + TempBuffer = ImVector(), -- Temporary text buffer -- Tables (imgui_tables.lua) CurrentTable = nil, - DebugBreakInTable = 0, - TablesTempDataStacked = 0, - TablesTempData = ImVector(), + DebugBreakInTable = 0, -- Set to break in BeginTable() call. + TablesTempDataStacked = 0, -- Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) + TablesTempData = ImVector(), -- Temporary table data (buffers reused/shared across instances, support nesting) Tables = ImPool(), -- ImPool, 0-based indices (imgui_tables.lua) TablesLastTimeActive = ImVector(), -- [table_idx + 1] = float DrawChannelsTempMergeBuffer = ImVector(), @@ -36091,6 +41180,11 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct return this end +------------------------------------------------------------------------------- +-- [SECTION] Settings support +------------------------------------------------------------------------------- + +-- Windows data saved in imgui.ini file --- @class ImGuiWindowSettings --- @field ID int # Window ID --- @field Pos ImVec2 # Window position @@ -36110,22 +41204,23 @@ end function ImGuiWindowSettings() return setmetatable({ ID = 0, - Pos = ImVec2(0, 0), + Pos = ImVec2(0, 0), -- NB: Settings position are stored RELATIVE to the viewport! Whereas runtime ones are absolute positions. Size = ImVec2(0, 0), Collapsed = false, IsChild = false, - WantApply = false, - WantDelete = false, + WantApply = false, -- Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) + WantDelete = false, -- Set to invalidate/delete the settings entry Name = "", ViewportId = 0, ViewportPos = ImVec2(0, 0), - DockId = 0, - DockOrder = -1, - ClassId = 0, + DockId = 0, -- ID of last known DockNode (even if the DockNode is invisible because it has only 1 active window), or 0 if none. + DockOrder = -1, -- Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. + ClassId = 0, -- ID of window class if specified LastUsedDate = 0, }, IMGUI_WINDOW_SETTINGS) end +-- Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper. --- @class ImGuiMenuColumns --- @field TotalWidth ImU32 --- @field NextTotalWidth ImU32 @@ -36144,14 +41239,20 @@ local function ImGuiMenuColumns() TotalWidth = 0, NextTotalWidth = 0, Spacing = 0, - OffsetIcon = 0, - OffsetLabel = 0, + OffsetIcon = 0, -- Always zero for now + OffsetLabel = 0, -- Offsets are locked in Update() OffsetShortcut = 0, OffsetMark = 0, - Widths = {0, 0, 0, 0} + Widths = {0, 0, 0, 0} -- Width of: Icon, Label, Shortcut, Mark (accumulators for current frame) }, MT.ImGuiMenuColumns) end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiWindowTempData, ImGuiWindow +------------------------------------------------------------------------------- + +-- Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. +-- (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..) --- @class ImGuiWindowTempData --- @field CursorPos ImVec2 --- @field CursorPosPrevLine ImVec2 @@ -36185,48 +41286,49 @@ local function ImGuiWindowTempData() return { DockTabItemStatusFlags = 0, DockTabItemRect = ImRect(), - CursorPos = ImVec2(), + CursorPos = ImVec2(), -- Current emitting position, in absolute coordinates. CursorPosPrevLine = ImVec2(), - CursorStartPos = ImVec2(), - CursorMaxPos = ImVec2(), - IdealMaxPos = ImVec2(), + CursorStartPos = ImVec2(), -- Initial position after Begin(), generally ~ window position + WindowPadding. + CursorMaxPos = ImVec2(), -- Used to implicitly calculate ContentSize at the beginning of next frame, for scrolling range and auto-resize. Always growing during the frame. + IdealMaxPos = ImVec2(), -- Used to implicitly calculate ContentSizeIdeal at the beginning of next frame, for auto-resize only. Always growing during the frame. CurrLineSize = ImVec2(), PrevLineSize = ImVec2(), - CurrLineTextBaseOffset = 0, + CurrLineTextBaseOffset = 0, -- Baseline offset (0.0 by default on a new line, generally == style.FramePadding.y when a framed item has been added). PrevLineTextBaseOffset = 0, IsSameLine = false, IsSetPos = false, - NavLayersActiveMask = 0, NavLayersActiveMaskNext = 0, + NavLayersActiveMask = 0, NavLayersActiveMaskNext = 0, -- Which layers have been written to (result from previous frame) - Indent = ImVec1(), - ColumnsOffset = ImVec1(), + Indent = ImVec1(), -- Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + ColumnsOffset = ImVec1(), -- Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree.Column.Tree. Need revamp columns API. GroupOffset = ImVec1(), - CursorStartPosLossyness = ImVec2(), + CursorStartPosLossyness = ImVec2(), -- Record the loss of precision of CursorStartPos due to really large scrolling amount. This is used by clipper to compensate and fix the most common use case of large scroll area. - ItemWidth = 0, + ItemWidth = 0, -- Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window). ItemWidthDefault = 0, - TextWrapPos = 0, - ItemWidthStack = ImVector(), - TextWrapPosStack = ImVector(), + TextWrapPos = 0, -- Current text wrap pos. + ItemWidthStack = ImVector(), -- Store item widths to restore (attention: .back() is not == ItemWidth) + TextWrapPosStack = ImVector(), -- Store text wrap pos to restore (attention: .back() is not == TextWrapPos) MenuBarAppending = false, -- FIXME: Remove this - MenuBarOffset = ImVec2(), - MenuColumns = ImGuiMenuColumns(), - TreeDepth = 0, - TreeHasStackDataDepthMask = nil, - TreeRecordsClippedNodesY2Mask = nil, + MenuBarOffset = ImVec2(), -- 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. + MenuColumns = ImGuiMenuColumns(), -- Simplified columns storage for menu items measurement + TreeDepth = 0, -- Current tree depth. + TreeHasStackDataDepthMask = nil, -- Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. Sync any changes with TREE_NODE_MAX_DEPTH/TREE_NODE_GET_DEPTH_MASK! + TreeRecordsClippedNodesY2Mask = nil, -- Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. ChildWindows = ImVector(), CurrentTableIdx = -1, -- 0-based index into g.Tables, -1 if none CurrentColumns = nil, -- ImGuiOldColumns (legacy Columns API) - StateStorage = nil, + StateStorage = nil, -- Current persistent per-window storage (store e.g. tree node open/close state) LayoutType = nil } end +-- Storage for one window --- @class ImGuiWindow --- @field Ctx ImGuiContext --- @field Name string @@ -36270,6 +41372,7 @@ end MT.ImGuiWindow = {} MT.ImGuiWindow.__index = MT.ImGuiWindow +-- We don't use g.FontSize because the window may be != g.CurrentWindow. --- @return ImRect --- @nodiscard function MT.ImGuiWindow:Rect() @@ -36293,58 +41396,58 @@ end --- @nodiscard function ImGuiWindow(ctx, name) local this = { - ID = 0, + ID = 0, -- == ImHashStr(Name) - MoveId = 0, + MoveId = 0, -- == window.GetID("#MOVE") - Ctx = ctx, - Name = name, + Ctx = ctx, -- Parent UI context (needs to be set explicitly by parent). + Name = name, -- Window name Flags = 0, - ChildFlags = 0, - WindowClass = ImGuiWindowClass(), + ChildFlags = 0, -- Set when window is a child window. See enum ImGuiChildFlags + WindowClass = ImGuiWindowClass(), -- Advanced users only. Set with SetNextWindowClass() - Pos = ImVec2(), + Pos = ImVec2(), -- Position (always rounded-up to nearest pixel) Size = ImVec2(), -- Current size (==SizeFull or collapsed title bar size) - SizeFull = ImVec2(), + SizeFull = ImVec2(), -- Size when non collapsed - Active = false, + Active = false, -- Set to true on Begin(), unless Collapsed WasActive = false, - Collapsed = false, + Collapsed = false, -- Set when collapsing window to become only title-bar - SkipItems = false, + SkipItems = false, -- Set when items can safely be all clipped (e.g. window not visible or collapsed) - SkipRefresh = false, + SkipRefresh = false, -- [EXPERIMENTAL] Reuse previous frame drawn contents, Begin() returns false. CacheSnap = nil, -- [Port] SetNextWindowCached(): state at the last refresh CacheSkipItemsBackup = nil, - Appearing = false, + Appearing = false, -- Set during the frame where the window is appearing (or re-appearing) - Hidden = false, - IsFallbackWindow = false, + Hidden = false, -- Do not display (== HiddenFrames*** > 0) + IsFallbackWindow = false, -- Set on the "Debug##Default" window. - IsExplicitChild = nil, + IsExplicitChild = nil, -- Set when passed _ChildWindow, left to false by BeginDocked() - ResizeBorderHovered = -1, - ResizeBorderHeld = -1, + ResizeBorderHovered = -1, -- Current border being hovered for resize (-1: none, otherwise 0-3) + ResizeBorderHeld = -1, -- Current border being held for resize (-1: none, otherwise 0-3) - BeginCount = 0, - BeginCountPreviousFrame = 0, - BeginOrderWithinParent = 0, - BeginOrderWithinContext = 0, + BeginCount = 0, -- Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) + BeginCountPreviousFrame = 0, -- Number of Begin() during the previous frame + BeginOrderWithinParent = 0, -- Begin() order within immediate parent window, if we are a child window. Otherwise 0. + BeginOrderWithinContext = 0, -- Begin() order within entire imgui context. This is mostly used for debugging submission order related issues. - FocusOrder = nil, + FocusOrder = nil, -- Order within WindowsFocusOrder[], altered when windows are focused. - HiddenFramesCanSkipItems = 0, - HiddenFramesCannotSkipItems = 0, - HiddenFramesForRenderOnly = 0, + HiddenFramesCanSkipItems = 0, -- Hide the window for N frames + HiddenFramesCannotSkipItems = 0, -- Hide the window for N frames while allowing items to be submitted so we can measure their size + HiddenFramesForRenderOnly = 0, -- Hide the window until frame N at Render() time only - DisableInputsFrames = 0, + DisableInputsFrames = 0, -- Disable window interactions for N frames - WindowRounding = 0, - WindowBorderSize = 1, + WindowRounding = 0, -- Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc. + WindowBorderSize = 1, -- Window border size at the time of Begin(). TitleBarHeight = 0, MenuBarHeight = 0, @@ -36352,83 +41455,83 @@ function ImGuiWindow(ctx, name) DecoOuterSizeX2 = 0, DecoOuterSizeY2 = 0, DecoInnerSizeX1 = 0, DecoInnerSizeY1 = 0, - ContentSize = ImVec2(), + ContentSize = ImVec2(), -- Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. ContentSizeIdeal = ImVec2(), - ContentSizeExplicit = ImVec2(), + ContentSizeExplicit = ImVec2(), -- Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). AutoFitFramesX = -1, AutoFitFramesY = -1, AutoFitOnlyGrows = false, - HasCloseButton = true, + HasCloseButton = true, -- Set when the window has a close button (p_open ~= nil) - BgClickFlags = 0, + BgClickFlags = 0, -- Configure behavior of click+dragging on window bg/void or over items. Default sets by io.ConfigWindowsMoveFromTitleBarOnly. If you use this please report in #3379. - SetWindowPosAllowFlags = 0, SetWindowSizeAllowFlags = 0, SetWindowCollapsedAllowFlags = 0, - SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX), - SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX), + SetWindowPosAllowFlags = 0, SetWindowSizeAllowFlags = 0, SetWindowCollapsedAllowFlags = 0, -- store acceptable condition flags for SetNextWindowPos() use. + SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX), -- store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) + SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX), -- store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5, 0.5) for centering; ImVec2(1, 1) for bottom right. - SettingsOffset = -1, + SettingsOffset = -1, -- Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) - ScrollbarSizes = ImVec2(), + ScrollbarSizes = ImVec2(), -- 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. Scroll = ImVec2(), ScrollbarX = false, - ScrollbarY = false, + ScrollbarY = false, -- Are scrollbars visible? ScrollMax = ImVec2(), - ScrollTarget = ImVec2(FLT_MAX, FLT_MAX), - ScrollTargetCenterRatio = ImVec2(0.5, 0.5), - ScrollTargetEdgeSnapDist = ImVec2(), + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX), -- target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0. (FLT_MAX for no change) + ScrollTargetCenterRatio = ImVec2(0.5, 0.5), -- 0.0 = scroll so that target position is at top, 0.5 = scroll so that target position is centered + ScrollTargetEdgeSnapDist = ImVec2(), -- 0.0 = no snapping, >0.0 snapping threshold - ScrollbarXStabilizeToggledHistory = 0, + ScrollbarXStabilizeToggledHistory = 0, -- Used to stabilize scrollbar visibility in case of feedback loops - DrawList = nil, + DrawList = nil, -- == DrawListInst DrawListInst = ImDrawList(ctx.DrawListSharedData), - RootWindow = nil, - RootWindowPopupTree = nil, - RootWindowDockTree = nil, + RootWindow = nil, -- Point to ourself or first ancestor that is not a child window. Doesn't cross through popups/dock nodes. + RootWindowPopupTree = nil, -- Point to ourself or first ancestor that is not a child window. Cross through popups parent<>child. + RootWindowDockTree = nil, -- Point to ourself or first ancestor that is not a child window. Cross through dock nodes. - ParentWindow = nil, + ParentWindow = nil, -- If we are a child _or_ popup _or_ docked window, this is pointing to our parent. Otherwise nil. ParentWindowInBeginStack = nil, - IDStack = ImVector(), + IDStack = ImVector(), -- ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure) - ViewportAllowPlatformMonitorExtend = -1, - Viewport = nil, - ViewportId = 0, - ViewportPos = ImVec2(FLT_MAX, FLT_MAX), + ViewportAllowPlatformMonitorExtend = -1, -- Reset to -1 every frame (index is guaranteed to be valid between NewFrame..EndFrame), only used in the Appearing frame of a tooltip/popup to enforce clamping to a given monitor + Viewport = nil, -- Always set in Begin(). Inactive windows may have a nil value here if their viewport was discarded. + ViewportId = 0, -- We backup the viewport id (since the viewport may disappear or never be created if the window is inactive) + ViewportPos = ImVec2(FLT_MAX, FLT_MAX), -- We backup the viewport position (since the viewport may disappear or never be created if the window is inactive) ViewportOwned = nil, - DC = ImGuiWindowTempData(), + DC = ImGuiWindowTempData(), -- Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. - OuterRectClipped = ImRect(), - InnerRect = ImRect(), - InnerClipRect = ImRect(), - WorkRect = ImRect(), - ParentWorkRect = ImRect(), - ContentRegionRect = ImRect(), + OuterRectClipped = ImRect(), -- == Window.Rect() just after setup in Begin(). == window.Rect() for root window. + InnerRect = ImRect(), -- Inner rectangle (omit title bar, menu bar, scroll bar) + InnerClipRect = ImRect(), -- == InnerRect shrunk by WindowPadding*0.5 on each side, clipped within viewport or parent clip rect. + WorkRect = ImRect(), -- Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0 on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). + ParentWorkRect = ImRect(), -- Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. -- FIXME-WORKRECT: Could be a stack? + ContentRegionRect = ImRect(), -- FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. - ClipRect = ImRect(), + ClipRect = ImRect(), -- Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList.clip_rect_stack.back(). - LastFrameActive = -1, - LastFrameJustFocused = -1, - LastTimeActive = -1.0, + LastFrameActive = -1, -- Last frame number the window was Active. + LastFrameJustFocused = -1, -- Last frame number the window was made Focused. + LastTimeActive = -1.0, -- Last timestamp the window was Active (using float as we don't need high precision there) StateStorage = {}, ColumnsStorage = ImVector(), -- ImVector - WriteAccessed = false, + WriteAccessed = false, -- Set to true when any widget access the current window - FontWindowScale = 1.0, + FontWindowScale = 1.0, -- User scale multiplier per-window, via SetWindowFontScale() FontWindowScaleParents = 1.0, - HitTestHoleSize = ImVec2(), + HitTestHoleSize = ImVec2(), -- Define an optional rectangular hole where mouse will pass-through the window. - NavLastChildNavWindow = nil, + NavLastChildNavWindow = nil, -- When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) NavLastIds = {[0] = 0, [1] = 0}, -- FIXME: 1-based instead - NavRectRel = {[0] = ImRect(), [1] = ImRect()}, - NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, - NavRootFocusScopeId = 0 + NavRectRel = {[0] = ImRect(), [1] = ImRect()}, -- Reference rectangle, in window relative space + NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, -- Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX. + NavRootFocusScopeId = 0 -- Focus Scope ID at the time of Begin() } this.DrawList = this.DrawListInst @@ -36439,27 +41542,27 @@ function ImGuiWindow(ctx, name) this.ID = ImHashStr(name) this.IDStack:push_back(this.ID) this.MoveId = this:GetID("#MOVE") - this.TabId = this:GetID("#TAB") + this.TabId = this:GetID("#TAB") -- == window.GetID("#TAB") -- Docking - this.ChildId = this.ChildId or 0 - this.SetWindowDockAllowFlags = 0 - this.ParentWindowForFocusRoute = nil - this.DockIsActive = false + this.ChildId = this.ChildId or 0 -- ID of corresponding item in parent window (for navigation to return from child window to parent window) + this.SetWindowDockAllowFlags = 0 -- store acceptable condition flags for SetNextWindowDock() use. + this.ParentWindowForFocusRoute = nil -- Set to manual link a window to its logical parent so that Shortcut() chain are honored (e.g. Tool linked to Document) + this.DockIsActive = false -- When docking artifacts are actually visible. When this is set, DockNode is guaranteed to be != nil. ~~ (DockNode != nil) && (DockNode.Windows.Size > 1). this.DockNodeIsVisible = false - this.DockTabIsVisible = false + this.DockTabIsVisible = false -- Is our window visible this frame? ~~ is the corresponding tab selected? this.DockTabWantClose = false - this.DockOrder = -1 + this.DockOrder = -1 -- Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. this.DockStyle = { Colors = {} } for i = 0, 8 do this.DockStyle.Colors[i] = 0 end - this.DockNode = nil - this.DockNodeAsHost = nil - this.DockId = 0 + this.DockNode = nil -- 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. + this.DockNodeAsHost = nil -- Which node are we owning (for parent windows) + this.DockId = 0 -- Backup of last valid DockNode.ID, so single window remember their dock node id even when they are not bound any more return this end --- @class ImDrawDataBuilder ---- @field Layers [ImVector?, ImVector?] +--- @field Layers [ImVector?, ImVector?] # Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData. --- @field LayerData1 ImVector --- @return ImDrawDataBuilder @@ -36467,11 +41570,17 @@ end local function ImDrawDataBuilder() return { - Layers = {nil, nil}, + Layers = {nil, nil}, -- Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData. LayerData1 = ImVector() } end +------------------------------------------------------------------------------- +-- [SECTION] Viewport support +------------------------------------------------------------------------------- + +-- ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!) +-- Every instance of ImGuiViewport is in fact a ImGuiViewportP. --- @class ImGuiViewportP : ImGuiViewport --- @field Window? ImGuiWindow --- @field Idx int # Initial value = -1, then becomes 1-based index @@ -36506,6 +41615,7 @@ function IMGUI_VIEWPORT_P:ClearRequestFlags() self.PlatformRequestResize = false end +-- Calculate work rect pos/size given a set of offset (we have 1 pair of offset for rect locked from last frame data, and 1 pair for currently building rect) function IMGUI_VIEWPORT_P:CalcWorkRectPos(inset_min) return ImVec2(self.Pos.x + inset_min.x, self.Pos.y + inset_min.y) end @@ -36514,11 +41624,13 @@ function IMGUI_VIEWPORT_P:CalcWorkRectSize(inset_min, inset_max) return ImVec2(ImMax(0.0, self.Size.x - inset_min.x - inset_max.x), ImMax(0.0, self.Size.y - inset_min.y - inset_max.y)) end +-- Update public fields function IMGUI_VIEWPORT_P:UpdateWorkRect() self.WorkPos = self:CalcWorkRectPos(self.WorkInsetMin) self.WorkSize = self:CalcWorkRectSize(self.WorkInsetMin, self.WorkInsetMax) end +-- Helpers to retrieve ImRect (we don't need to store BuildWorkRect as every access tend to change it, hence the code asymmetry) --- @nodiscard function IMGUI_VIEWPORT_P:GetMainRect() return ImRect(self.Pos.x, self.Pos.y, @@ -36545,38 +41657,49 @@ end function ImGuiViewportP() local this = setmetatable(ImGuiViewport(), IMGUI_VIEWPORT_P) --- @cast this ImGuiViewportP - this.Window = nil + this.Window = nil -- Set when the viewport is owned by a window (and ImGuiViewportFlags.CanHostOtherWindows is NOT set) this.Idx = -1 - this.LastFrameActive = -1 - this.LastFocusedStampCount = -1 + this.LastFrameActive = -1 -- Last frame number this viewport was activated by a window + this.LastFocusedStampCount = -1 -- Last stamp number from when a window hosted by this viewport was focused (by comparing this value between two viewport we have an implicit viewport z-order we use as fallback) this.LastNameHash = 0 this.LastPos = ImVec2() -- ImGuiViewport() { memset(this, 0, sizeof(*this)); } this.LastSize = ImVec2() - this.Alpha = 1.0 + this.Alpha = 1.0 -- Window opacity (when dragging dockable windows/viewports we make them transparent) this.LastAlpha = 1.0 - this.LastFocusedHadNavWindow = false + this.LastFocusedHadNavWindow = false -- Instead of maintaining a LastFocusedWindow (which may harder to correctly maintain), we merely store weither NavWindow ~= nil last time the viewport was focused. this.PlatformMonitor = -1 - this.BgFgDrawListsLastTimeActive = {-1, -1} - this.BgFgDrawLists = {nil, nil} + this.BgFgDrawListsLastTimeActive = {-1, -1} -- Timestamps for Gc. + this.BgFgDrawLists = {nil, nil} -- Convenience background [1] and foreground [2] draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays. this.DrawDataP = ImDrawData() - this.DrawDataBuilder = ImDrawDataBuilder() + this.DrawDataBuilder = ImDrawDataBuilder() -- Temporary data while building final ImDrawData this.LastPlatformPos = ImVec2(FLT_MAX, FLT_MAX) this.LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX) this.LastRendererSize = ImVec2(FLT_MAX, FLT_MAX) - this.WorkInsetMin = ImVec2(0, 0) - this.WorkInsetMax = ImVec2(0, 0) - this.BuildWorkInsetMin = ImVec2(0, 0) - this.BuildWorkInsetMax = ImVec2(0, 0) + -- Per-viewport work area + -- - Insets are >= 0.0 values, distance from viewport corners to work area. + -- - BeginMainMenuBar() and DockspaceOverViewport() tend to use work area to avoid stepping over existing contents. + -- - Generally 'safeAreaInsets' in iOS land, 'DisplayCutout' in Android land. + this.WorkInsetMin = ImVec2(0, 0) -- Work Area inset locked for the frame. GetWorkRect() always fits within GetMainRect(). + this.WorkInsetMax = ImVec2(0, 0) -- " + this.BuildWorkInsetMin = ImVec2(0, 0) -- Work Area inset accumulator for current frame, to become next frame's WorkInset + this.BuildWorkInsetMax = ImVec2(0, 0) -- " return this end +------------------------------------------------------------------------------- +-- [SECTION] ImFontLoader +------------------------------------------------------------------------------- + +-- 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. --- @class ImFontLoader --- @field Name string --- @field LoaderInit? fun(atlas: ImFontAtlas): bool @@ -36605,13 +41728,24 @@ function ImFontLoader() this.FontSrcContainsGlyph = nil this.FontBakedInit = nil this.FontBakedDestroy = nil - this.FontBakedLoadGlyph = nil + this.FontBakedLoadGlyph = nil -- Required + -- 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? this.FontBakedSrcLoaderDataSize = 0 return this end +------------------------------------------------------------------------------- +-- [SECTION] ImFontAtlas internal API +------------------------------------------------------------------------------- + +-- 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. --- @class ImFontAtlasRectEntry --- @field TargetIndex int # 0-based! When IsUsed = true, TargetIndex = this rect's index in Rects; IsUsed = false, TargetIndex = the next unused RectsIndex entry's index --- @field Generation unsigned_int # How many times this entry is reused @@ -36627,8 +41761,9 @@ function ImFontAtlasRectEntry() } end -local ImFontAtlasRectId_IndexMask_ = 0x0007FFFF -local ImFontAtlasRectId_GenerationMask_ = 0x3FF00000 +-- Refer to ImFontAtlasPackGetRect() to better understand how this works. +local ImFontAtlasRectId_IndexMask_ = 0x0007FFFF -- 20-bits signed: index to access builder.RectsIndex[]. +local ImFontAtlasRectId_GenerationMask_ = 0x3FF00000 -- 10-bits: entry generation, so each ID is unique and get can safely detected old identifiers. local ImFontAtlasRectId_GenerationShift_ = 20 --- @param id ImFontAtlasRectId # Expects 0-based! @@ -36647,6 +41782,7 @@ function ImFontAtlasRectId_Make(index_idx, gen_idx) return bitOr(index_idx, bitLShift(gen_idx, ImFontAtlasRectId_GenerationShift_)) end +-- Data available to potential texture post-processing functions --- @class ImFontAtlasPostProcessData --- @field FontAtlas ImFontAtlas --- @field Font ImFont @@ -36681,6 +41817,7 @@ function ImFontAtlasPostProcessData(atlas, font, font_src, font_baked, glyph, pi FontBaked = font_baked, Glyph = glyph, + -- Pixel data Pixels = pixels, _PixelsBase = pixels_base, Format = format, @@ -36690,10 +41827,14 @@ function ImFontAtlasPostProcessData(atlas, font, font_src, font_baked, glyph, pi } end +------------------------------------------------------------------------------- +-- [SECTION] Inputs support +------------------------------------------------------------------------------- + --- @enum ImGuiInputSource ImGuiInputSource = { None = 0, - Mouse = 1, + Mouse = 1, -- Note: may be Mouse or TouchScreen or Pen. See io.MouseSource to distinguish them. Keyboard = 2, Gamepad = 3, COUNT = 4 @@ -36778,7 +41919,7 @@ function ImGuiInputEvent() return { Type = 0, Source = 0, - EventId = 0, + EventId = 0, -- Unique, sequential increasing integer to identify an event (if you need to correlate them to other data). -- union MousePos = nil, -- if Type == ImGuiInputEventType.MousePos @@ -36791,6 +41932,7 @@ function ImGuiInputEvent() } end +-- [Internal] Key ranges ImGuiKey_Keyboard_BEGIN = ImGuiKey.NamedKey_BEGIN ImGuiKey_Keyboard_END = ImGuiKey.GamepadStart ImGuiKey_Gamepad_BEGIN = ImGuiKey.GamepadStart @@ -36800,12 +41942,13 @@ ImGuiKey_Mouse_END = ImGuiKey.MouseWheelY + 1 ImGuiKey_Aliases_BEGIN = ImGuiKey_Mouse_BEGIN ImGuiKey_Aliases_END = ImGuiKey_Mouse_END +-- [Internal] Named shortcuts for Navigation ImGuiKey.NavKeyboardTweakSlow = ImGuiMod_Ctrl ImGuiKey.NavKeyboardTweakFast = ImGuiMod_Shift ImGuiKey.NavGamepadTweakSlow = ImGuiKey.GamepadL1 ImGuiKey.NavGamepadTweakFast = ImGuiKey.GamepadR1 -ImGuiKey.NavGamepadMenu = ImGuiKey.GamepadFaceLeft -ImGuiKey.NavGamepadContextMenu = ImGuiKey.GamepadFaceUp +ImGuiKey.NavGamepadMenu = ImGuiKey.GamepadFaceLeft -- Toggle menu layer. Hold to enable Windowing. +ImGuiKey.NavGamepadContextMenu = ImGuiKey.GamepadFaceUp -- Open context menu (same as Shift+F10) --- @enum ImGuiInputEventType ImGuiInputEventType = { @@ -36820,19 +41963,33 @@ ImGuiInputEventType = { COUNT = 8 } -ImGuiInputFlags.RepeatRateDefault = bitLShift(1, 1) -ImGuiInputFlags.RepeatRateNavMove = bitLShift(1, 2) -ImGuiInputFlags.RepeatRateNavTweak = bitLShift(1, 3) -ImGuiInputFlags.RepeatUntilRelease = bitLShift(1, 4) -ImGuiInputFlags.RepeatUntilKeyModsChange = bitLShift(1, 5) -ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone = bitLShift(1, 6) -ImGuiInputFlags.RepeatUntilOtherKeyPress = bitLShift(1, 7) -ImGuiInputFlags.LockThisFrame = bitLShift(1, 20) -ImGuiInputFlags.LockUntilRelease = bitLShift(1, 21) -ImGuiInputFlags.CondHovered = bitLShift(1, 22) -ImGuiInputFlags.CondActive = bitLShift(1, 23) +-- Extend ImGuiInputFlags +-- Flags for extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() +-- Don't mistake with ImGuiInputTextFlags! (which is for ImGui.InputText() function) + +-- Flags for IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(), Shortcut() +-- - Repeat mode: Repeat rate selection +ImGuiInputFlags.RepeatRateDefault = bitLShift(1, 1) -- Repeat rate: Regular (default) +ImGuiInputFlags.RepeatRateNavMove = bitLShift(1, 2) -- Repeat rate: Fast +ImGuiInputFlags.RepeatRateNavTweak = bitLShift(1, 3) -- Repeat rate: Faster +-- - Repeat mode: Specify when repeating key pressed can be interrupted. +-- - In theory ImGuiInputFlags.RepeatUntilOtherKeyPress may be a desirable default, but it would break too many behavior so everything is opt-in. +ImGuiInputFlags.RepeatUntilRelease = bitLShift(1, 4) -- Stop repeating when released (default for all functions except Shortcut). This only exists to allow overriding Shortcut() default behavior. +ImGuiInputFlags.RepeatUntilKeyModsChange = bitLShift(1, 5) -- Stop repeating when released OR if keyboard mods are changed (default for Shortcut) +ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone = bitLShift(1, 6) -- Stop repeating when released OR if keyboard mods are leaving the None state. Allows going from Mod+Key to Key by releasing Mod. +ImGuiInputFlags.RepeatUntilOtherKeyPress = bitLShift(1, 7) -- Stop repeating when released OR if any other keyboard key is pressed during the repeat + +-- Flags for SetKeyOwner(), SetItemKeyOwner() +-- - Locking key away from non-input aware code. Locking is useful to make input-owner-aware code steal keys from non-input-owner-aware code. If all code is input-owner-aware locking would never be necessary. +ImGuiInputFlags.LockThisFrame = bitLShift(1, 20) -- Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared at end of frame. +ImGuiInputFlags.LockUntilRelease = bitLShift(1, 21) -- Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared when the key is released or at end of each frame if key is released. + +-- - Condition for SetItemKeyOwner() +ImGuiInputFlags.CondHovered = bitLShift(1, 22) -- Only set if item is hovered (default to both) +ImGuiInputFlags.CondActive = bitLShift(1, 23) -- Only set if item is active (default to both) ImGuiInputFlags.CondDefault_ = bitOr(ImGuiInputFlags.CondHovered, ImGuiInputFlags.CondActive) +-- [Internal] Mask of which function support which flags ImGuiInputFlags.RepeatRateMask_ = bitOr(ImGuiInputFlags.RepeatRateDefault, ImGuiInputFlags.RepeatRateNavMove, ImGuiInputFlags.RepeatRateNavTweak) ImGuiInputFlags.RepeatUntilMask_ = bitOr(ImGuiInputFlags.RepeatUntilRelease, ImGuiInputFlags.RepeatUntilKeyModsChange, ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone, ImGuiInputFlags.RepeatUntilOtherKeyPress) ImGuiInputFlags.RepeatMask_ = bitOr(ImGuiInputFlags.Repeat, ImGuiInputFlags.RepeatRateMask_, ImGuiInputFlags.RepeatUntilMask_) @@ -36861,32 +42018,39 @@ ImGuiPlotType = Histogram = 1 } +------------------------------------------------------------------------------- +-- [SECTION] Navigation support +------------------------------------------------------------------------------- + --- @enum ImGuiActivateFlags ImGuiActivateFlags = { None = 0, - PreferInput = bitLShift(1, 0), - PreferTweak = bitLShift(1, 1), - TryToPreserveState = bitLShift(1, 2), - FromTabbing = bitLShift(1, 3), - FromShortcut = bitLShift(1, 4), - FromFocusApi = bitLShift(1, 5) + PreferInput = bitLShift(1, 0), -- Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default for Enter key. + PreferTweak = bitLShift(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. + TryToPreserveState = bitLShift(1, 2), -- Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection) + FromTabbing = bitLShift(1, 3), -- Activation requested by a tabbing request (ImGuiNavMoveFlags.IsTabbing) + FromShortcut = bitLShift(1, 4), -- Activation requested by an item shortcut via SetNextItemShortcut() function. + FromFocusApi = bitLShift(1, 5) -- Activation requested by an api request (ImGuiNavMoveFlags.FocusApi) } +-- Early work-in-progress API for ScrollToItem() +-- FIXME: Missing flags to request making both edges visible when possible. --- @enum ImGuiScrollFlags ImGuiScrollFlags = { None = 0, - KeepVisibleEdgeX = bitLShift(1, 0), - KeepVisibleEdgeY = bitLShift(1, 1), - KeepVisibleCenterX = bitLShift(1, 2), - KeepVisibleCenterY = bitLShift(1, 3), - AlwaysCenterX = bitLShift(1, 4), - AlwaysCenterY = bitLShift(1, 5), - NoScrollParent = bitLShift(1, 6), + KeepVisibleEdgeX = bitLShift(1, 0), -- If item is not visible: scroll as little as possible on X axis to bring item back into view [default for X axis] + KeepVisibleEdgeY = bitLShift(1, 1), -- If item is not visible: scroll as little as possible on Y axis to bring item back into view [default for Y axis for windows that are already visible] + KeepVisibleCenterX = bitLShift(1, 2), -- If item is not visible: scroll to make the item centered on X axis [rarely used] + KeepVisibleCenterY = bitLShift(1, 3), -- If item is not visible: scroll to make the item centered on Y axis + AlwaysCenterX = bitLShift(1, 4), -- Always center the result item on X axis [rarely used] + AlwaysCenterY = bitLShift(1, 5), -- Always center the result item on Y axis [default for Y axis for appearing window) + NoScrollParent = bitLShift(1, 6), -- Disable forwarding scrolling to parent window if required to keep item/rect visible (only scroll window the function was applied to). } ImGuiScrollFlags.MaskX_ = bitOr(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleCenterX, ImGuiScrollFlags.AlwaysCenterX) ImGuiScrollFlags.MaskY_ = bitOr(ImGuiScrollFlags.KeepVisibleEdgeY, ImGuiScrollFlags.KeepVisibleCenterY, ImGuiScrollFlags.AlwaysCenterY) +-- Stacked storage data for BeginGroup()/EndGroup() --- @class ImGuiGroupData --- @field WindowID ImGuiID --- @field BackupCursorPos ImVec2 @@ -36929,9 +42093,13 @@ end ImGuiTooltipFlags = { None = 0, - OverridePrevious = bitLShift(1, 1) + OverridePrevious = bitLShift(1, 1) -- Clear/ignore previously submitted tooltip (defaults to append) } +------------------------------------------------------------------------------- +-- [SECTION] Popup support +------------------------------------------------------------------------------- + --- @enum ImGuiPopupPositionPolicy ImGuiPopupPositionPolicy = { @@ -36940,6 +42108,7 @@ ImGuiPopupPositionPolicy = Tooltip = 2 } +-- Storage for popup stacks (g.OpenPopupStack and g.BeginPopupStack) --- @class ImGuiPopupData --- @field PopupId ImGuiID --- @field Window ImGuiWindow @@ -36954,32 +42123,38 @@ ImGuiPopupPositionPolicy = --- @nodiscard function ImGuiPopupData() return { - PopupId = 0, - Window = nil, - RestoreNavWindow = nil, - ParentNavLayer = -1, - OpenFrameCount = -1, - OpenParentId = 0, - OpenPopupPos = ImVec2(), - OpenMousePos = ImVec2() + PopupId = 0, -- Set on OpenPopup() + Window = nil, -- Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() + RestoreNavWindow = nil, -- Set on OpenPopup(), a NavWindow that will be restored on popup close + ParentNavLayer = -1, -- Resolved on BeginPopup(). Actually a ImGuiNavLayer type (declared down below), initialized to -1 which is not part of an enum, but serves well-enough as "not any of layers" value + OpenFrameCount = -1, -- Set on OpenPopup() + OpenParentId = 0, -- Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) + OpenPopupPos = ImVec2(), -- Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) + OpenMousePos = ImVec2() -- Set on OpenPopup(), copy of mouse position at the time of opening popup } end --- @enum ImGuiWindowRefreshFlags ImGuiWindowRefreshFlags = { None = 0, - TryToAvoidRefresh = bitLShift(1, 0), - RefreshOnHover = bitLShift(1, 1), - RefreshOnFocus = bitLShift(1, 2) + TryToAvoidRefresh = bitLShift(1, 0), -- [EXPERIMENTAL] Try to keep existing contents, USER MUST NOT HONOR BEGIN() RETURNING FALSE AND NOT APPEND. + RefreshOnHover = bitLShift(1, 1), -- [EXPERIMENTAL] Always refresh on hover + RefreshOnFocus = bitLShift(1, 2) -- [EXPERIMENTAL] Always refresh on focus + -- Refresh policy/frequency, Load Balancing etc. } --- @enum ImGuiNavRenderCursorFlags ImGuiNavRenderCursorFlags = { None = 0, Compact = bitLShift(1, 1), -- Compact highlight, no padding/distance from focused item - AlwaysDraw = bitLShift(1, 2), -- Draw rectangular highlight if (g.NavId == id) even when g.NavCursorVisible == false, aka even when using the mouse + AlwaysDraw = bitLShift(1, 2), -- Draw rectangular highlight if (g.NavId == id) even when g.NavCursorVisible == false, aka even when using the mouse. } +------------------------------------------------------------------------------- +-- [SECTION] Metrics, Debug Tools +------------------------------------------------------------------------------- + +-- See IMGUI_DEBUG_LOG() and IMGUI_DEBUG_LOG_XXX() macros. --- @enum ImGuiDebugLogFlags ImGuiDebugLogFlags = { -- Event types @@ -36998,7 +42173,7 @@ ImGuiDebugLogFlags = { EventViewport = bitLShift(1, 11), EventTable = bitLShift(1, 12), - OutputToTTY = bitLShift(1, 20), + OutputToTTY = bitLShift(1, 20), -- Also send output to TTY OutputToDebugger = bitLShift(1, 21), OutputToTestEngine = bitLShift(1, 22), } @@ -37019,6 +42194,11 @@ ImGuiDebugLogFlags.EventMask_ = bitOr( ImGuiDebugLogFlags.EventViewport ) +------------------------------------------------------------------------------- +-- [SECTION] Localization support +------------------------------------------------------------------------------- + +-- This is experimental and not officially supported, it'll probably fall short of features, if/when it does we may backtrack. --- @enum ImGuiLocKey ImGuiLocKey = { VersionStr = 1, @@ -37057,6 +42237,7 @@ function ImGui.TempInputIsActive(id) return (g.TempInputId == id and g.ActiveId == id) or (g.InputTextDeactivatedState.ID == id) end +-- Get input text state if active --- @param id ImGuiID --- @return ImGuiInputTextState? function ImGui.GetInputTextState(id) @@ -37082,9 +42263,183 @@ end __FILES['imgui_tables.lua'] = function() --- Dear ImGui WIP --- (Tables and Columns Code) +-- (tables and columns code) -- 1:1 port of imgui_tables.cpp (docking branch, 1.93 WIP) + +-- Index of this file: -- +-- [SECTION] Commentary +-- [SECTION] Structs (port: struct constructors from imgui_internal.h / imgui.h) +-- [SECTION] Tables: Main code +-- [SECTION] Tables: Simple accessors +-- [SECTION] Tables: Row changes +-- [SECTION] Tables: Columns changes +-- [SECTION] Tables: Columns width management +-- [SECTION] Tables: Drawing +-- [SECTION] Tables: Sorting +-- [SECTION] Tables: Headers +-- [SECTION] Tables: Context Menu +-- [SECTION] Tables: Settings (.ini data) +-- [SECTION] Tables: Garbage Collection +-- [SECTION] Columns, BeginColumns, EndColumns, etc. + +------------------------------------------------------------------------------- +-- [SECTION] Commentary +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- Typical tables call flow: (root level is generally public API): +------------------------------------------------------------------------------- +-- - BeginTable() user begin into a table +-- | BeginChild() - (if ScrollX/ScrollY is set) +-- | TableBeginInitMemory() - first time table is used +-- | TableResetSettings() - on settings reset +-- | TableLoadSettings() - on settings load +------------------------------------------------------------------------------- +-- - TableSetupColumn() user submit columns details (optional) +-- - TableSetupScrollFreeze() user submit scroll freeze information (optional) +------------------------------------------------------------------------------- +-- - TableUpdateLayout() [Internal] followup to BeginTable(): setup everything: widths, columns positions, clipping rectangles. Automatically called by the FIRST call to TableNextRow() or TableHeadersRow(). +-- | TableApplyQueuedRequests() - apply queued resizing/reordering/hiding requests +-- | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame) +-- | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width +-- | - TableSetColumnDisplayOrder() - apply reordering a column +-- | TableSetupDrawChannels() - setup ImDrawList channels +-- | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission +-- | TableBeginContextMenuPopup() +-- | - TableDrawDefaultContextMenu() - draw right-click context menu contents +------------------------------------------------------------------------------- +-- - TableHeadersRow() or TableHeader() user submit a headers row (optional) +-- | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction +-- | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu +-- - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers) +-- - TableNextRow() user begin into a new row (also automatically called by TableHeadersRow()) +-- | TableEndRow() - finish existing row +-- | TableBeginRow() - add a new row +-- - TableSetColumnIndex() / TableNextColumn() user begin into a cell +-- | TableEndCell() - close existing column/cell +-- | TableBeginCell() - enter into current column/cell +-- - [...] user emit contents +------------------------------------------------------------------------------- +-- - EndTable() user ends the table +-- | TableDrawBorders() - draw outer borders, inner vertical borders +-- | TableMergeDrawChannels() - merge draw channels if clipping isn't required +-- | EndChild() - (if ScrollX/ScrollY is set) +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- TABLE SIZING +------------------------------------------------------------------------------- +-- (Read carefully because this is subtle but it does make sense!) +------------------------------------------------------------------------------- +-- About 'outer_size': +-- Its meaning needs to differ slightly depending on if we are using ScrollX/ScrollY flags. +-- Default value is ImVec2(0.0, 0.0). +-- X +-- - outer_size.x <= 0.0 -> Right-align from window/work-rect right-most edge. With -FLT_MIN or 0.0 will align exactly on right-most edge. +-- - outer_size.x > 0.0 -> Set Fixed width. +-- Y with ScrollX/ScrollY disabled: we output table directly in current window +-- - outer_size.y < 0.0 -> Bottom-align (but will auto extend, unless _NoHostExtendY is set). Not meaningful if parent window can vertically scroll. +-- - outer_size.y = 0.0 -> No minimum height (but will auto extend, unless _NoHostExtendY is set) +-- - outer_size.y > 0.0 -> Set Minimum height (but will auto extend, unless _NoHostExtendY is set) +-- Y with ScrollX/ScrollY enabled: using a child window for scrolling +-- - outer_size.y < 0.0 -> Bottom-align. Not meaningful if parent window can vertically scroll. +-- - outer_size.y = 0.0 -> Bottom-align, consistent with BeginChild(). Not recommended unless table is last item in parent window. +-- - outer_size.y > 0.0 -> Set Exact height. Recommended when using Scrolling on any axis. +------------------------------------------------------------------------------- +-- Outer size is also affected by the NoHostExtendX/NoHostExtendY flags. +-- Important to note how the two flags have slightly different behaviors! +-- - ImGuiTableFlags.NoHostExtendX -> Make outer width auto-fit to columns (overriding outer_size.x value). Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. +-- - ImGuiTableFlags.NoHostExtendY -> Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY is disabled. Data below the limit will be clipped and not visible. +-- In theory ImGuiTableFlags.NoHostExtendY could be the default and any non-scrolling tables with outer_size.y ~= 0.0 would use exact height. +-- This would be consistent but perhaps less useful and more confusing (as vertically clipped items are not useful and not easily noticeable). +------------------------------------------------------------------------------- +-- About 'inner_width': +-- With ScrollX disabled: +-- - inner_width -> *ignored* +-- With ScrollX enabled: +-- - inner_width < 0.0 -> *illegal* fit in known width (right align from outer_size.x) <-- weird +-- - inner_width = 0.0 -> fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns. +-- - inner_width > 0.0 -> override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space! +------------------------------------------------------------------------------- +-- Details: +-- - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept +-- of "available space" doesn't make sense. +-- - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding +-- of what the value does. +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- COLUMNS SIZING POLICIES +-- (Reference: ImGuiTableFlags.SizingXXX flags and ImGuiTableColumnFlags.WidthXXX flags) +------------------------------------------------------------------------------- +-- About overriding column sizing policy and width/weight with TableSetupColumn(): +-- We use a default parameter of -1 for 'init_width'/'init_weight'. +-- - with ImGuiTableColumnFlags.WidthFixed, init_width <= 0 (default) --> width is automatic +-- - with ImGuiTableColumnFlags.WidthFixed, init_width > 0 (explicit) --> width is custom +-- - with ImGuiTableColumnFlags.WidthStretch, init_weight <= 0 (default) --> weight is 1.0 +-- - with ImGuiTableColumnFlags.WidthStretch, init_weight > 0 (explicit) --> weight is custom +-- Widths are specified _without_ CellPadding. If you specify a width of 100.0, the column will be cover (100.0 + Padding * 2.0) +-- and you can fit a 100.0 wide item in it without clipping and with padding honored. +------------------------------------------------------------------------------- +-- About default sizing policy (if you don't specify a ImGuiTableColumnFlags.WidthXXXX flag) +-- - with Table policy ImGuiTableFlags.SizingFixedFit --> default Column policy is ImGuiTableColumnFlags.WidthFixed, default Width is equal to contents width +-- - with Table policy ImGuiTableFlags.SizingFixedSame --> default Column policy is ImGuiTableColumnFlags.WidthFixed, default Width is max of all contents width +-- - with Table policy ImGuiTableFlags.SizingStretchSame --> default Column policy is ImGuiTableColumnFlags.WidthStretch, default Weight is 1.0 +-- - with Table policy ImGuiTableFlags.SizingStretchWeight --> default Column policy is ImGuiTableColumnFlags.WidthStretch, default Weight is proportional to contents +-- Default Width and default Weight can be overridden when calling TableSetupColumn(). +------------------------------------------------------------------------------- +-- About mixing Fixed/Auto and Stretch columns together: +-- - the typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +-- - using mixed policies with ScrollX does not make much sense, as using Stretch columns with ScrollX does not make much sense in the first place! +-- that is, unless 'inner_width' is passed to BeginTable() to explicitly provide a total width to layout columns in. +-- - when using ImGuiTableFlags.SizingFixedSame with mixed columns, only the Fixed/Auto columns will match their widths to the width of the maximum contents. +-- - when using ImGuiTableFlags.SizingStretchSame with mixed columns, only the Stretch columns will match their weights/widths. +------------------------------------------------------------------------------- +-- About using column width: +-- If a column is manually resizable or has a width specified with TableSetupColumn(): +-- - you may use GetContentRegionAvail().x to query the width available in a given column. +-- - right-side alignment features such as SetNextItemWidth(-x) or PushItemWidth(-x) will rely on this width. +-- If the column is not resizable and has no width specified with TableSetupColumn(): +-- - its width will be automatic and be set to the max of items submitted. +-- - therefore you generally cannot have ALL items of the columns use e.g. SetNextItemWidth(-FLT_MIN). +-- - but if the column has one or more items of known/fixed size, this will become the reference width used by SetNextItemWidth(-FLT_MIN). +------------------------------------------------------------------------------- + + +------------------------------------------------------------------------------- +-- TABLES CLIPPING/CULLING +------------------------------------------------------------------------------- +-- About clipping/culling of Rows in Tables: +-- - For large numbers of rows, it is recommended you use ImGuiListClipper to submit only visible rows. +-- ImGuiListClipper is reliant on the fact that rows are of equal height. +-- See 'Demo->Tables->Vertical Scrolling' or 'Demo->Tables->Advanced' for a demo of using the clipper. +-- - Note that auto-resizing columns don't play well with using the clipper. +-- By default a table with _ScrollX but without _Resizable will have column auto-resize. +-- So, if you want to use the clipper, make sure to either enable _Resizable, either setup columns width explicitly with _WidthFixed. +------------------------------------------------------------------------------- +-- About clipping/culling of Columns in Tables: +-- - Both TableSetColumnIndex() and TableNextColumn() return true when the column is visible or performing +-- width measurements. Otherwise, you may skip submitting the contents of a cell/column, BUT ONLY if you know +-- it is not going to contribute to row height. +-- In many situations, you may skip submitting contents for every column but one (e.g. the first one). +-- - Case A: column is not hidden by user, and at least partially in sight (most common case). +-- - Case B: column is clipped / out of sight (because of scrolling or parent ClipRect): TableNextColumn() return false as a hint but we still allow layout output. +-- - Case C: column is hidden explicitly by the user (e.g. via the context menu, or _DefaultHide column flag, etc.). +-- +-- [A] [B] [C] +-- TableNextColumn(): true false false -> [userland] when TableNextColumn() / TableSetColumnIndex() returns false, user can skip submitting items but only if the column doesn't contribute to row height. +-- SkipItems: false false true -> [internal] when SkipItems is true, most widgets will early out if submitted, resulting is no layout output. +-- ClipRect: normal zero-width zero-width -> [internal] when ClipRect is zero, ItemAdd() will return false and most widgets will early out mid-way. +-- ImDrawList output: normal dummy dummy -> [internal] when using the dummy channel, ImDrawList submissions (if any) will be wasted (because cliprect is zero-width anyway). +-- +-- - We need to distinguish those cases because non-hidden columns that are clipped outside of scrolling bounds should still contribute their height to the row. +-- However, in the majority of cases, the contribution to row height is the same for all columns, or the tallest cells are known by the programmer. +------------------------------------------------------------------------------- +-- About clipping/culling of whole Tables: +-- - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false. +------------------------------------------------------------------------------- + -- Port notes: -- - Column indices / display orders / draw channel indices are 0-based VALUES like upstream. -- Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys. @@ -37110,32 +42465,40 @@ end local bit32 = bit32 local band, bor, bnot, lshift, rshift = bit32.band, bit32.bor, bit32.bnot, bit32.lshift, bit32.rshift -IM_COL32_DISABLE = IM_COL32(0, 0, 0, 1) -IMGUI_TABLE_MAX_COLUMNS = 512 +IM_COL32_DISABLE = IM_COL32(0, 0, 0, 1) -- Special sentinel code which cannot be used as a regular color. +IMGUI_TABLE_MAX_COLUMNS = 512 -- Arbitrary "safety" maximum, may be lifted in the future if needed. Must fit in ImGuiTableColumnIdx/ImGuiTableDrawChannelIdx. local function IMGUI_DEBUG_LOG_TABLE(fmt, ...) local g = GImGui if band(g.DebugLogFlags, ImGuiDebugLogFlags.EventTable) ~= 0 then ImGui.DebugLog(fmt, ...) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Structs ----------------------------------------------------------------- +------------------------------------------------------------------------------- local function BitArrayClearAll(arr) table.clear(arr) end local function BitArraySet(arr, n) arr[n] = true end local function BitTest(arr, n) return arr[n] == true end +-- Sorting specification for one column of a table --- @class ImGuiTableColumnSortSpecs function ImGuiTableColumnSortSpecs() return { ColumnUserID = 0, ColumnIndex = 0, SortOrder = 0, SortDirection = ImGuiSortDirection.None } end +-- Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +-- Obtained by calling TableGetSortSpecs(). +-- When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. +-- Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! --- @class ImGuiTableSortSpecs function ImGuiTableSortSpecs() return { Specs = nil, SpecsCount = 0, SpecsDirty = false } end +-- We use the terminology "Enabled" to refer to a column that is not Hidden by user/api. +-- We use the terminology "Clipped" to refer to a column that is out of sight because of scrolling/clipping. +-- This is in contrast with some user-facing api such as IsItemVisible() / IsRectVisible() which use "Visible" to mean "not clipped". --- @class ImGuiTableColumn function ImGuiTableColumn() return { @@ -37166,11 +42529,16 @@ local function TableColumnClone(src) return TableColumnCopy(ImGuiTableColumn(), src) end +-- Per-instance data that needs preserving across frames (seemingly most others do not need to be preserved aside from debug needs. Does that means they could be moved to ImGuiTableTempData?) --- @class ImGuiTableInstanceData function ImGuiTableInstanceData() return { TableInstanceID = 0, LastOuterHeight = 0.0, LastTopHeadersRowHeight = 0.0, LastFrozenHeight = 0.0, HoveredRowLast = -1, HoveredRowNext = -1 } end +-- Transient data that are only needed between BeginTable() and EndTable(), those buffers are shared (1 per level of stacked table). +-- - Accessing those requires chasing an extra pointer so for very frequently used data we leave them in the main table structure. +-- - We also leave out of this structure data that tend to be particularly useful for debugging/metrics. +-- FIXME-TABLE: more transient data could be stored in a stacked ImGuiTableTempData: e.g. SortSpecs. --- @class ImGuiTableTempData function ImGuiTableTempData() return { @@ -37184,6 +42552,7 @@ function ImGuiTableTempData() } end +-- Storage for a table --- @class ImGuiTable function ImGuiTable() return { @@ -37223,11 +42592,13 @@ function ImGuiTableColumnSettings() IsEnabled = -1, IsStretch = 0, IsLoaded = false } end +-- Storage for a table .ini settings --- @class ImGuiTableSettings function ImGuiTableSettings() return { ID = 0, SaveFlags = 0, RefScale = 0.0, ColumnsCount = 0, ColumnsCountMax = 0, LastUsedDate = 0, WantApply = false, Columns = {} } end +-- Storage data for a single column for legacy Columns() api --- @class ImGuiOldColumnData function ImGuiOldColumnData() return { OffsetNorm = 0.0, OffsetNormBeforeResize = 0.0, Flags = 0, ClipRect = ImRect() } @@ -37240,28 +42611,42 @@ function ImGuiOldColumns() HostBackupClipRect = ImRect(), HostBackupParentWorkRect = ImRect(), Columns = ImVector(), Splitter = ImDrawListSplitter() } end +-- Flags for internal's BeginColumns(). This is an obsolete API. Prefer using BeginTable() nowadays! ImGuiOldColumnFlags = ImGuiOldColumnFlags or { None = 0, - NoBorder = lshift(1, 0), - NoResize = lshift(1, 1), - NoPreserveWidths = lshift(1, 2), - NoForceWithinWindow = lshift(1, 3), - GrowParentContentsSize = lshift(1, 4), + NoBorder = lshift(1, 0), -- Disable column dividers + NoResize = lshift(1, 1), -- Disable resizing columns when clicking on the dividers + NoPreserveWidths = lshift(1, 2), -- Disable column width preservation when adjusting columns + NoForceWithinWindow = lshift(1, 3), -- Disable forcing columns to fit within window + GrowParentContentsSize = lshift(1, 4), -- Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. } -ImGuiTableColumnFlags.NoDirectResize_ = ImGuiTableColumnFlags.NoDirectResize_ or lshift(1, 30) +ImGuiTableColumnFlags.NoDirectResize_ = ImGuiTableColumnFlags.NoDirectResize_ or lshift(1, 30) -- [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) local function Rect(r) return ImRect(r.Min.x, r.Min.y, r.Max.x, r.Max.y) end local function V2(v) return ImVec2(v.x, v.y) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Main code ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableFixFlags() [Internal] +-- - TableFindByID() [Internal] +-- - BeginTable() +-- - BeginTableEx() [Internal] +-- - TableBeginInitMemory() [Internal] +-- - TableApplyQueuedRequests() [Internal] +-- - TableSetupColumnFlags() [Internal] +-- - TableUpdateLayout() [Internal] +-- - TableUpdateBorders() [Internal] +-- - EndTable() +-- - TableSetupColumn() +-- - TableSetupScrollFreeze() +------------------------------------------------------------------------------- -- Configuration local TABLE_DRAW_CHANNEL_BG0 = 0 local TABLE_DRAW_CHANNEL_BG2_FROZEN = 1 -local TABLE_DRAW_CHANNEL_NOCLIP = 2 -- When using ImGuiTableFlags_NoClip (this becomes the last visible channel) +local TABLE_DRAW_CHANNEL_NOCLIP = 2 -- When using ImGuiTableFlags.NoClip (this becomes the last visible channel) local TABLE_BORDER_SIZE = 1.0 -- FIXME-TABLE: Currently hard-coded because of clipping assumptions with outer borders rendering. local TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0 -- Extend outside inner borders. local TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06 -- Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped. @@ -37273,7 +42658,7 @@ local function TableFixFlags(flags, outer_window) flags = bor(flags, (band(flags, ImGuiTableFlags.ScrollX) ~= 0 or band(outer_window.Flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0) and ImGuiTableFlags.SizingFixedFit or ImGuiTableFlags.SizingStretchSame) end - -- Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags_SizingFixedSame + -- Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags.SizingFixedSame if band(flags, ImGuiTableFlags.SizingMask_) == ImGuiTableFlags.SizingFixedSame then flags = bor(flags, ImGuiTableFlags.NoKeepColumnsVisible) end @@ -37353,6 +42738,12 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi end -- If an outer size is specified ahead we will be able to early out when not visible. Exact clipping criteria may evolve. + -- FIXME: coarse clipping because access to table data causes two issues: + -- - instance numbers varying/unstable. may not be a direct problem for users, but could make outside access broken or confusing, e.g. TestEngine. + -- - can't implement support for ImGuiChildFlags.ResizeY as we need to somehow pull the height data from somewhere. this also needs stable instance numbers. + -- The side-effects of accessing table data on coarse clip would be: + -- - always reserving the pooled ImGuiTable data ahead for a fully clipped table (minor IMHO). Also the 'outer_window_is_measuring_size' criteria may already be defeating this in some situations. + -- - always performing the GetOrAddByKey() O(log N) query in g.Tables.Map[]. local use_child_window = band(flags, bor(ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY)) ~= 0 local avail_size = ImGui.GetContentRegionAvail() local actual_outer_size = ImTrunc(ImGui.CalcItemSize(outer_size, ImMax(avail_size.x, IMGUI_WINDOW_HARD_MIN_SIZE), use_child_window and ImMax(avail_size.y, IMGUI_WINDOW_HARD_MIN_SIZE) or 0.0)) @@ -37380,7 +42771,7 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi local temp_data = g.TablesTempData.Data[g.TablesTempDataStacked] table_.TempData = temp_data temp_data.TableIndex = table_idx - temp_data.ReconcileColumnsRequests:resize(0) + temp_data.ReconcileColumnsRequests:resize(0) -- FIXME: Use shrink(0) everywhere? table_.DrawSplitter = table_.TempData.DrawSplitter table_.DrawSplitter:Clear() @@ -37422,12 +42813,16 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi -- When not using a child window, WorkRect.Max will grow as we append contents. if use_child_window then -- Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent + -- (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing) local override_content_size = ImVec2(FLT_MAX, FLT_MAX) if band(flags, ImGuiTableFlags.ScrollX) ~= 0 and band(flags, ImGuiTableFlags.ScrollY) == 0 then override_content_size.y = FLT_MIN end - -- Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and never lead to any scrolling). + -- Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and + -- never lead to any scrolling). We don't handle inner_width < 0.0, we could potentially use it to right-align + -- based on the right side of the child window work rect, which would require knowing ahead if we are going to + -- have decoration taking horizontal spaces (typically a vertical scrollbar). if band(flags, ImGuiTableFlags.ScrollX) ~= 0 and inner_width > 0.0 then override_content_size.x = inner_width end @@ -37465,18 +42860,19 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi table_.HasScrollbarYCurr = table_.HasScrollbarYCurr or table_.InnerWindow.ScrollbarY else -- For non-scrolling tables, WorkRect == OuterRect == InnerRect. + -- But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable(). ImRect_Copy(table_.WorkRect, outer_rect) ImRect_Copy(table_.OuterRect, outer_rect) ImRect_Copy(table_.InnerRect, outer_rect) table_.HasScrollbarYPrev = false table_.HasScrollbarYCurr = false - table_.InnerWindow.DC.TreeDepth = table_.InnerWindow.DC.TreeDepth + 1 -- This is designed to always linking ImGuiTreeNodeFlags_DrawLines linking across a table + table_.InnerWindow.DC.TreeDepth = table_.InnerWindow.DC.TreeDepth + 1 -- This is designed to always linking ImGuiTreeNodeFlags.DrawLines linking across a table end -- Push a standardized ID for both child-using and not-child-using tables ImGui.PushOverrideID(id) if instance_no > 0 then - ImGui.PushOverrideID(instance_id) + ImGui.PushOverrideID(instance_id) -- FIXME: Somehow this is not resolved by stack-tool, even tho GetIDWithSeed() submitted the symbol. end -- Backup a copy of host window members we will modify @@ -37497,7 +42893,13 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi inner_window.DC.CurrLineSize.x = 0.0; inner_window.DC.CurrLineSize.y = 0.0 -- Make borders not overlap our contents by offsetting HostClipRect (#6765, #7428, #3752) + -- (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the + -- limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap + -- problem only affect scrolling tables in this case we can get away with doing it without extra cost). if inner_window ~= outer_window then + -- FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window.WindowBorderSize, + -- it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with + -- different x/y values to BeginChild(). local border_size = TABLE_BORDER_SIZE if band(flags, ImGuiTableFlags.BordersOuterV) ~= 0 then table_.HostClipRect.Min.x = ImMin(table_.HostClipRect.Min.x + border_size, table_.HostClipRect.Max.x) @@ -37514,6 +42916,10 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi end -- Padding and Spacing + -- - None ........Content..... Pad .....Content........ + -- - PadOuter | Pad ..Content..... Pad .....Content.. Pad | + -- - PadInner ........Content.. Pad | Pad ..Content........ + -- - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad | local pad_outer_x if band(flags, ImGuiTableFlags.NoPadOuterX) ~= 0 then pad_outer_x = false elseif band(flags, ImGuiTableFlags.PadOuterX) ~= 0 then pad_outer_x = true @@ -37634,9 +43040,12 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi end -- Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call.. + -- This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user. + -- Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. inner_window.SkipItems = true -- Clear names + -- At this point the .NameOffset field of each column will be invalid until TableUpdateLayout() or the first call to TableSetupColumn() if #table_.ColumnsNames > 0 then table.clear(table_.ColumnsNames) end @@ -37664,6 +43073,8 @@ end -- Apply queued resizing/reordering/hiding requests function ImGui.TableApplyQueuedRequests(table_) -- Handle resizing request + -- (We process this in the TableBegin() of the first instance of each table) + -- FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling? if table_.InstanceCurrent == 0 then if table_.ResizedColumn ~= -1 and table_.ResizedColumnNextWidth ~= FLT_MAX then ImGui.TableSetColumnWidth(table_.ResizedColumn, table_.ResizedColumnNextWidth) @@ -37673,6 +43084,7 @@ function ImGui.TableApplyQueuedRequests(table_) table_.ResizedColumn = -1 -- Process auto-fit for single column, which is a special case for stretch columns and fixed columns with FixedSame policy. + -- FIXME-TABLE: Would be nice to redistribute available stretch space accordingly to other weights, instead of giving it all to siblings. if table_.AutoFitSingleColumn ~= -1 then ImGui.TableSetColumnWidth(table_.AutoFitSingleColumn, table_.Columns[table_.AutoFitSingleColumn].WidthAuto) table_.AutoFitSingleColumn = -1 @@ -37680,6 +43092,7 @@ function ImGui.TableApplyQueuedRequests(table_) end -- Handle reordering request + -- Note: we don't clear ReorderColumn after handling the request (FIXME: clarify why or add a test). if table_.InstanceCurrent == 0 then table_.LastHeldHeaderColumn = table_.HeldHeaderColumn table_.HeldHeaderColumn = -1 @@ -37693,6 +43106,8 @@ function ImGui.TableApplyQueuedRequests(table_) if g.ActiveId == 0 then -- FIXME: Need to revisit. See 38f5e5a. table_.ReorderColumn = -1 end + --if (table.HeldHeaderColumn == -1 and table.ReorderColumn ~= -1) + -- table.ReorderColumn = -1 end -- Handle display order / visibility reset requests @@ -37734,8 +43149,10 @@ function ImGui.TableSetColumnDisplayOrder(table_, column_n, dst_order) c.DisplayOrder = c.DisplayOrder - reorder_dir order_n = order_n + reorder_dir end + --IM_ASSERT(dst_column.DisplayOrder == dst_order - reorder_dir) - -- Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[]. Rebuild later from the former. + -- Display order is stored in both columns.IndexDisplayOrder and table.DisplayOrder[]. Rebuild later from the former. + -- FIXME-OPT: If this is called multiple times we'd effectively have a O(N^2) thing going on. for n = 0, table_.ColumnsCount - 1 do table_.DisplayOrderToIndex[table_.Columns[n].DisplayOrder] = n end @@ -37749,11 +43166,12 @@ local function TableGetMaxDisplayOrderAllowed(table_, src_order, dst_order) end -- Cannot cross over the frozen column limit when interactively reordering. + -- TableSetupScrollFreeze() enforce a display order range for frozen columns. Reordering across the frozen column barrier is illegal and will be undone. if table_.FreezeColumnsRequest > 0 then dst_order = (src_order < table_.FreezeColumnsRequest) and ImMin(dst_order, table_.FreezeColumnsRequest - 1) or ImMax(dst_order, table_.FreezeColumnsRequest) end - -- Cannot cross over a column with the ImGuiTableColumnFlags_NoReorder flag. + -- Cannot cross over a column with the ImGuiTableColumnFlags.NoReorder flag. local reorder_dir = (src_order < dst_order) and 1 or -1 local order_n = src_order while (src_order < dst_order and order_n <= dst_order) or (dst_order < src_order and order_n >= dst_order) do @@ -37809,6 +43227,11 @@ local function TableSetupColumnFlags(table_, column, column_n, flags_in) flags = bor(flags, (column_n == 0) and ImGuiTableColumnFlags.IndentEnable or ImGuiTableColumnFlags.IndentDisable) end + -- Alignment + --if (flags & ImGuiTableColumnFlags.AlignMask_) == 0 then + -- flags = bor(flags, ImGuiTableColumnFlags.AlignCenter) + --IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags.AlignMask_)) -- Check that only 1 of each set is used. + -- Preserve status flags column.Flags = bor(flags, band(column.Flags, ImGuiTableColumnFlags.StatusMask_)) @@ -37831,6 +43254,8 @@ end -- Layout columns for the frame. This is in essence the followup to BeginTable() and this is our largest function. -- Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() and other TableSetupXXXXX() functions to be called first. +-- FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns. +-- Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns? function ImGui.TableUpdateLayout(table_) local g = GImGui local temp_data = table_.TempData @@ -37870,7 +43295,11 @@ function ImGui.TableUpdateLayout(table_) ImGui.TableApplyQueuedRequests(table_) -- Handle DPI/font resize - local new_ref_scale_unit = g.FontSize + -- This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well. + -- It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition. + -- FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory. + -- This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path. + local new_ref_scale_unit = g.FontSize -- g.Font.GetCharAdvance('A') ? if table_.RefScale ~= 0.0 and table_.RefScale ~= new_ref_scale_unit then local scale_factor = new_ref_scale_unit / table_.RefScale for n = 0, columns_count - 1 do @@ -37885,11 +43314,12 @@ function ImGui.TableUpdateLayout(table_) BitArrayClearAll(table_.EnabledMaskByIndex) BitArrayClearAll(table_.EnabledMaskByDisplayOrder) table_.LeftMostEnabledColumn = -1 - table_.MinColumnWidth = ImMax(1.0, g.Style.FramePadding.x * 1.0) -- g.Style.ColumnsMinSpacing; // FIXME-TABLE + table_.MinColumnWidth = ImMax(1.0, g.Style.FramePadding.x * 1.0) -- g.Style.ColumnsMinSpacing -- FIXME-TABLE -- [Part 1] Apply/lock Enabled and Order states. Calculate auto/ideal width for columns. Count fixed/stretch columns. - local count_fixed = 0 - local count_stretch = 0 + -- Process columns in their visible orders as we are building the Prev/Next indices. + local count_fixed = 0 -- Number of columns that have fixed sizing policies + local count_stretch = 0 -- Number of columns that have stretch sizing policies local prev_visible_column_idx = -1 local has_auto_fit_request = false local has_resizable = false @@ -37900,6 +43330,8 @@ function ImGui.TableUpdateLayout(table_) local column = table_.Columns[column_n] -- Clear column setup if not submitted by user. Currently we make it mandatory to call TableSetupColumn() every frame. + -- It would easily work without but we're not ready to guarantee it since e.g. names need resubmission anyway. + -- We take a slight shortcut but in theory we could be calling TableSetupColumn() here with dummy values, it should yield the same effect. if table_.DeclColumnsCount <= column_n then TableSetupColumnFlags(table_, column, column_n, ImGuiTableColumnFlags.None) column.NameOffset = -1 @@ -37963,6 +43395,7 @@ function ImGui.TableUpdateLayout(table_) IM_ASSERT(column.IndexWithinEnabledSet <= column.DisplayOrder) -- Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping) + -- Combine width from regular rows + width from headers unless requested not to. if not column.IsPreserveWidthAuto and table_.InstanceCurrent == 0 then column.WidthAuto = ImGui.TableGetColumnWidthAuto(table_, column) end @@ -37994,7 +43427,9 @@ function ImGui.TableUpdateLayout(table_) table_.RightMostEnabledColumn = prev_visible_column_idx IM_ASSERT(table_.LeftMostEnabledColumn >= 0 and table_.RightMostEnabledColumn >= 0) - -- [Part 2] Disable child window clipping while fitting columns. + -- [Part 2] Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid + -- the column fitting having to wait until the first visible frame of the child container (may or not be a good thing). Also see #6510. + -- FIXME-TABLE: for always auto-resizing columns may not want to do that all the time. if has_auto_fit_request and table_.OuterWindow ~= table_.InnerWindow then table_.InnerWindow.SkipItems = false end @@ -38003,8 +43438,8 @@ function ImGui.TableUpdateLayout(table_) end -- [Part 3] Fix column flags and record a few extra information. - local sum_width_requests = 0.0 - local stretch_sum_weights = 0.0 + local sum_width_requests = 0.0 -- Sum of all width for fixed and auto-resize columns, excluding width contributed by Stretch columns but including spacing/padding. + local stretch_sum_weights = 0.0 -- Sum of all weights for stretch columns. table_.LeftMostStretchedColumn = -1; table_.RightMostStretchedColumn = -1 for column_n = 0, columns_count - 1 do if BitTest(table_.EnabledMaskByIndex, column_n) then @@ -38019,6 +43454,7 @@ function ImGui.TableUpdateLayout(table_) end -- Apply automatic width + -- Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!) if column.AutoFitQueue ~= 0x00 then column.WidthRequest = width_auto elseif band(column.Flags, ImGuiTableColumnFlags.WidthFixed) ~= 0 and not column_is_resizable and column.IsRequestOutput then @@ -38026,6 +43462,11 @@ function ImGui.TableUpdateLayout(table_) end -- FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets + -- (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very + -- large height (= first frame scrollbar display very off + clipper would skip lots of items). + -- This is merely making the side-effect less extreme, but doesn't properly fixes it. + -- FIXME: Move this to .WidthGiven to avoid temporary lossyness? + -- FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller. if column.AutoFitQueue > 0x01 and table_.IsInitializing and not column.IsPreserveWidthAuto then column.WidthRequest = ImMax(column.WidthRequest, table_.MinColumnWidth * 4.0) -- FIXME-TABLE: Another constant/scale? end @@ -38077,6 +43518,7 @@ function ImGui.TableUpdateLayout(table_) end -- [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column + -- See additional comments in TableSetColumnWidth(). if column.NextEnabledColumn == -1 and table_.LeftMostStretchedColumn ~= -1 then column.Flags = bor(column.Flags, ImGuiTableColumnFlags.NoDirectResize_) end @@ -38087,7 +43529,8 @@ function ImGui.TableUpdateLayout(table_) end end - -- [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0f * number of Stretch column). + -- [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0 * number of Stretch column). + -- Using right-to-left distribution (more likely to match resizing cursor). if width_remaining_for_stretched_columns >= 1.0 and band(table_.Flags, ImGuiTableFlags.PreciseWidths) == 0 then local order_n = columns_count - 1 while stretch_sum_weights > 0.0 and width_remaining_for_stretched_columns >= 1.0 and order_n >= 0 do @@ -38104,6 +43547,10 @@ function ImGui.TableUpdateLayout(table_) end -- Determine if table is hovered which will be used to flag columns as hovered. + -- - In principle we'd like to use the equivalent of IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem), + -- but because our item is partially submitted at this point we use ItemHoverable() and a workaround (temporarily + -- clear ActiveId, which is equivalent to the change provided by _AllowWhenBLockedByActiveItem). + -- - This allows columns to be marked as hovered when e.g. clicking a button inside the column, or using drag and drop. local table_instance = ImGui.TableGetInstanceData(table_, table_.InstanceCurrent) table_instance.HoveredRowLast = table_instance.HoveredRowNext table_instance.HoveredRowNext = -1 @@ -38123,10 +43570,12 @@ function ImGui.TableUpdateLayout(table_) end -- [Part 6] Setup final position, offset, skip/clip states and clipping rectangles, detect hovered column + -- Process columns in their visible orders as we are comparing the visible order and adjusting host_clip_rect while looping. local has_at_least_one_column_requesting_output = false local offset_x_frozen = (table_.FreezeColumnsCount > 0) local offset_x = ((table_.FreezeColumnsCount > 0) and table_.OuterRect.Min.x or work_rect.Min.x) + table_.OuterPaddingX - table_.CellSpacingX1 local host_clip_rect = Rect(table_.InnerClipRect) + --host_clip_rect.Max.x += table.CellPaddingX + table.CellSpacingX2 BitArrayClearAll(table_.VisibleMaskByIndex) for order_n = 0, columns_count - 1 do local column_n = table_.DisplayOrderToIndex[order_n] @@ -38145,6 +43594,7 @@ function ImGui.TableUpdateLayout(table_) if not BitTest(table_.EnabledMaskByDisplayOrder, order_n) then -- Hidden column: clear a few fields and we are done with it for the remainder of the function. + -- We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper. column.MinX = offset_x; column.MaxX = offset_x; column.WorkMinX = offset_x column.ClipRect.Min.x = offset_x; column.ClipRect.Max.x = offset_x column.WidthGiven = 0.0 @@ -38165,20 +43615,30 @@ function ImGui.TableUpdateLayout(table_) column.MaxX = offset_x + column.WidthGiven + table_.CellSpacingX1 + table_.CellSpacingX2 + table_.CellPaddingX * 2.0 -- Lock other positions + -- - ClipRect.Min.x: Because merging draw commands doesn't compare min boundaries, we make ClipRect.Min.x match left bounds to be consistent regardless of merging. + -- - ClipRect.Max.x: using WorkMaxX instead of MaxX (aka including padding) makes things more consistent when resizing down, tho slightly detrimental to visibility in very-small column. + -- - ClipRect.Max.x: using MaxX makes it easier for header to receive hover highlight with no discontinuity and display sorting arrow. + -- - FIXME-TABLE: We want equal width columns to have equal (ClipRect.Max.x - WorkMinX) width, which means ClipRect.max.x cannot stray off host_clip_rect.Max.x else right-most column may appear shorter. local previous_instance_work_min_x = column.WorkMinX column.WorkMinX = column.MinX + table_.CellPaddingX + table_.CellSpacingX1 column.WorkMaxX = column.MaxX - table_.CellPaddingX - table_.CellSpacingX2 -- Expected max column.ItemWidth = ImTrunc(column.WidthGiven * 0.65) column.ClipRect.Min.x = column.MinX column.ClipRect.Min.y = work_rect.Min.y - column.ClipRect.Max.x = column.MaxX --column->WorkMaxX; + column.ClipRect.Max.x = column.MaxX --column.WorkMaxX column.ClipRect.Max.y = FLT_MAX column.ClipRect:ClipWithFull(host_clip_rect) -- Mark column as Clipped (not in sight) + -- Note that scrolling tables (where inner_window ~= outer_window) handle Y clipped earlier in BeginTable() so IsVisibleY really only applies to non-scrolling tables. + -- FIXME-TABLE: Because InnerClipRect.Max.y is conservatively ==outer_window.ClipRect.Max.y, we never can mark columns _Above_ the scroll line as not IsVisibleY. + -- Taking advantage of LastOuterHeight would yield good results there... + -- FIXME-TABLE: Y clipping is disabled because it effectively means not submitting will reduce contents width which is fed to outer_window.DC.CursorMaxPos.x, + -- and this may be used (e.g. typically by outer_window using AlwaysAutoResize or outer_window's horizontal scrollbar, but could be something else). + -- Possible solution to preserve last known content width for clipped column. Test 'table_reported_size' fails when enabling Y clipping and window is resized small. column.IsVisibleX = (column.ClipRect.Max.x > column.ClipRect.Min.x) - column.IsVisibleY = true -- (column->ClipRect.Max.y > column->ClipRect.Min.y); - local is_visible = column.IsVisibleX --&& column->IsVisibleY; + column.IsVisibleY = true -- (column.ClipRect.Max.y > column.ClipRect.Min.y) + local is_visible = column.IsVisibleX --and column.IsVisibleY if is_visible then BitArraySet(table_.VisibleMaskByIndex, column_n) end @@ -38187,6 +43647,7 @@ function ImGui.TableUpdateLayout(table_) column.IsRequestOutput = is_visible or column.AutoFitQueue ~= 0 or column.CannotSkipItemsQueue ~= 0 -- Mark column as SkipItems (ignoring all items/layout) + -- (table.HostSkipItems is a copy of inner_window.SkipItems before we cleared it above in Part 2) column.IsSkipItems = not column.IsEnabled or table_.HostSkipItems if column.IsSkipItems then IM_ASSERT(not is_visible) @@ -38210,6 +43671,15 @@ function ImGui.TableUpdateLayout(table_) table_.HoveredColumnBody = column_n end + -- Alignment + -- FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in + -- many cases (to be able to honor this we might be able to store a log of cells width, per row, for + -- visible rows, but nav/programmatic scroll would have visible artifacts.) + --if (column.Flags & ImGuiTableColumnFlags.AlignRight) + -- column.WorkMinX = ImMax(column.WorkMinX, column.MaxX - column.ContentWidthRowsUnfrozen) + --else if (column.Flags & ImGuiTableColumnFlags.AlignCenter) + -- column.WorkMinX = ImLerp(column.WorkMinX, ImMax(column.StartX, column.MaxX - column.ContentWidthRowsUnfrozen), 0.5) + -- Reset content width variables if table_.InstanceCurrent == 0 then column.ContentMaxXFrozen = column.WorkMinX @@ -38240,12 +43710,15 @@ function ImGui.TableUpdateLayout(table_) end -- In case the table is visible (e.g. decorations) but all columns clipped, we keep a column visible. + -- Else if give no chance to a clipper-savvy user to submit rows and therefore total contents height used by scrollbar. if has_at_least_one_column_requesting_output == false then table_.Columns[table_.LeftMostEnabledColumn].IsRequestOutput = true table_.Columns[table_.LeftMostEnabledColumn].IsSkipItems = false end -- [Part 7] Detect/store when we are hovering the unused space after the right-most column (so e.g. context menus can react on it) + -- Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either + -- because of using _WidthAuto/_WidthStretch). This will hide the resizing option from the context menu. local unused_x1 = ImMax(table_.WorkRect.Min.x, table_.Columns[table_.RightMostEnabledColumn].ClipRect.Max.x) if is_hovering_table and table_.HoveredColumnBody == -1 then if mouse_skewed_x >= unused_x1 then @@ -38259,6 +43732,8 @@ function ImGui.TableUpdateLayout(table_) table_.IsActiveIdAliveBeforeTable = (g.ActiveIdIsAlive ~= 0) -- [Part 8] Lock actual OuterRect/WorkRect right-most position. + -- This is done late to handle the case of fixed-columns tables not claiming more widths that they need. + -- Because of this we are careful with uses of WorkRect and InnerClipRect before this point. if table_.RightMostStretchedColumn ~= -1 then table_.Flags = band(table_.Flags, bnot(ImGuiTableFlags.NoHostExtendX)) end @@ -38301,12 +43776,17 @@ function ImGui.TableUpdateLayout(table_) end -- [Part 11] Default context menu + -- - To append to this menu: you can 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 and ImGui.TableBeginContextMenuPopup(table_) then ImGui.TableDrawDefaultContextMenu(table_, table_.Flags) ImGui.EndPopup() end -- [Part 12] Sanitize and build sort specs before we have a chance to use them for display. + -- This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change) if table_.IsSortSpecsDirty and band(table_.Flags, ImGuiTableFlags.Sortable) ~= 0 then ImGui.TableSortSpecsBuild(table_) end @@ -38330,7 +43810,7 @@ function ImGui.TableUpdateLayout(table_) if band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0 then table_.DrawSplitter:SetCurrentChannel(inner_window.DrawList, TABLE_DRAW_CHANNEL_NOCLIP) else - inner_window.DrawList:PushClipRect(inner_window.InnerClipRect.Min, inner_window.InnerClipRect.Max, false) -- FIXME: use table->InnerClipRect? + inner_window.DrawList:PushClipRect(inner_window.InnerClipRect.Min, inner_window.InnerClipRect.Max, false) -- FIXME: use table.InnerClipRect? end end @@ -38350,10 +43830,15 @@ function ImGui.TableApplyExternalUnclipRect(table_, rect) end -- Process hit-testing on resizing borders. Actual size change will be applied in EndTable() +-- - Set table.HoveredColumnBorder with a short delay/timer to reduce visual feedback noise. function ImGui.TableUpdateBorders(table_) local g = GImGui IM_ASSERT(band(table_.Flags, ImGuiTableFlags.Resizable) ~= 0) + -- At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and + -- use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not + -- really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height). + -- Actual columns highlight/render will be performed in EndTable() and not be affected. local table_instance = ImGui.TableGetInstanceData(table_, table_.InstanceCurrent) local hit_half_width = ImTrunc(TABLE_RESIZE_SEPARATOR_HALF_THICKNESS * g.CurrentDpiScale) local hit_y1 = ((table_.FreezeRowsCount >= 1) and table_.OuterRect.Min.y or table_.WorkRect.Min.y) + table_.AngledHeadersHeight @@ -38372,7 +43857,7 @@ function ImGui.TableUpdateBorders(table_) break end - -- ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders() + -- ImGuiTableFlags.NoBordersInBodyUntilResize will be honored in TableDrawBorders() local border_y2_hit = (band(table_.Flags, ImGuiTableFlags.NoBordersInBody) ~= 0) and hit_y2_head or hit_y2_body if band(table_.Flags, ImGuiTableFlags.NoBordersInBody) ~= 0 and table_.IsUsingHeaders == false then break @@ -38385,6 +43870,7 @@ function ImGui.TableUpdateBorders(table_) local column_id = ImGui.TableGetColumnResizeID(table_, column_n, table_.InstanceCurrent) local hit_rect = ImRect(column.MaxX - hit_half_width, hit_y1, column.MaxX + hit_half_width, border_y2_hit) ImGui.ItemAdd(hit_rect, column_id, nil, ImGuiItemFlags.NoNav) + --ImGui.GetForegroundDrawList():AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100)) local pressed, hovered, held = ImGui.ButtonBehavior(hit_rect, column_id, bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.PressedOnClick, ImGuiButtonFlags.PressedOnDoubleClick, ImGuiButtonFlags.NoNavFocus)) if pressed and ImGui.IsMouseDoubleClicked(0) then @@ -38412,7 +43898,12 @@ function ImGui.EndTable() local table_ = g.CurrentTable IM_ASSERT_USER_ERROR_RET(table_ ~= nil, "EndTable() call should only be done while in BeginTable() scope!") - -- If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves. + -- This assert would be very useful to catch a common error... unfortunately it would probably trigger in some + -- cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) + --IM_ASSERT(table.IsLayoutLocked, "Table unused: never called TableNextRow(), is that the intent?") + + -- If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our + -- code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc. if not table_.IsLayoutLocked then ImGui.TableUpdateLayout(table_) end @@ -38440,7 +43931,7 @@ function ImGui.EndTable() ImVec2_Copy(inner_window.DC.PrevLineSize, temp_data.HostBackupPrevLineSize) ImVec2_Copy(inner_window.DC.CurrLineSize, temp_data.HostBackupCurrLineSize) ImVec2_Copy(inner_window.DC.CursorMaxPos, temp_data.HostBackupCursorMaxPos) - local inner_content_max_y = ImCeil(table_.RowPosY2) -- Rounding final position is important as we currently don't round row height + local inner_content_max_y = ImCeil(table_.RowPosY2) -- Rounding final position is important as we currently don't round row height ('Demo->Tables->Outer Size' demo uses non-integer heights) IM_ASSERT(table_.RowPosY2 == inner_window.DC.CursorPos.y) if inner_window ~= outer_window then inner_window.DC.CursorMaxPos.y = inner_content_max_y @@ -38452,6 +43943,8 @@ function ImGui.EndTable() table_instance.LastOuterHeight = table_.OuterRect:GetHeight() -- Setup inner scrolling range + -- FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window.DC.CursorMaxPos.y, + -- but since the later is likely to be impossible to do we'd rather update both axes together. if band(table_.Flags, ImGuiTableFlags.ScrollX) ~= 0 then local outer_padding_for_border = (band(table_.Flags, ImGuiTableFlags.BordersOuterV) ~= 0) and TABLE_BORDER_SIZE or 0.0 local max_pos_x = inner_window.DC.CursorMaxPos.x @@ -38552,6 +44045,8 @@ function ImGui.EndTable() outer_window.DC.ColumnsOffset.x = temp_data.HostBackupColumnsOffset -- Layout in outer window + -- (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding + -- CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414) if inner_window ~= outer_window then local backup_nav_layers_active_mask = inner_window.DC.NavLayersActiveMask inner_window.DC.NavLayersActiveMask = bor(inner_window.DC.NavLayersActiveMask, lshift(1, table_.NavLayer)) -- So empty table don't appear to navigate differently. @@ -38567,9 +44062,13 @@ function ImGui.EndTable() -- Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar if band(table_.Flags, ImGuiTableFlags.NoHostExtendX) ~= 0 then + -- FIXME-TABLE: Could we remove this section? + -- ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents IM_ASSERT(band(table_.Flags, ImGuiTableFlags.ScrollX) == 0) outer_window.DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table_.OuterRect.Min.x + table_.ColumnsAutoFitWidth) elseif temp_data.UserOuterSize.x <= 0.0 then + -- Some references for this: #7651 + tests "table_reported_size", "table_reported_size_outer" equivalent Y block, #9352 + -- - FIXME-TABLE: Would make sense to pre-compute expected scrollbar visibility/sizes to generally save a frame of feedback? See broken test in 'table_reported_size_outer' local outer_content_max_x = table_.OuterRect.Min.x + table_.ColumnsAutoFitWidth local decoration_size = table_.TempData.AngledHeadersExtraWidth + ((inner_window ~= outer_window) and inner_window.ScrollbarSizes.x or 0.0) outer_window.DC.IdealMaxPos.x = ImMax(outer_window.DC.IdealMaxPos.x, outer_content_max_x + decoration_size - temp_data.UserOuterSize.x) @@ -38578,13 +44077,14 @@ function ImGui.EndTable() outer_window.DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table_.OuterRect.Max.x) end if temp_data.UserOuterSize.y <= 0.0 then + -- (same comment as above) local outer_content_size_y = (inner_window == outer_window) and (inner_content_max_y - table_.InnerRect.Min.y) or (inner_content_max_y - inner_window.DC.CursorStartPos.y) local outer_content_max_y = table_.OuterRect.Min.y + outer_content_size_y local decoration_size = (inner_window ~= outer_window) and inner_window.ScrollbarSizes.y or 0.0 outer_window.DC.IdealMaxPos.y = ImMax(outer_window.DC.IdealMaxPos.y, outer_content_max_y + decoration_size - temp_data.UserOuterSize.y) outer_window.DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, ImMin(table_.OuterRect.Max.y, outer_content_max_y + decoration_size)) else - -- OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set) + -- OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags.NoHostExtendY is set) outer_window.DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, table_.OuterRect.Max.y) end @@ -38640,16 +44140,18 @@ function ImGui.TableInitColumnDefaults(table_, column, column_n, init_mask) end -- See "COLUMNS SIZING POLICIES" comments at the top of this file --- If (init_width_or_weight <= 0.0f) it is ignored +-- If (init_width_or_weight <= 0.0) it is ignored local function TableSetupColumnApply(table_, idx, id, name_offset, flags, init_width_or_weight, user_data) local column = table_.Columns[idx] -- Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa. + -- Give a grace to users of ImGuiTableFlags.ScrollX. if table_.IsDefaultSizingPolicy and band(flags, ImGuiTableColumnFlags.WidthMask_) == 0 and band(flags, ImGuiTableFlags.ScrollX) == 0 then IM_ASSERT_USER_ERROR_RET(init_width_or_weight <= 0.0, "TableSetupColumn(): can only specify width/weight if sizing policy is set explicitly in either Table or Column.") end -- When passing a width automatically enforce WidthFixed policy + -- (whereas TableSetupColumnFlags would default to WidthAuto if table is not resizable) if band(flags, ImGuiTableColumnFlags.WidthMask_) == 0 and init_width_or_weight > 0.0 then if band(table_.Flags, ImGuiTableFlags.SizingMask_) == ImGuiTableFlags.SizingFixedFit or band(table_.Flags, ImGuiTableFlags.SizingMask_) == ImGuiTableFlags.SizingFixedSame then flags = bor(flags, ImGuiTableColumnFlags.WidthFixed) @@ -38680,10 +44182,11 @@ function ImGui.TableSetupColumn(label, flags, init_width_or_weight, user_data) local table_ = g.CurrentTable IM_ASSERT_USER_ERROR_RET(table_ ~= nil, "Call should only be done while in BeginTable() scope!") IM_ASSERT_USER_ERROR_RET(table_.DeclColumnsCount < table_.ColumnsCount, "TableSetupColumn(): called too many times!") - IM_ASSERT_USER_ERROR_RET(table_.IsLayoutLocked == false, "TableSetupColumn(): need to call before first row!") + IM_ASSERT_USER_ERROR_RET(table_.IsLayoutLocked == false, "TableSetupColumn(): need to call before first row!") -- Table layout is locked when submitting a row or when calling BeginMultiSelect() with box-select. IM_ASSERT(band(flags, ImGuiTableColumnFlags.StatusMask_) == 0, "Illegal to pass StatusMask values to TableSetupColumn()") -- Store name + -- FIXME: If we recorded the number of \n in names we could compute header row height local name_offset = -1 if label ~= nil and label ~= "" then name_offset = #table_.ColumnsNames @@ -38713,6 +44216,9 @@ function ImGui.TableSetupColumn(label, flags, init_width_or_weight, user_data) end -- Reconcile path: defer applying data to TableUpdateLayout() -> TableReconcileMovedColumns() -> TableSetupColumnApply(). + -- On column count change: search the previous columns: + -- - the live Columns[] array is truncated on shrink, so a moved column may only exist in old data. + -- - the live Columns[] array may already be partially reset. local reconcile_data = { ID = column_id, NameOffset = name_offset, Flags = flags, InitWidthOrWeight = init_width_or_weight, UserData = user_data, ColumnNewIdx = column_idx, ColumnOldIdx = -1, ColumnOldData = ImGuiTableColumn(), @@ -38777,9 +44283,9 @@ function ImGui.TableReconcileColumns(table_) end end - -- Apply in the final pass. Because it is possible that src_columns == table->Columns we went through a temporary copy. + -- Apply in the final pass. Because it is possible that src_columns == table.Columns we went through a temporary copy. for _, reconcile_data in reconcile_requests:iter() do - TableColumnCopy(table_.Columns[reconcile_data.ColumnNewIdx], reconcile_data.ColumnOldData) + TableColumnCopy(table_.Columns[reconcile_data.ColumnNewIdx], reconcile_data.ColumnOldData) -- When old column was not found clear anyway with default-constructed data (which will set IsJustCreated=true) TableSetupColumnApply(table_, reconcile_data.ColumnNewIdx, reconcile_data.ID, reconcile_data.NameOffset, reconcile_data.Flags, reconcile_data.InitWidthOrWeight, reconcile_data.UserData) end ImGui.TableFixDisplayOrder(table_) @@ -38804,10 +44310,25 @@ function ImGui.TableSetupScrollFreeze(columns, rows) table_.IsUnfrozenRows = (table_.FreezeRowsCount == 0) -- Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it. end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Simple accessors ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetColumnCount() +-- - TableGetColumnName() +-- - TableGetColumnName() [Internal] +-- - TableSetColumnEnabled() +-- - TableGetColumnFlags() +-- - TableGetCellBgRect() [Internal] +-- - TableGetColumnResizeID() [Internal] +-- - TableGetHoveredColumn() [Internal] +-- - TableGetHoveredRow() [Internal] +-- - TableSetBgColor() +------------------------------------------------------------------------------- +-- [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences, +-- they would meddle many times with the underlying ImDrawCmd. +-- Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let +-- the subsequent single call to SetCurrentChannel() does it things once. function ImGui.SetWindowClipRectBeforeSetChannel(window, clip_rect) local clip_rect_vec4 = clip_rect:ToVec4() ImRect_Copy(window.ClipRect, clip_rect) @@ -38848,6 +44369,11 @@ function ImGui.TableGetColumnName(a, b) end -- Change user accessible enabled/disabled state of a column (often perceived as "showing/hiding" from users point of view) +-- Note that end-user can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags.ContextMenuInBody) +-- - Require table to have the ImGuiTableFlags.Hideable flag because we are manipulating user accessible state. +-- - Request will be applied during next layout, which happens on the first call to TableNextRow() after BeginTable(). +-- - For the getter you can test (TableGetColumnFlags() & ImGuiTableColumnFlags.IsEnabled) ~= 0. +-- - Alternative: the ImGuiTableColumnFlags.Disabled is an overriding/master disable flag which will also hide the column from context menu. function ImGui.TableSetColumnEnabled(column_n, enabled) local g = GImGui local table_ = g.CurrentTable @@ -38879,10 +44405,19 @@ function ImGui.TableGetColumnFlags(column_n) end -- Return the cell rectangle based on currently known height. +-- - Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations. +-- The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it, or in TableEndRow() when we locked that height. +-- - Important: if ImGuiTableFlags.PadOuterX is set but ImGuiTableFlags.PadInnerX is not set, the outer-most left and right +-- columns report a small offset so their CellBgRect can extend up to the outer border. +-- FIXME: But the rendering code in TableEndRow() nullifies that with clamping required for scrolling. function ImGui.TableGetCellBgRect(table_, column_n) local column = table_.Columns[column_n] local x1 = column.MinX local x2 = column.MaxX + --if column.PrevEnabledColumn == -1 then + -- x1 = x1 - table.OuterPaddingX + --if column.NextEnabledColumn == -1 then + -- x2 = x2 + table.OuterPaddingX x1 = ImMax(x1, table_.WorkRect.Min.x) x2 = ImMin(x2, table_.WorkRect.Max.x) return ImRect(x1, table_.RowPosY1, x2, table_.RowPosY2) @@ -38907,6 +44442,8 @@ function ImGui.TableGetHoveredColumn() end -- Return -1 when table is not hovered. Return maxrow+1 if in table but below last submitted row. +-- *IMPORTANT* Unlike TableGetHoveredColumn(), this has a one frame latency in updating the value. +-- This difference with is the reason why this is not public yet. function ImGui.TableGetHoveredRow() local g = GImGui local table_ = g.CurrentTable @@ -38957,11 +44494,16 @@ function ImGui.TableSetBgColor(target, color, column_n) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Row changes ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetRowIndex() +-- - TableNextRow() +-- - TableBeginRow() [Internal] +-- - TableEndRow() [Internal] +------------------------------------------------------------------------------- --- [Public] Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows +-- [Public] Note: for row coloring we use .RowBgColorCounter which is the same value without counting header rows function ImGui.TableGetRowIndex() local g = GImGui local table_ = g.CurrentTable @@ -39029,7 +44571,7 @@ function ImGui.TableBeginRow(table_) window.DC.PrevLineTextBaseOffset = 0.0 window.DC.CursorPosPrevLine.x = window.DC.CursorPos.x window.DC.CursorPosPrevLine.y = window.DC.CursorPos.y + table_.RowCellPaddingY -- This allows users to call SameLine() to share LineSize between columns. - window.DC.PrevLineSize.x = 0.0; window.DC.PrevLineSize.y = 0.0 + window.DC.PrevLineSize.x = 0.0; window.DC.PrevLineSize.y = 0.0 -- This allows users to call SameLine() to share LineSize between columns, and to call it from first column too. window.DC.CurrLineSize.x = 0.0; window.DC.CurrLineSize.y = 0.0 window.DC.IsSameLine = false; window.DC.IsSetPos = false window.DC.CursorMaxPos.y = next_y1 @@ -39060,7 +44602,8 @@ function ImGui.TableEndRow(table_) ImGui.LogRenderedText(nil, "|") end - -- Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. + -- Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is + -- likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding. window.DC.CursorPos.y = table_.RowPosY2 -- Row background fill @@ -39128,6 +44671,7 @@ function ImGui.TableEndRow(table_) for cell_n = 0, table_.RowCellDataCurrent do local cell_data = table_.RowCellData[cell_n] -- As we render the BG here we need to clip things (for layout we would not) + -- FIXME: This cancels the OuterPadding addition done by TableGetCellBgRect(), need to keep it while rendering correctly while scrolling. local column = table_.Columns[cell_data.Column] local cell_bg_rect = ImGui.TableGetCellBgRect(table_, cell_data.Column) cell_bg_rect:ClipWith(table_.BgClipRect) @@ -39151,6 +44695,8 @@ function ImGui.TableEndRow(table_) end -- End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) + -- - We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark + -- end of row and get the new cursor position. if unfreeze_rows_request then IM_ASSERT(table_.FreezeRowsRequest > 0) for column_n = 0, table_.ColumnsCount - 1 do @@ -39163,7 +44709,7 @@ function ImGui.TableEndRow(table_) IM_ASSERT(table_.IsUnfrozenRows == false) table_.IsUnfrozenRows = true - -- BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect + -- BgClipRect starts as table.InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect local min_y = ImMin(y0, table_.InnerClipRect.Max.y) table_.BgClipRect.Min.y = min_y; table_.Bg2ClipRectForDrawCmd.Min.y = min_y table_.BgClipRect.Max.y = table_.InnerClipRect.Max.y; table_.Bg2ClipRectForDrawCmd.Max.y = table_.InnerClipRect.Max.y @@ -39180,7 +44726,7 @@ function ImGui.TableEndRow(table_) column.ClipRect.Min.y = table_.Bg2ClipRectForDrawCmd.Min.y end - -- Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y + -- Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect.Min.y ImGui.SetWindowClipRectBeforeSetChannel(window, table_.Columns[0].ClipRect) table_.DrawSplitter:SetCurrentChannel(window.DrawList, table_.Columns[0].DrawChannelCurrent) end @@ -39192,9 +44738,15 @@ function ImGui.TableEndRow(table_) table_.IsInsideRow = false end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Columns changes ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetColumnIndex() +-- - TableSetColumnIndex() +-- - TableNextColumn() +-- - TableBeginCell() [Internal] +-- - TableEndCell() [Internal] +------------------------------------------------------------------------------- function ImGui.TableGetColumnIndex() local g = GImGui @@ -39254,6 +44806,7 @@ end -- [Internal] Called by TableSetColumnIndex()/TableNextColumn() -- This is called very frequently, so we need to be mindful of unnecessary overhead. +-- FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns. function ImGui.TableBeginCell(table_, column_n) local g = GImGui local column = table_.Columns[column_n] @@ -39263,7 +44816,7 @@ function ImGui.TableBeginCell(table_, column_n) -- Start position is roughly ~~ CellRect.Min + CellPadding + Indent local start_x = column.WorkMinX if band(column.Flags, ImGuiTableColumnFlags.IndentEnable) ~= 0 then - start_x = start_x + table_.RowIndentOffsetX -- ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row. + start_x = start_x + table_.RowIndentOffsetX -- ~~ += window.DC.Indent.x - table.HostIndentX, except we locked it for the row. end window.DC.CursorPos.x = start_x @@ -39290,6 +44843,7 @@ function ImGui.TableBeginCell(table_, column_n) if band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0 then -- FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed. table_.DrawSplitter:SetCurrentChannel(window.DrawList, TABLE_DRAW_CHANNEL_NOCLIP) + --IM_ASSERT(table.DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP) else -- FIXME-TABLE: Could avoid this if draw channel is dummy channel? ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect) @@ -39327,27 +44881,43 @@ function ImGui.TableEndCell(table_) column.ItemWidth = window.DC.ItemWidth -- Propagate text baseline for the entire row + -- FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one. table_.RowTextBaseline = ImMax(table_.RowTextBaseline, window.DC.PrevLineTextBaseOffset) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Columns width management ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetMaxColumnWidth() [Internal] +-- - TableGetColumnWidthAuto() [Internal] +-- - TableSetColumnWidth() +-- - TableSetColumnWidthAutoSingle() [Internal] +-- - TableSetColumnWidthAutoAll() [Internal] +-- - TableUpdateColumnsWeightFromWidth() [Internal] +------------------------------------------------------------------------------- +-- Note that actual columns widths are computed in TableUpdateLayout(). +------------------------------------------------------------------------------- --- Maximum column content width given current layout. Use column->MinX so this value differs on a per-column basis. +-- Maximum column content width given current layout. Use column.MinX so this value differs on a per-column basis. function ImGui.TableCalcMaxColumnWidth(table_, column_n) local column = table_.Columns[column_n] local max_width = FLT_MAX local min_column_distance = table_.MinColumnWidth + table_.CellPaddingX * 2.0 + table_.CellSpacingX1 + table_.CellSpacingX2 if band(table_.Flags, ImGuiTableFlags.ScrollX) ~= 0 then -- Frozen columns can't reach beyond visible width else scrolling will naturally break. + -- (we use DisplayOrder as within a set of multiple frozen column reordering is possible) if column.DisplayOrder < table_.FreezeColumnsRequest then max_width = (table_.InnerClipRect.Max.x - (table_.FreezeColumnsRequest - column.DisplayOrder) * min_column_distance) - column.MinX max_width = max_width - table_.OuterPaddingX - table_.CellPaddingX - table_.CellSpacingX2 end elseif band(table_.Flags, ImGuiTableFlags.NoKeepColumnsVisible) == 0 then - -- If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make sure they are all visible. + -- If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make + -- sure they are all visible. Because of this we also know that all of the columns will always fit in + -- table.WorkRect and therefore in table.InnerRect (because ScrollX is off) + -- FIXME-TABLE: This is solved incorrectly but also quite a difficult problem to fix as we also want ClipRect width to match. + -- See "table_width_distrib" and "table_width_keep_visible" tests max_width = table_.WorkRect.Max.x - (table_.ColumnsEnabledCount - column.IndexWithinEnabledSet - 1) * min_column_distance - column.MinX + --max_width = max_width - table.CellSpacingX1 max_width = max_width - table_.CellSpacingX2 max_width = max_width - table_.CellPaddingX * 2.0 max_width = max_width - table_.OuterPaddingX @@ -39355,7 +44925,7 @@ function ImGui.TableCalcMaxColumnWidth(table_, column_n) return max_width end --- Note this is meant to be stored in column->WidthAuto, please generally use the WidthAuto field +-- Note this is meant to be stored in column.WidthAuto, please generally use the WidthAuto field function ImGui.TableGetColumnWidthAuto(table_, column) local content_width_body = ImMax(column.ContentMaxXFrozen, column.ContentMaxXUnfrozen) - column.WorkMinX local content_width_headers = column.ContentMaxXHeadersIdeal - column.WorkMinX @@ -39384,6 +44954,7 @@ function ImGui.TableSetColumnWidth(column_n, width) local column_0_width = width -- Apply constraints early + -- Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded) IM_ASSERT(table_.MinColumnWidth > 0.0) local min_width = table_.MinColumnWidth local max_width = ImMax(min_width, column_0.WidthMax) -- Don't use TableCalcMaxColumnWidth() here as it would rely on MinX from last instance (#7933) @@ -39392,8 +44963,41 @@ function ImGui.TableSetColumnWidth(column_n, width) return end + --IMGUI_DEBUG_PRINT("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0.WidthGiven, column_0_width) local column_1 = (column_0.NextEnabledColumn ~= -1) and table_.Columns[column_0.NextEnabledColumn] or nil + -- In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns. + -- - All fixed: easy. + -- - All stretch: easy. + -- - One or more fixed + one stretch: easy. + -- - One or more fixed + more than one stretch: tricky. + -- Qt when manual resize is enabled only supports a single _trailing_ stretch column, we support more cases here. + + -- When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1. + -- FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user. + -- Scenarios: + -- - F1 F2 F3 resize from F1| or F2| --> ok: alter .WidthRequested of Fixed column. Subsequent columns will be offset. + -- - F1 F2 F3 resize from F3| --> ok: alter .WidthRequested of Fixed column. If active, ScrollX extent can be altered. + -- - F1 F2 W3 resize from F1| or F2| --> ok: alter .WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size. + -- - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 W2 W3 resize from W1| or W2| --> ok + -- - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 W2 F3 resize from W1| or W2| --> ok + -- - W1 F2 W3 resize from W1| or F2| --> ok + -- - F1 W2 F3 resize from W2| --> ok + -- - F1 W3 F2 resize from W3| --> ok + -- - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move. + -- - W1 F2 F3 resize from F2| --> ok + -- All resizes from a Wx columns are locking other columns. + + -- Possible improvements: + -- - W1 W2 W3 resize W1| --> to not be stuck, both W2 and W3 would stretch down. Seems possible to fix. Would be most beneficial to simplify resize of all-weighted columns. + -- - W3 F1 F2 resize W3| --> to not be stuck past F1|, both F1 and F2 would need to stretch down, which would be lossy or ambiguous. Seems hard to fix. + + -- [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout(). + -- If we have all Fixed columns OR resizing a Fixed column that doesn't come after a Stretch one, we can do an offsetting resize. -- This is the preferred resize path if band(column_0.Flags, ImGuiTableColumnFlags.WidthFixed) ~= 0 then @@ -39426,6 +45030,7 @@ function ImGui.TableSetColumnWidth(column_n, width) end -- Disable clipping then auto-fit, will take 2 frames +-- (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns) function ImGui.TableSetColumnWidthAutoSingle(table_, column_n) -- Single auto width uses auto-fit local column = table_.Columns[column_n] @@ -39472,11 +45077,24 @@ function ImGui.TableUpdateColumnsWeightFromWidth(table_) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Drawing ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TablePushBackgroundChannel() [Internal] +-- - TablePopBackgroundChannel() [Internal] +-- - TableSetupDrawChannels() [Internal] +-- - TableMergeDrawChannels() [Internal] +-- - TableGetColumnBorderCol() [Internal] +-- - TableDrawBorders() [Internal] +------------------------------------------------------------------------------- + + +-- FIXME: This could be abstracted and merged with PushColumnsBackground(), by creating a generic struct +-- with storage for backup cliprect + backup channel + storage for splitter pointer, new clip rect. +-- This would slightly simplify caller code. -- Bg2 is used by Selectable (and possibly other widgets) to render to the background. +-- Unlike our Bg0/1 channel which we uses for RowBg/CellBg/Borders and where we guarantee all shapes to be CPU-clipped, the Bg2 channel being widgets-facing will rely on regular ClipRect. function ImGui.TablePushBackgroundChannel() local g = GImGui local window = g.CurrentWindow @@ -39528,6 +45146,21 @@ function ImGui.TablePopColumnChannel() end -- Allocate draw channels. Called by TableUpdateLayout() +-- - We allocate them following storage order instead of display order so reordering columns won't needlessly +-- increase overall dormant memory cost. +-- - We isolate headers draw commands in their own channels instead of just altering clip rects. +-- This is in order to facilitate merging of draw commands. +-- - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels. +-- - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other +-- channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged. +-- - We allocate 1 or 2 background draw channels. This is because we know TablePushBackgroundChannel() is only used for +-- horizontal spanning. If we allowed vertical spanning we'd need one background draw channel per merge group (1-4). +-- Draw channel allocation (before merging): +-- - NoClip --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call) +-- - Clip --> 2+D+N channels +-- - FreezeRows --> 2+D+N*2 (unless scrolling value is zero) +-- - FreezeRows || FreezeColumns --> 3+D+N*2 (unless scrolling value is zero) +-- Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0. function ImGui.TableSetupDrawChannels(table_) local freeze_row_multiplier = (table_.FreezeRowsCount > 0) and 2 or 1 local channels_for_row = (band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0) and 1 or table_.ColumnsEnabledCount @@ -39563,6 +45196,8 @@ function ImGui.TableSetupDrawChannels(table_) end -- Initial draw cmd starts with a BgClipRect that matches the one of its host, to facilitate merge draw commands by default. + -- All our cell highlight are manually clipped with BgClipRect. When unfreezing it will be made smaller to fit scrolling rect. + -- (This technically isn't part of setting up draw channels, but is reasonably related to be done here) ImRect_Copy(table_.BgClipRect, table_.InnerClipRect) ImRect_Copy(table_.Bg0ClipRectForDrawCmd, table_.OuterWindow.ClipRect) ImRect_Copy(table_.Bg2ClipRectForDrawCmd, table_.HostClipRect) @@ -39570,6 +45205,34 @@ function ImGui.TableSetupDrawChannels(table_) end -- This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable(). +-- For simplicity we call it TableMergeDrawChannels() but in fact it only reorder channels + overwrite ClipRect, +-- actual merging is done by table.DrawSplitter:Merge() which is called right after TableMergeDrawChannels(). +-- +-- Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve +-- this we merge their clip rect and make them contiguous in the channel list, so they can be merged +-- by the call to DrawSplitter:Merge() following to the call to this function. +-- We reorder draw commands by arranging them into a maximum of 4 distinct groups: +-- +-- 1 group: 2 groups: 2 groups: 4 groups: +-- [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze +-- [ .. ] or no scroll [ 2. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll +-- +-- Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled). +-- When the contents of a column didn't stray off its limit, we move its channels into the corresponding group +-- based on its position (within frozen rows/columns groups or not). +-- At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect. +-- This function assume that each column are pointing to a distinct draw channel, +-- otherwise merge_group.ChannelsCount will not match set bit count of merge_group.ChannelsMask. +-- +-- Column channels will not be merged into one of the 1-4 groups in the following cases: +-- - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value). +-- Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui.* bounds +-- matches, by e.g. calling SetCursorScreenPos(). +-- - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here.. +-- we could do better but it's going to be rare and probably not worth the hassle. +-- Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. +-- +-- This function is particularly tricky to understand.. take a breath. -- (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets) function ImGui.TableMergeDrawChannels(table_) local splitter = table_.DrawSplitter @@ -39608,6 +45271,7 @@ function ImGui.TableMergeDrawChannels(table_) end -- Find out the width of this merge group and check if it will fit in our column + -- (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it) if band(column.Flags, ImGuiTableColumnFlags.NoClip) == 0 then local content_max_x if not has_freeze_v then @@ -39637,6 +45301,7 @@ function ImGui.TableMergeDrawChannels(table_) end -- Invalidate current draw channel + -- (we don't clear DrawChannelFrozen/DrawChannelUnfrozen solely to facilitate debugging/later inspection of data) column.DrawChannelCurrent = -1 end end @@ -39652,6 +45317,7 @@ function ImGui.TableMergeDrawChannels(table_) remaining_mask[table_.Bg2DrawChannelUnfrozen] = nil IM_ASSERT(has_freeze_v == false or table_.Bg2DrawChannelUnfrozen ~= TABLE_DRAW_CHANNEL_BG2_FROZEN) local remaining_count = splitter._Count - (has_freeze_v and (LEADING_DRAW_CHANNELS + 1) or LEADING_DRAW_CHANNELS) + --local host_rect = (table.InnerWindow == table.OuterWindow) and table.InnerClipRect or table.HostClipRect local host_rect = table_.HostClipRect for merge_group_n = 0, 3 do local merge_channels_count = merge_groups[merge_group_n].ChannelsCount @@ -39661,6 +45327,11 @@ function ImGui.TableMergeDrawChannels(table_) -- Extend outer-most clip limits to match those of host, so draw calls can be merged even if -- outer-most columns have some outer padding offsetting them from their parent ClipRect. + -- The principal cases this is dealing with are: + -- - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge + -- - Columns can use padding and have left-most ClipRect.Min.x and right-most ClipRect.Max.x != from host ClipRect -> will extend and match host ClipRect -> will merge + -- FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit + -- within host clip rect, solely because of the half-padding difference between window.WorkRect and window.InnerClipRect. if band(merge_group_n, 1) == 0 or not has_freeze_h then merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x) end @@ -39673,6 +45344,9 @@ function ImGui.TableMergeDrawChannels(table_) if band(merge_group_n, 2) ~= 0 and band(table_.Flags, ImGuiTableFlags.NoHostExtendY) == 0 then merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y) end + --ImGui.GetForegroundDrawList():AddRect(merge_group.ClipRect.Min, merge_group.ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0, 0, 1.0) -- [DEBUG] + --ImGui.GetForegroundDrawList():AddLine(merge_group.ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200)) + --ImGui.GetForegroundDrawList():AddLine(merge_group.ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200)) remaining_count = remaining_count - merge_group.ChannelsCount for n in pairs(merge_group.ChannelsMask) do remaining_mask[n] = nil @@ -39789,7 +45463,13 @@ function ImGui.TableDrawBorders(table_) end -- Draw outer border + -- FIXME: could use AddRect or explicit VLine/HLine helper? if band(table_.Flags, ImGuiTableFlags.BordersOuter) ~= 0 then + -- Display outer border offset by 1 which is a simple way to display it without adding an extra draw call + -- (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their + -- parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part + -- of it in inner window, and the part that's over scrollbars in the outer window..) + -- Either solution currently won't allow us to use a larger border size: the border would clipped. local outer_border = table_.OuterRect local outer_col = table_.BorderColorStrong if band(table_.Flags, ImGuiTableFlags.BordersOuter) == ImGuiTableFlags.BordersOuter then @@ -39814,12 +45494,23 @@ function ImGui.TableDrawBorders(table_) inner_drawlist:PopClipRect() end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Sorting ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetSortSpecs() +-- - TableFixColumnSortDirection() [Internal] +-- - TableGetColumnNextSortDirection() [Internal] +-- - TableSetColumnSortDirection() [Internal] +-- - TableSortSpecsSanitize() [Internal] +-- - TableSortSpecsBuild() [Internal] +------------------------------------------------------------------------------- --- Return nil if no sort specs (most often when ImGuiTableFlags_Sortable is not set) --- When 'sort_specs.SpecsDirty == true' you should sort your data. Specs is a 1-based Lua array. +-- Return nil if no sort specs (most often when ImGuiTableFlags.Sortable is not set) +-- When 'sort_specs.SpecsDirty == true' you should sort your data. It will be true when sorting specs have +-- changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, +-- else you may wastefully sort your data every frame! +-- Lifetime: don't hold on this table over multiple frames or past any subsequent call to BeginTable()! +-- PORT: Specs is a 1-based Lua array. function ImGui.TableGetSortSpecs() local g = GImGui local table_ = g.CurrentTable @@ -39851,6 +45542,8 @@ function ImGui.TableFixColumnSortDirection(table_, column) end -- Calculate next sort direction that would be set after clicking the column +-- - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click. +-- - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op. function ImGui.TableGetColumnNextSortDirection(column) IM_ASSERT(column.SortDirectionsAvailCount > 0) if column.SortOrder == -1 then @@ -39934,6 +45627,7 @@ function ImGui.TableSortSpecsSanitize(table_) local fixed_mask = {} for sort_n = 0, sort_order_count - 1 do -- Fix: Rewrite sort order fields if needed so they have no gap or duplicate. + -- (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1) local column_with_smallest_sort_order = -1 for column_n = 0, table_.ColumnsCount - 1 do if not fixed_mask[column_n] and table_.Columns[column_n].SortOrder ~= -1 then @@ -39946,7 +45640,7 @@ function ImGui.TableSortSpecsSanitize(table_) fixed_mask[column_with_smallest_sort_order] = true table_.Columns[column_with_smallest_sort_order].SortOrder = sort_n - -- Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set. + -- Fix: Make sure only one column has a SortOrder if ImGuiTableFlags.MultiSortable is not set. if need_fix_single_sort_order then sort_order_count = 1 for column_n = 0, table_.ColumnsCount - 1 do @@ -39959,7 +45653,7 @@ function ImGui.TableSortSpecsSanitize(table_) end end - -- Fallback default sort order (if no column with the ImGuiTableColumnFlags_DefaultSort flag) + -- Fallback default sort order (if no column with the ImGuiTableColumnFlags.DefaultSort flag) if sort_order_count == 0 and band(table_.Flags, ImGuiTableFlags.SortTristate) == 0 then for column_n = 0, table_.ColumnsCount - 1 do local column = table_.Columns[column_n] @@ -39988,6 +45682,7 @@ function ImGui.TableSortSpecsBuild(table_) end -- Write output + -- May be able to move all SortSpecs data from table (48 bytes) to ImGuiTableTempData if we decide to write it back on every BeginTable() local sort_specs if table_.SortSpecsCount == 0 then sort_specs = nil @@ -40015,12 +45710,22 @@ function ImGui.TableSortSpecsBuild(table_) table_.SortSpecs.SpecsCount = table_.SortSpecsCount end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Headers ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetHeaderRowHeight() [Internal] +-- - TableGetHeaderAngledMaxLabelWidth() [Internal] +-- - TableHeadersRow() +-- - TableHeader() +-- - TableAngledHeadersRow() +-- - TableAngledHeadersRowEx() [Internal] +------------------------------------------------------------------------------- function ImGui.TableGetHeaderRowHeight() + -- Caring for a minor edge case: -- Calculate row height, for the unlikely case that some labels may be taller than others. + -- If we didn't do that, uneven header height would highlight but smaller one before the tallest wouldn't catch input for all height. + -- In your custom header row you may omit this all together and just call TableNextRow() without a height... local g = GImGui local table_ = g.CurrentTable local row_height = g.FontSize @@ -40049,6 +45754,12 @@ function ImGui.TableGetHeaderAngledMaxLabelWidth() end -- [Public] This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). +-- The intent is that advanced users willing to create customized headers would not need to use this helper +-- and can create their own! For example: TableHeader() may be preceded by Checkbox() or other custom widgets. +-- See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this. +-- This code is intentionally written to not make much use of internal functions, to give you better direction +-- if you need to write your own. +-- FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public. function ImGui.TableHeadersRow() local g = GImGui local table_ = g.CurrentTable @@ -40090,6 +45801,7 @@ end -- Emit a column header (text + optional sort order) -- We cpu-clip text here so that all columns headers can be merged into a same draw call. +-- Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader() function ImGui.TableHeader(label) local g = GImGui local window = g.CurrentWindow @@ -40112,6 +45824,7 @@ function ImGui.TableHeader(label) local label_pos = V2(window.DC.CursorPos) -- If we already got a row height, there's use that. + -- FIXME-TABLE: Padding problem if the correct outer-padding CellBgRect strays off our ClipRect? local cell_r = ImGui.TableGetCellBgRect(table_, column_n) local label_height = ImMax(label_size.y, table_.RowMinHeight - table_.RowCellPaddingY * 2.0) @@ -40145,11 +45858,15 @@ function ImGui.TableHeader(label) return end + --GetForegroundDrawList():AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)) -- [DEBUG] + --GetForegroundDrawList():AddRect(bb.Min, bb.Max, IM_COL32(255, 0, 0, 255)) -- [DEBUG] + -- Using AllowOverlap mode because we cover the whole cell, and we want user to be able to submit subsequent items. local highlight = (table_.HighlightColumnHeader == column_n) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, ImGuiButtonFlags.AllowOverlap) if held or hovered or highlight then local col = ImGui.GetColorU32(held and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header)) + --RenderFrame(bb.Min, bb.Max, col, false, 0.0) ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, col, table_.CurrentColumn) else -- Submit single cell bg color in the case we didn't submit a full header row @@ -40164,7 +45881,14 @@ function ImGui.TableHeader(label) window.DC.CursorPos.y = window.DC.CursorPos.y - g.Style.ItemSpacing.y * 0.5 -- Drag and drop to re-order columns. + -- FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone. if held and band(table_.Flags, ImGuiTableFlags.Reorderable) ~= 0 and ImGui.IsMouseDragging(0) and not g.DragDropActive then + -- - While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x + -- - We need to handle reordering across hidden columns. + -- In the configuration below, moving C to the right of E will lead to: + -- ... C [D] E ---> ... [D] E C (Column name/index) + -- ... 2 3 4 ... 2 3 4 (Display order) + -- - The other constraints are enforced by TableQueueSetColumnDisplayOrder() which might early out. table_.InstanceInteracted = table_.InstanceCurrent if g.IO.MouseDelta.x < 0.0 and g.IO.MousePos.x < cell_r.Min.x then local prev_column = (column.PrevEnabledColumn ~= -1) and table_.Columns[column.PrevEnabledColumn] or nil @@ -40181,6 +45905,8 @@ function ImGui.TableHeader(label) end -- Sort order arrow + -- - Only clip label for a visible arrow. Auto-fit still accounts for a possible arrow, but when + -- manually sized smaller we don't clip the label for the sake of an arrow that isn't displayed. local ellipsis_max = ImMax(cell_r.Max.x - (sort_arrow and (w_arrow + w_sort_text) or 0.0), label_pos.x) if band(table_.Flags, ImGuiTableFlags.Sortable) ~= 0 and band(column.Flags, ImGuiTableColumnFlags.NoSort) == 0 then if column.SortOrder ~= -1 then @@ -40204,6 +45930,7 @@ function ImGui.TableHeader(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) ImGui.RenderTextEllipsis(window.DrawList, label_pos, ImVec2(ellipsis_max, bb.Max.y), ellipsis_max, label, label_end, label_size) local text_clipped = label_size.x > (ellipsis_max - label_pos.x) @@ -40218,6 +45945,7 @@ function ImGui.TableHeader(label) end -- Unlike TableHeadersRow() it is not expected that you can reimplement or customize this with custom widgets. +-- FIXME: No hit-testing/button on the angled header. function ImGui.TableAngledHeadersRow() local g = GImGui local table_ = g.CurrentTable @@ -40241,7 +45969,7 @@ function ImGui.TableAngledHeadersRow() if BitTest(table_.EnabledMaskByDisplayOrder, order_n) then local column_n = table_.DisplayOrderToIndex[order_n] local column = table_.Columns[column_n] - if band(column.Flags, ImGuiTableColumnFlags.AngledHeader) ~= 0 then -- Note: can't rely on ImGuiTableColumnFlags_IsVisible test here. + if band(column.Flags, ImGuiTableColumnFlags.AngledHeader) ~= 0 then -- Note: can't rely on ImGuiTableColumnFlags.IsVisible test here. temp_data.AngledHeadersRequests:push_back({ Index = column_n, TextColor = col_text, BgColor0 = col_header_bg, BgColor1 = (column_n == highlight_column_n) and ImGui.GetColorU32(ImGuiCol.Header) or 0 }) end end @@ -40287,6 +46015,7 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat local unit_right = ImVec2(cos_a, sin_a) -- Calculate our base metrics and set angled headers data _before_ the first call to TableNextRow() + -- FIXME-STYLE: Would it be better for user to submit 'max_label_width' or 'row_height' ? One can be derived from the other. local header_height = g.FontSize + g.Style.CellPadding.x * 2.0 local row_height = ImTrunc(ImAbs(ImRotate(ImVec2(max_label_width, flip_label and header_height or -header_height), cos_a, sin_a).y)) table_.AngledHeadersHeight = row_height @@ -40294,6 +46023,7 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat local header_angled_vector = unit_right * (row_height / -sin_a) -- vector from bottom-left to top-left, and from bottom-right to top-right -- Declare row, override and draw our own background + -- FIXME-TABLE: Generally broken when overlapping frozen columns limit. ImGui.TableNextRow(ImGuiTableRowFlags.Headers, row_height) ImGui.TableNextColumn() local row_r = ImRect(table_.WorkRect.Min.x, table_.BgClipRect.Min.y, table_.WorkRect.Max.x, table_.RowPosY2) @@ -40335,6 +46065,8 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat max_x = ImMax(max_x, bg_shape[3].x) -- Draw label + -- - First draw at an offset where RenderTextXXX() function won't meddle with applying current ClipRect, then transform to final offset. + -- - Handle multiple lines manually, as we want each lines to follow on the horizontal border, rather than see a whole block rotated. local label_name = ImGui.TableGetColumnName(table_, column_n) local label_name_end = ImGui.FindRenderedTextEnd(label_name) local line_off_step_x = (g.FontSize / -sin_a) @@ -40382,6 +46114,7 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat end pivot_out.x = pivot_out.x + (flip_label and (line_off_curr_x + line_off_step_x) or line_off_curr_x) ImGui.ShadeVertsTransformPos(draw_list, vtx_idx_begin, vtx_idx_end, pivot_in, label_cos_a, label_sin_a, pivot_out) -- Rotate and offset + --if g.IO.KeyShift then local fg_dl = GetForegroundDrawList(); vtx_idx_begin = fg_dl._VtxCurrentIdx; fg_dl:AddRect(clip_r.Min, clip_r.Max, IM_COL32(0, 255, 0, 255), 0.0, 0, 1.0); ShadeVertsTransformPos(fg_dl, vtx_idx_begin, fg_dl._VtxCurrentIdx, pivot_in, label_cos_a, label_sin_a, pivot_out) end p = label_name_eol + 1 end @@ -40398,9 +46131,13 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat table_.TempData.AngledHeadersExtraWidth = ImMax(0.0, max_x - table_.Columns[table_.RightMostEnabledColumn].MaxX) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Context Menu ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableOpenContextMenu() [Internal] +-- - TableBeginContextMenuPopup() [Internal] +-- - TableDrawDefaultContextMenu() [Internal] +------------------------------------------------------------------------------- -- Use -1 to open menu not specific to a given column. function ImGui.TableOpenContextMenu(column_n) @@ -40454,8 +46191,8 @@ local function MenuItemForColumnReorder(label, selected, enabled) end local has_been_moved = (g.ActiveId == id) and g.ActiveIdHasBeenEditedBefore -- But disable toggling once moved. - ImGui.BeginDisabled(not enabled) -- Don't use ImGuiSelectableFlags_Disabled so that Check mark is also affected. - local ret = ImGui.Selectable(label, false, selectable_flags, ImVec2(min_w, label_size.y)) and not has_been_moved + ImGui.BeginDisabled(not enabled) -- Don't use ImGuiSelectableFlags.Disabled so that Check mark is also affected. + local ret = ImGui.Selectable(label, false, selectable_flags, ImVec2(min_w, label_size.y)) and not has_been_moved -- Can't use IsMouseDragging(0) as button is released already. if band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 and selected then ImGui.RenderCheckMark(window.DrawList, text_pos + ImVec2(offsets.OffsetMark + stretch_w + g.FontSize * 0.40, g.FontSize * 0.134 * 0.5), ImGui.GetColorU32(ImGuiCol.Text), g.FontSize * 0.866) end @@ -40465,6 +46202,13 @@ local function MenuItemForColumnReorder(label, selected, enabled) end -- Output context menu into current window (generally a popup) +-- FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data? +-- Sections to display are pulled from 'flags_for_section_to_display', which is typically == table.Flags. +-- - ImGuiTableFlags.Resizable -> display Sizing menu items +-- - ImGuiTableFlags.Reorderable -> display "Reset Order" +---- ImGuiTableFlags.Sortable -> display sorting options (disabled) +-- - ImGuiTableFlags.Hideable -> display columns visibility menu items +-- It means if you have a custom context menus you can call this section and omit some sections, and add your own. function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) local g = GImGui local window = g.CurrentWindow @@ -40500,6 +46244,9 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) -- Reset Order/Visibility etc. if band(flags_for_section_to_display, bor(ImGuiTableFlags.Reorderable, ImGuiTableFlags.Hideable)) ~= 0 then if ImGui.BeginMenu(ImGui.LocalizeGetMsg(ImGuiLocKey.TableReset)) then + --if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.TableResetAll)) then -- FIXME: Hiding because altering Sort Order + requesting auto-fit simultaneously has a tendency to exhibit a sizing glitch. + -- table_.IsResetAllRequest = true + --end if band(flags_for_section_to_display, ImGuiTableFlags.Reorderable) ~= 0 then if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.TableResetOrder), nil, false, not table_.IsDefaultDisplayOrder) then -- PS: cannot be hidden because it would mess with drag reordering. table_.IsResetDisplayOrderRequest = true @@ -40514,6 +46261,22 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end end + -- Sorting + -- (modify TableOpenContextMenu() to add _Sortable flag if enabling this) + -- #if 0 + --if band(flags_for_section_to_display, ImGuiTableFlags.Sortable) ~= 0 and column ~= nil and band(column.Flags, ImGuiTableColumnFlags.NoSort) == 0 then + -- if want_separator then ImGui.Separator() end + -- want_separator = true + -- local append_to_sort_specs = g.IO.KeyShift + -- if ImGui.MenuItem("Sort in Ascending Order", nil, column.SortOrder ~= -1 and column.SortDirection == ImGuiSortDirection.Ascending, band(column.Flags, ImGuiTableColumnFlags.NoSortAscending) == 0) then + -- ImGui.TableSetColumnSortDirection(table_, column_n, ImGuiSortDirection.Ascending, append_to_sort_specs) + -- end + -- if ImGui.MenuItem("Sort in Descending Order", nil, column.SortOrder ~= -1 and column.SortDirection == ImGuiSortDirection.Descending, band(column.Flags, ImGuiTableColumnFlags.NoSortDescending) == 0) then + -- ImGui.TableSetColumnSortDirection(table_, column_n, ImGuiSortDirection.Descending, append_to_sort_specs) + -- end + --end + -- #endif + -- Hiding / Visibility if band(flags_for_section_to_display, ImGuiTableFlags.Hideable) ~= 0 then if want_separator then @@ -40521,7 +46284,8 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end want_separator = true - -- While reordering: we calculate min/max allowed range once here so we can avoid a O(N log N) in the loop. + -- While reordering: we calculate min/max allowed range once here so we can avoid a O(N log N) in the loop (because the query itself does a sweep scan). + -- This assume that reordering constraints output a single range, otherwise would need to either call TableGetMaxDisplayOrderAllowed() for each item below, or cache this once per frame into columns. local is_reordering = (g.ActiveId ~= 0 and g.ActiveIdWindow == g.CurrentWindow and table_.ReorderColumn ~= -1 and g.ActiveIdHasBeenEditedBefore) -- FIXME: This is a bit of a hack. local reorder_src_order = is_reordering and table_.Columns[table_.ReorderColumn].DisplayOrder or -1 local reorder_min_order = is_reordering and TableGetMaxDisplayOrderAllowed(table_, reorder_src_order, 0) or 0 @@ -40549,6 +46313,7 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end -- Drag to reorder + -- FIXME: It is currently not possible to reorder columns marked with ImGuiTableColumnFlags.NoHide. if ImGui.IsItemActive() and ImGui.IsMouseDragging(0) and g.ActiveIdSource == ImGuiInputSource.Mouse and band(table_.Flags, ImGuiTableFlags.Reorderable) ~= 0 then g.ActiveIdHasBeenEditedBefore = true -- Disable toggle in MenuItemForColumnReorder() + start dimming to display allowed reorder targets. table_.ReorderColumn = column_n @@ -40565,9 +46330,31 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Settings (.ini data) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- FIXME: The binding/finding/creating flow are too confusing. +------------------------------------------------------------------------------- +-- - TableSettingsInit() [Internal] +-- - TableSettingsCreate() [Internal] +-- - TableSettingsFindByID() [Internal] +-- - TableGetBoundSettings() [Internal] +-- - TableResetSettings() +-- - TableSaveSettings() [Internal] +-- - TableLoadSettings() [Internal] +-- - TableLoadSettingsForColumns() [Internal] +-- - TableSettingsHandler_ClearAll() [Internal] +-- - TableSettingsHandler_ApplyAll() [Internal] +-- - TableSettingsHandler_ReadOpen() [Internal] +-- - TableSettingsHandler_ReadLine() [Internal] +-- - TableSettingsHandler_WriteAll() [Internal] +-- - TableSettingsAddSettingsHandler() [Internal] +------------------------------------------------------------------------------- +-- [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings. +-- [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table. +-- [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty. +-- [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file. +------------------------------------------------------------------------------- -- Clear and initialize empty settings instance local function TableSettingsInit(settings, id, columns_count, columns_count_max) @@ -40599,6 +46386,7 @@ end -- Find existing settings function ImGui.TableSettingsFindByID(id) + -- FIXME-OPT: Might want to store a lookup map for this? local g = GImGui for _, settings in g.SettingsTables:iter() do if settings.ID == id then @@ -40613,7 +46401,7 @@ local function SettingsTablesOffsetFromPtr(settings) return g.SettingsTables:find_index(settings) or -1 end --- Get settings for a given table, NULL if none +-- Get settings for a given table, nil if none function ImGui.TableGetBoundSettings(table_) if table_.SettingsOffset == -1 then return nil @@ -40673,6 +46461,8 @@ function ImGui.TableSaveSettings(table_) end -- We skip saving some data in the .ini file when they are unnecessary to restore our state. + -- Note that fixed width where initial width was derived from auto-fit will always be saved as InitStretchWeightOrWidth will be 0.0f. + -- FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present. if width_or_weight ~= column.InitStretchWeightOrWidth then settings.SaveFlags = bor(settings.SaveFlags, ImGuiTableFlags.Resizable) end @@ -40817,7 +46607,8 @@ function ImGui.TableFixDisplayOrder(table_) for n = 0, table_.ColumnsCount - 1 do fdo_columns[n + 1] = n end - -- Sort by DisplayOrder and then Index. -1 (unsigned short 0xFFFF) always sorts after. + -- Sort by DisplayOrder and then Index + -- Assume ImGuiTableColumnIdx == signed short, to turn -1 into a large value so that it always sort after. local function key(idx) local o = table_.Columns[idx].DisplayOrder if o < 0 then o = o + 0x10000 end @@ -40859,6 +46650,9 @@ local function TableSettingsHandler_ApplyAll(ctx, handler) end local function TableSettingsHandler_ReadOpen(ctx, handler, name) + -- FIXME: As topology changes are allowed, strictly speaking a >= IMGUI_TABLE_MAX_COLUMNS tables stored in .ini file + -- that was emitted with a higher max count could still be meaningful in some unlikely cases. + -- We might want to use another MAX defined as (1<<(sizeof(ImGuiTableColumnIdx)*8-1))-1. local id, columns_count = string.match(name, "^0x(%x+),(%-?%d+)") if id == nil then return nil @@ -40914,6 +46708,8 @@ local function TableSettingsHandler_WriteAll(ctx, handler, buf) local g = ctx for _, settings in g.SettingsTables:iter() do if settings.ID ~= 0 then -- Skip ditched settings + -- TableSaveSettings() may clear some of those flags when we establish that the data can be stripped + -- (e.g. Order was unchanged) local save_size = band(settings.SaveFlags, ImGuiTableFlags.Resizable) ~= 0 local save_visible = band(settings.SaveFlags, ImGuiTableFlags.Hideable) ~= 0 local save_order = band(settings.SaveFlags, ImGuiTableFlags.Reorderable) ~= 0 @@ -40926,6 +46722,7 @@ local function TableSettingsHandler_WriteAll(ctx, handler, buf) end for column_n = 0, settings.ColumnsCount - 1 do local column = settings.Columns[column_n] + -- "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" local save_column = save_size or save_visible or save_order or (save_sort and column.SortOrder ~= -1) if save_column then buf:appendf("Column %-2d", column_n) @@ -40958,12 +46755,17 @@ function ImGui.TableSettingsAddSettingsHandler() ImGui.AddSettingsHandler(ini_handler) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Garbage Collection ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableRemove() [Internal] +-- - TableGcCompactTransientBuffers() [Internal] +-- - TableGcCompactSettings() [Internal] +------------------------------------------------------------------------------- -- Remove Table data (currently only used by TestEngine) function ImGui.TableRemove(table_) + --IMGUI_DEBUG_PRINT("TableRemove() id=0x%08X\n", table_.ID) local g = GImGui local table_idx = g.Tables:GetIndex(table_) g.Tables:Remove(table_.ID, table_) @@ -40980,6 +46782,7 @@ function ImGui.TableGcCompactTransientBuffers(t) t.LastTimeActive = -1.0 return end + --IMGUI_DEBUG_PRINT("TableGcCompactTransientBuffers() id=0x%08X\n", t.ID) local g = GImGui local table_ = t IM_ASSERT(table_.MemoryCompacted == false) @@ -40994,7 +46797,7 @@ function ImGui.TableGcCompactTransientBuffers(t) g.TablesLastTimeActive.Data[g.Tables:GetIndex(table_) + 1] = -1.0 end --- Compact and remove unused or resize settings data +-- Compact and remove unused or resize settings data (only TestEngine mark unused, but resizing table down can lead to compaction) function ImGui.TableGcCompactSettings() local g = GImGui local has_dead = false @@ -41012,10 +46815,28 @@ function ImGui.TableGcCompactSettings() ForEachTable(g, function(t) t.SettingsOffset = -1 end) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Columns, BeginColumns, EndColumns, etc. -- (This is a legacy API, prefer using BeginTable/EndTable!) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- FIXME: sizing is lossy when columns width is very small (default width may turn negative etc.) +------------------------------------------------------------------------------- +-- - GetColumnIndex() +-- - GetColumnsCount() +-- - GetColumnOffset() +-- - GetColumnWidth() +-- - SetColumnOffset() +-- - SetColumnWidth() +-- - PushColumnClipRect() [Internal] +-- - PushColumnsBackground() [Internal] +-- - PopColumnsBackground() [Internal] +-- - FindOrCreateColumns() [Internal] +-- - GetColumnsID() [Internal] +-- - BeginColumns() +-- - NextColumn() +-- - EndColumns() +-- - Columns() +------------------------------------------------------------------------------- -- (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1]) function ImGui.GetColumnIndex() @@ -41039,7 +46860,8 @@ end local COLUMNS_HIT_RECT_HALF_THICKNESS = 4.0 local function GetDraggedColumnOffset(columns, column_index) - -- Active (dragged) column always follow mouse. + -- Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + -- window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. local g = GImGui local window = g.CurrentWindow IM_ASSERT(column_index > 0) -- We are not supposed to drag column 0. @@ -41193,6 +47015,7 @@ function ImGui.GetColumnsID(str_id, columns_count) local window = ImGui.GetCurrentWindow() -- Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + -- In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. ImGui.PushID(0x11223347 + (str_id and 0 or columns_count)) local id = window:GetID(str_id or "columns") ImGui.PopID() @@ -41225,6 +47048,7 @@ function ImGui.BeginColumns(str_id, columns_count, flags) ImRect_Copy(window.ParentWorkRect, window.WorkRect) -- Set state for first column + -- We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect local column_padding = g.Style.ItemSpacing.x local half_clip_extend_x = ImTrunc(ImMax(window.WindowPadding.x * 0.5, window.WindowBorderSize)) local max_1 = window.WorkRect.Max.x + column_padding - ImMax(column_padding - window.WindowPadding.x, 0.0) @@ -41298,6 +47122,7 @@ function ImGui.NextColumn() ImGui.PopItemWidth() -- Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect() + -- (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), local column = columns.Columns.Data[columns.Current + 1] ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect) columns.Splitter:SetCurrentChannel(window.DrawList, columns.Current + 1) @@ -41306,6 +47131,7 @@ function ImGui.NextColumn() columns.LineMaxY = ImMax(columns.LineMaxY, window.DC.CursorPos.y) if columns.Current > 0 then -- Columns 1+ ignore IndentX (by canceling it out) + -- FIXME-COLUMNS: Unnecessary, could be locked? window.DC.ColumnsOffset.x = ImGui.GetColumnOffset(columns.Current) - window.DC.Indent.x + column_padding else -- New row/line: column 0 honor IndentX. @@ -41318,6 +47144,7 @@ function ImGui.NextColumn() window.DC.CurrLineSize.x = 0.0; window.DC.CurrLineSize.y = 0.0 window.DC.CurrLineTextBaseOffset = 0.0 + -- FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. local offset_0 = ImGui.GetColumnOffset(columns.Current) local offset_1 = ImGui.GetColumnOffset(columns.Current + 1) local width = offset_1 - offset_0 @@ -41345,6 +47172,7 @@ function ImGui.EndColumns() end -- Draw columns borders and handle resize + -- The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy local is_being_resized = false if band(flags, ImGuiOldColumnFlags.NoBorder) == 0 and not window.SkipItems then -- We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. @@ -41410,6 +47238,7 @@ function ImGui.Columns(columns_count, id, borders) IM_ASSERT(columns_count >= 1) local flags = borders and 0 or ImGuiOldColumnFlags.NoBorder + --flags = bor(flags, ImGuiOldColumnFlags.NoPreserveWidths) -- NB: Legacy behavior local columns = window.DC.CurrentColumns if columns ~= nil and columns.Count == columns_count and columns.Flags == flags then return @@ -41429,7 +47258,30 @@ end __FILES['imgui_widgets.lua'] = function() --- Dear ImGui WIP --- (Widgets Code) +-- (widgets code) + +-- +-- Index of this file: +-- +-- [SECTION] Widgets: Text, etc. +-- [SECTION] Widgets: Value helpers +-- [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.) +-- [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.) +-- [SECTION] Widgets: ComboBox +-- [SECTION] Data Type and Data Formatting Helpers +-- [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +-- [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +-- [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +-- [SECTION] Widgets: InputText, InputTextMultiline +-- [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +-- [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +-- [SECTION] Widgets: Selectable +-- [SECTION] Widgets: ListBox +-- [SECTION] Widgets: PlotLines, PlotHistogram +-- [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc. +-- [SECTION] Widgets: BeginTabBar, EndTabBar, etc. +-- [SECTION] Widgets: BeginTabItem, EndTabItem, etc. +-- --- @type ImGuiContext? local GImGui @@ -41441,8 +47293,13 @@ function ImGui._SetCurrentContext_Widgets(ctx) GImGui = ctx end -local DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70 -- Time for drag-hold to activate items accepting the ImGuiButtonFlags.PressedOnDragDropHold button behavior -local DRAG_MOUSE_THRESHOLD_FACTOR = 0.50 -- Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags +------------------------------------------------------------------------------- +-- Data +------------------------------------------------------------------------------- + +-- Widgets +local DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70 -- Time for drag-hold to activate items accepting the ImGuiButtonFlags.PressedOnDragDropHold button behavior. +local DRAG_MOUSE_THRESHOLD_FACTOR = 0.50 -- Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags. local IM_S8_MIN = -128 local IM_S8_MAX = 127 @@ -41452,14 +47309,25 @@ local IM_S16_MIN = -32768 local IM_S16_MAX = 32767 local IM_U16_MIN = 0 local IM_U16_MAX = 0xFFFF -local IM_S32_MIN = INT_MIN -local IM_S32_MAX = INT_MAX +local IM_S32_MIN = INT_MIN -- (-2147483647 - 1), (0x80000000); +local IM_S32_MAX = INT_MAX -- (2147483647), (0x7FFFFFFF) local IM_U32_MIN = 0 -local IM_U32_MAX = UINT_MAX +local IM_U32_MAX = UINT_MAX -- (0xFFFFFFFF) ----------------------------------------------------------------- --- [SECTION] TEXT ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Text, etc. +------------------------------------------------------------------------------- +-- - TextEx() [Internal] +-- - TextUnformatted() +-- - Text() +-- - TextV() +-- - TextColored() +-- - TextDisabled() +-- - TextWrapped() +-- - TextAligned() +-- - LabelText() +-- - BulletText() +------------------------------------------------------------------------------- --- @param text string --- @param text_end? int @@ -41474,11 +47342,13 @@ function ImGui.TextEx(text, text_end, flags) return end + -- Accept null ranges if not text or text == "" then text = "" text_end = 1 end + -- Calculate length if text_end == nil then text_end = #text + 1 end @@ -41487,6 +47357,7 @@ function ImGui.TextEx(text, text_end, flags) local wrap_pos_x = window.DC.TextWrapPos local wrap_enabled = (wrap_pos_x >= 0.0) if (text_end - 1 <= 2000) or wrap_enabled then + -- Common case local wrap_width = wrap_enabled and ImGui.CalcWrapWidthForPos(window.DC.CursorPos, wrap_pos_x) or 0.0 local text_size = ImGui.CalcTextSize(text, text_end, false, wrap_width) @@ -41496,12 +47367,18 @@ function ImGui.TextEx(text, text_end, flags) return end + -- Render (we don't hide text after ## in this end-user function) ImGui.RenderTextWrapped(bb.Min, text, text_end, wrap_width) else + -- Long text! + -- Perform manual coarse clipping to optimize for long multi-line text + -- - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. + -- - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. local line = 1 local line_height = ImGui.GetTextLineHeight() local text_size = ImVec2(0, 0) + -- Lines to skip (can't skip when logging text) local pos = ImVec2(text_pos.x, text_pos.y) if not g.LogEnabled then local lines_skippable = ImFloor((window.ClipRect.Min.y - text_pos.y) / line_height) @@ -41523,6 +47400,7 @@ function ImGui.TextEx(text, text_end, flags) end end + -- Lines to render if line < text_end then local line_rect = ImRect(pos, pos + ImVec2(FLT_MAX, line_height)) while line < text_end do @@ -41544,6 +47422,7 @@ function ImGui.TextEx(text, text_end, flags) pos.y = pos.y + line_height end + -- Count remaining lines local lines_skipped = 0 while line < text_end do local line_end = ImMemchr(text, "\n", line) @@ -41619,7 +47498,7 @@ end --- @param ... any function ImGui.TextWrapped(fmt, ...) local g = GImGui - local need_backup = (g.CurrentWindow.DC.TextWrapPos < 0.0) + local need_backup = (g.CurrentWindow.DC.TextWrapPos < 0.0) -- Keep existing wrap position if one is already set if need_backup then ImGui.PushTextWrapPos(0.0) end @@ -41630,8 +47509,8 @@ function ImGui.TextWrapped(fmt, ...) end -- 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) +-- size_x < 0.0f (e.g. -FLT_MIN): shortcut for GetContentRegionAvail().x +-- FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024, #9455) --- @param align_x float --- @param size_x float --- @param fmt string @@ -41661,7 +47540,7 @@ function ImGui.TextAligned(align_x, size_x, fmt, ...) ImVec2_Copy(backup_max_pos, window.DC.CursorMaxPos) ImGui.ItemSize(size) ImGui.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 + window.DC.CursorMaxPos.x = backup_max_pos.x -- Cancel out extending content to 'size' to use 'text_size' allowing auto-resize to function with align_x > 0.0f if size_x < text_size.x and ImGui.IsItemHovered(bit32.bor(ImGuiHoveredFlags.NoNavOverride, ImGuiHoveredFlags.AllowWhenDisabled, ImGuiHoveredFlags.ForTooltip)) then ImGui.SetTooltip("%.*s", text_end - 1, text) @@ -41704,6 +47583,7 @@ function ImGui.LabelText(label, fmt, ...) end end +-- Text with a little bullet aligned to the typical tree node. --- @param fmt string --- @param ... any function ImGui.BulletText(fmt, ...) @@ -41742,6 +47622,13 @@ ImGui.TextAlignedV = ImGui.TextAligned ImGui.LabelTextV = ImGui.LabelText ImGui.BulletTextV = ImGui.BulletText +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Value helpers +-- Those is not very useful, legacy API. +------------------------------------------------------------------------------- +-- - Value() +------------------------------------------------------------------------------- + -- Value(prefix, b) / Value(prefix, int) / Value(prefix, float, float_format) -- Lua can't tell int from float: integers without float_format print as %d, otherwise %.3f function ImGui.Value(prefix, v, float_format) @@ -41756,10 +47643,94 @@ function ImGui.Value(prefix, v, float_format) end end ----------------------------------------------------------------- --- [SECTION] MAIN: BUTTONS, SCROLLBARS, ... ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Main +------------------------------------------------------------------------------- +-- - ButtonBehavior() [Internal] +-- - Button() +-- - SmallButton() +-- - InvisibleButton() +-- - ArrowButton() +-- - CloseButton() [Internal] +-- - CollapseButton() [Internal] +-- - GetWindowScrollbarID() [Internal] +-- - GetWindowScrollbarRect() [Internal] +-- - Scrollbar() [Internal] +-- - ScrollbarEx() [Internal] +-- - Image() +-- - ImageButton() +-- - Checkbox() +-- - CheckboxFlagsT() [Internal] +-- - CheckboxFlags() +-- - RadioButton() +-- - ProgressBar() +-- - Bullet() +-- - Hyperlink() +------------------------------------------------------------------------------- +-- The ButtonBehavior() function is key to many interactions and used by many/most widgets. +-- Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags), +-- this code is a little complex. +-- By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags.PressedOnClickRelease button behavior. +-- See the series of events below and the corresponding state reported by dear imgui: +------------------------------------------------------------------------------- +-- with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+0 (mouse is outside bb) - - - - - - +-- Frame N+1 (mouse moves inside bb) - true - - - - +-- Frame N+2 (mouse button is down) - true true true - true +-- Frame N+3 (mouse button is down) - true true - - - +-- Frame N+4 (mouse moves outside bb) - - true - - - +-- Frame N+5 (mouse moves inside bb) - true true - - - +-- Frame N+6 (mouse button is released) true true - - true - +-- Frame N+7 (mouse button is released) - true - - - - +-- Frame N+8 (mouse moves outside bb) - - - - - - +------------------------------------------------------------------------------- +-- with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+2 (mouse button is down) true true true true - true +-- Frame N+3 (mouse button is down) - true true - - - +-- Frame N+6 (mouse button is released) - true - - true - +-- Frame N+7 (mouse button is released) - true - - - - +------------------------------------------------------------------------------- +-- with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+2 (mouse button is down) - true - - - true +-- Frame N+3 (mouse button is down) - true - - - - +-- Frame N+6 (mouse button is released) true true - - - - +-- Frame N+7 (mouse button is released) - true - - - - +------------------------------------------------------------------------------- +-- with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+0 (mouse button is down) - true - - - true +-- Frame N+1 (mouse button is down) - true - - - - +-- Frame N+2 (mouse button is released) - true - - - - +-- Frame N+3 (mouse button is released) - true - - - - +-- Frame N+4 (mouse button is down) true true true true - true +-- Frame N+5 (mouse button is down) - true true - - - +-- Frame N+6 (mouse button is released) - true - - true - +-- Frame N+7 (mouse button is released) - true - - - - +------------------------------------------------------------------------------- +-- Note that some combinations are supported, +-- - 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 ImGuiItemFlags.ButtonRepeat is set: +-- Repeat+ Repeat+ Repeat+ Repeat+ +-- PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick +------------------------------------------------------------------------------- +-- Frame N+0 (mouse button is down) - true - true +-- ... - - - - +-- Frame N + RepeatDelay true true - true +-- ... - - - - +-- Frame N + RepeatDelay + RepeatRate*N true true - true +------------------------------------------------------------------------------- + +-- - FIXME: For refactor we could output flags, incl mouse hovered vs nav keyboard vs nav triggered etc. +-- 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 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() +-- Returns (pressed, hovered, held). --- @param bb ImRect --- @param id ImGuiID --- @param flags? ImGuiButtonFlags @@ -41771,6 +47742,8 @@ function ImGui.ButtonBehavior(bb, id, flags) local window = g.CurrentWindow + -- 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. local item_flags = (g.LastItemData.ID == id) and g.LastItemData.ItemFlags or g.CurrentItemFlags if bit32.band(flags, ImGuiButtonFlags.AllowOverlap) ~= 0 then item_flags = bit32.bor(item_flags, ImGuiItemFlags.AllowOverlap) @@ -41797,6 +47770,9 @@ function ImGui.ButtonBehavior(bb, id, flags) local pressed = false local hovered = ImGui.ItemHoverable(bb, id, item_flags) + + -- 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 then if (bit32.band(flags, ImGuiButtonFlags.PressedOnDragDropHold) ~= 0) and (bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceNoHoldToOpenOthers) == 0) and ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) then hovered = true @@ -41818,10 +47794,14 @@ function ImGui.ButtonBehavior(bb, id, flags) g.HoveredWindow = backup_hovered_window end + -- Mouse handling local test_owner_id = (bit32.band(flags, ImGuiButtonFlags.NoTestKeyOwner) ~= 0) and ImGuiKeyOwner_Any or id if hovered then - IM_ASSERT(id ~= 0) + IM_ASSERT(id ~= 0) -- Lazily check inside rare path. + -- Poll mouse buttons + -- - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId. + -- - Technically we only need some values in one code path, but since this is gated by hovered test this is fine. local mouse_button_clicked = -1 local mouse_button_released = -1 for button = 0, 2 do @@ -41831,6 +47811,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end end + -- Process initial action local mods_ok = (bit32.band(flags, ImGuiButtonFlags.NoKeyModsAllowed) == 0) or (not g.IO.KeyCtrl and not g.IO.KeyShift and not g.IO.KeyAlt) if mods_ok then if mouse_button_clicked ~= -1 and g.ActiveId ~= id then @@ -41848,7 +47829,7 @@ function ImGui.ButtonBehavior(bb, id, flags) ImGui.SetFocusID(id, window) ImGui.FocusWindow(window) elseif bit32.band(flags, ImGuiButtonFlags.NoFocus) == 0 then - ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) + ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) -- Still need to focus and bring to front, but try to avoid losing NavId when navigating a child end end @@ -41858,7 +47839,7 @@ function ImGui.ButtonBehavior(bb, id, flags) if bit32.band(flags, ImGuiButtonFlags.NoHoldingActiveId) ~= 0 then ImGui.ClearActiveID() else - ImGui.SetActiveID(id, window) + ImGui.SetActiveID(id, window) -- Hold on ID end g.ActiveIdMouseButton = mouse_button_clicked @@ -41867,12 +47848,12 @@ function ImGui.ButtonBehavior(bb, id, flags) ImGui.SetFocusID(id, window) ImGui.FocusWindow(window) elseif bit32.band(flags, ImGuiButtonFlags.NoFocus) == 0 then - ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) + ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) -- Still need to focus and bring to front, but try to avoid losing NavId when navigating a child end end if bit32.band(flags, ImGuiButtonFlags.PressedOnRelease) ~= 0 then - -- FIXME: Traditionally ImGuiButtonFlags.PressedOnRelease never took ActiveId. Adding it in 2026-03-20 since ImGuiButtonFlags_NoHoldingActiveId can always be added. + -- FIXME: Traditionally ImGuiButtonFlags.PressedOnRelease never took ActiveId. Adding it in 2026-03-20 since ImGuiButtonFlags.NoHoldingActiveId can always be added. -- We don't yet perform an explicit ClearActiveID() to reduce scope of change, but this possibility could be investigated. if bit32.band(flags, ImGuiButtonFlags.NoHoldingActiveId) == 0 then ImGui.SetActiveID(id, window) -- Hold on ID @@ -41883,14 +47864,14 @@ function ImGui.ButtonBehavior(bb, id, flags) if bit32.band(flags, ImGuiButtonFlags.PressedOnRelease) ~= 0 then if mouse_button_released ~= -1 then - local has_repeated_at_least_once = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay + local has_repeated_at_least_once = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay -- Repeat mode trumps on release behavior if not has_repeated_at_least_once then pressed = true end if bit32.band(flags, ImGuiButtonFlags.NoNavFocus) == 0 then - ImGui.SetFocusID(id, window) -- FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why. + ImGui.SetFocusID(id, window) -- FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why. end ImGui.ClearActiveID() @@ -41912,7 +47893,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end -- Keyboard/Gamepad navigation handling - -- We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse + -- We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse. if bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then if g.NavId == id and g.NavCursorVisible and g.NavHighlightItemUnderNav then if bit32.band(flags, ImGuiButtonFlags.NoHoveredOnFocus) == 0 then @@ -41945,6 +47926,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end end + -- Process while held local held = false if g.ActiveId == id then if g.ActiveIdSource == ImGuiInputSource.Mouse then @@ -41966,7 +47948,7 @@ function ImGui.ButtonBehavior(bb, id, flags) -- Report as pressed when releasing the mouse (this is the most common path) local is_double_click_release = (bit32.band(flags, ImGuiButtonFlags.PressedOnDoubleClick) ~= 0) and g.IO.MouseReleased[mouse_button] and g.IO.MouseClickedLastCount[mouse_button] == 2 - local is_repeating_already = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay + local is_repeating_already = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay -- Repeat mode trumps local is_button_avail_or_owned = ImGui.TestKeyOwner(ImGui.MouseButtonToKey(mouse_button), test_owner_id) @@ -41984,7 +47966,7 @@ function ImGui.ButtonBehavior(bb, id, flags) elseif g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad then -- When activated using Nav, we hold on the ActiveID until activation button is released if g.NavActivateDownId == id then - held = true -- hovered == true not true as we are already likely hovered on direct activation. + held = true -- hovered == true not true as we are already likely hovered on direct activation. else ImGui.ClearActiveID() end @@ -41995,6 +47977,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end end + -- Activation highlight (this may be a remote activation) if g.NavHighlightActivatedId == id and (bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0) then hovered = true end @@ -42024,7 +48007,7 @@ function ImGui.ButtonEx(label, size_arg, flags) local pos = ImVec2() -- Don't modify the cursor! ImVec2_Copy(pos, window.DC.CursorPos) - if bit32.band(flags, ImGuiButtonFlags.AlignTextBaseLine) ~= 0 and style.FramePadding.y < window.DC.CurrLineTextBaseOffset then + if bit32.band(flags, ImGuiButtonFlags.AlignTextBaseLine) ~= 0 and style.FramePadding.y < window.DC.CurrLineTextBaseOffset then -- Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y = pos.y + window.DC.CurrLineTextBaseOffset - style.FramePadding.y end local size = ImGui.CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0, label_size.y + style.FramePadding.y * 2.0) @@ -42037,6 +48020,7 @@ function ImGui.ButtonEx(label, size_arg, flags) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, flags) + -- Render local col if held and hovered then col = ImGui.GetColorU32(ImGuiCol.ButtonActive) @@ -42068,6 +48052,7 @@ function ImGui.Button(label, size_arg) return ImGui.ButtonEx(label, size_arg, ImGuiButtonFlags.None) end +-- Small buttons fits within text without additional vertical spacing. --- @param label string --- @return bool function ImGui.SmallButton(label) @@ -42079,6 +48064,8 @@ function ImGui.SmallButton(label) return pressed end +-- Tip: use ImGui.PushID()/PopID() to push indices or pointers in the ID stack. +-- Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) --- @param str_id string --- @param size_arg ImVec2 --- @param flags? ImGuiButtonFlags @@ -42150,6 +48137,7 @@ function ImGui.ArrowButton(str_id, dir) return ImGui.ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags.None) end +-- Button to close a window --- @param id ImGuiID --- @param pos ImVec2 --- @return bool @@ -42158,6 +48146,8 @@ function ImGui.CloseButton(id, pos) local window = g.CurrentWindow + -- Tweak 1: Shrink hit-testing area if button covers an abnormally large proportion of the visible region. That's in order to facilitate moving the window away. (#3825) + -- This may better be applied as a general hit-rect reduction mechanism for all widgets to ensure the area to move window is always accessible? local bb = ImRect(pos, pos + ImVec2(g.FontSize, g.FontSize)) local bb_interact = ImRect() ImRect_Copy(bb_interact, bb) @@ -42167,6 +48157,8 @@ function ImGui.CloseButton(id, pos) bb_interact:Expand(ImTrunc(bb_interact:GetSize() * -0.25)) end + -- Tweak 2: We intentionally allow interaction when clipped so that a mechanical Alt,Right,Activate sequence can always close a window. + -- (this isn't the common behavior of buttons, but it doesn't affect the user because navigation tends to keep items visible in scrolling layer). local is_clipped = not ImGui.ItemAdd(bb_interact, id) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id) @@ -42174,6 +48166,7 @@ function ImGui.CloseButton(id, pos) return pressed end + -- Render local bg_col if held then bg_col = ImGui.GetColorU32(ImGuiCol.ButtonActive) @@ -42207,6 +48200,7 @@ function ImGui.CollapseButton(id, pos) local pressed, hovered = ImGui.ButtonBehavior(bb, id) + -- Render if hovered then window.DrawList:AddRectFilled(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.ButtonHovered)) end @@ -42231,6 +48225,7 @@ function ImGui.GetWindowScrollbarID(window, axis) end end +-- Return scrollbar rectangle, must only be called for corresponding axis if window.ScrollbarX/Y is set. --- @param window ImGuiWindow --- @param axis ImGuiAxis --- @return ImRect @@ -42271,6 +48266,12 @@ function ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb, threshold, axis) end end +-- Vertical/Horizontal scrollbar +-- The entire piece of code below is rather confusing because: +-- - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) +-- - 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.. --- @param bb_frame ImRect --- @param id ImGuiID --- @param axis ImGuiAxis @@ -42293,6 +48294,7 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ return false, p_scroll_v end + -- 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) local alpha = 1.0 if axis == ImGuiAxis.Y and bb_frame_height < bb_frame_width then alpha = ImSaturate(bb_frame_height / ImMax(bb_frame_width * 2.0, 1.0)) @@ -42322,7 +48324,9 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ return false, p_scroll_v end - IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0) + -- Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount) + -- But we maintain a minimum size in pixel to allow for the user to still aim inside. + IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0) -- Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. local win_size_v = ImMax(ImMax(size_contents_v, size_visible_v), 1) local grab_h_minsize = ImMin(bb:GetSize()[axis], style.GrabMinSize) local grab_h_pixels = ImTrunc(ImClamp(scrollbar_size_v * (size_visible_v / win_size_v), grab_h_minsize, scrollbar_size_v)) @@ -42333,15 +48337,18 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ ImRect_Copy(bb_hit, bb_frame) ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb_hit, g.Style.WindowBorderSize, ImGuiAxis.X + ImGuiAxis.Y - axis) -- swap axis here + -- Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). ImGui.ItemAdd(bb_frame, id, nil, ImGuiItemFlags.NoNav) local pressed, hovered, held = ImGui.ButtonBehavior(bb_hit, id, ImGuiButtonFlags.NoNavFocus) local scroll_max = ImMax(1, size_contents_v - size_visible_v) local scroll_ratio = ImSaturate(p_scroll_v / scroll_max) - local grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v + local grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v -- Grab position in normalized space if held and allow_interaction and grab_h_norm < 1.0 then local scrollbar_pos_v = bb.Min[axis] local mouse_pos_v = g.IO.MousePos[axis] + + -- Click position in scrollbar normalized space (0.0f->1.0f) local clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v) local held_dir @@ -42353,6 +48360,7 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ held_dir = 0 end if g.ActiveIdIsJustActivated then + -- On initial click when held_dir == 0 (clicked over grab): calculate the distance between mouse and the center of the grab local scroll_to_clicked_location = (g.IO.ConfigScrollbarScrollByPage == false) or g.IO.KeyShift or held_dir == 0 if scroll_to_clicked_location then @@ -42368,10 +48376,14 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ end end + -- Apply scroll (p_scroll_v will generally point on one member of window.Scroll) + -- It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position if g.ScrollbarSeekMode == 0 then + -- Absolute seeking scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5) / (1.0 - grab_h_norm)) p_scroll_v = scroll_v_norm * scroll_max else + -- Page by page if ImGui.IsMouseClickedEx(ImGuiMouseButton.Left, ImGuiInputFlags.Repeat) and held_dir == g.ScrollbarSeekMode then local page_dir if g.ScrollbarSeekMode > 0.0 then @@ -42383,10 +48395,16 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ end end + -- Update values for rendering scroll_ratio = ImSaturate(p_scroll_v / scroll_max) grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v + + -- Update distance to grab now that we have seek'ed and saturated + --if (seek_absolute) + -- g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f; end + -- Render local bg_col = ImGui.GetColorU32(ImGuiCol.ScrollbarBg) local grab_col if held then @@ -42428,7 +48446,8 @@ function ImGui.Scrollbar(axis) window.Scroll[axis] = scroll end --- - `uv0` and `uv1` are texture coordinates +-- - 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. --- @param tex_ref ImTextureRef --- @param image_size ImVec2 --- @param uv0? ImVec2 @@ -42520,7 +48539,7 @@ function ImGui.ImageButtonEx(id, tex_ref, image_size, uv0, uv1, bg_col, tint_col return pressed end --- - ImageButton() adds style.FramePadding*2.0 to provided size. This is in order to facilitate fitting an image in a button. +-- - 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? --- @param str_id string --- @param tex_ref ImTextureRef @@ -42571,12 +48590,13 @@ function ImGui.Checkbox(label, v) local is_visible = ImGui.ItemAdd(total_bb, id) local is_multi_select = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0) if not is_visible then - if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(total_bb) then -- Extra layer of "no logic clip" for box-select support + if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(total_bb) then -- Extra layer of "no logic clip" for box-select support -- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)) return false, v end end + -- Range-Selection/Multi-selection support (header) local checked = v if is_multi_select then -- TODO: MultiSelectItemHeader() @@ -42584,6 +48604,7 @@ function ImGui.Checkbox(label, v) local pressed, hovered, held = ImGui.ButtonBehavior(total_bb, id) + -- Range-Selection/Multi-selection support (footer) if is_multi_select then -- TODO: MultiSelectItemFooter() elseif pressed then @@ -42592,7 +48613,7 @@ function ImGui.Checkbox(label, v) if v ~= checked then v = checked - pressed = true + pressed = true -- return value ImGui.MarkItemEdited(id) end @@ -42763,8 +48784,8 @@ function ImGui.ProgressBar(fraction, size_arg, overlay) return end - -- Fraction < 0.0 will display an indeterminate progress bar animation - -- The value must be animated along with time, so e.g. passing '-1.0 * ImGui.GetTime()' as fraction works + -- Fraction < 0.0f will display an indeterminate progress bar animation + -- The value must be animated along with time, so e.g. passing '-1.0f * ImGui.GetTime()' as fraction works. local is_indeterminate = (fraction < 0.0) if not is_indeterminate then fraction = ImSaturate(fraction) @@ -42828,6 +48849,10 @@ function ImGui.Bullet() ImGui.SameLine(0, style.FramePadding.x * 2.0) end +-- This is provided as a convenience for being an often requested feature. +-- FIXME-STYLE: we delayed adding as there is a larger plan to revamp the styling system. +-- Because of this we currently don't provide many styling options for this widget +-- (e.g. hovered/active colors are automatically inferred from a single color). --- @param label string function ImGui.TextLink(label) local window = ImGui.GetCurrentWindow() @@ -42872,7 +48897,7 @@ function ImGui.TextLink(label) end local line_y = bb.Max.y + ImFloor(g.FontBaked.Descent * g.FontBakedScale * 0.20) - window.DrawList:AddLineH(bb.Min.x, bb.Max.x, line_y, ImGui.GetColorU32(line_colf), 1.0 * ImTrunc(g.Style._MainScale)) -- FIXME-DPI + window.DrawList:AddLineH(bb.Min.x, bb.Max.x, line_y, ImGui.GetColorU32(line_colf), 1.0 * ImTrunc(g.Style._MainScale)) -- FIXME-TEXT: Underline mode -- FIXME-DPI ImGui.PushStyleColor(ImGuiCol.Text, ImGui.GetColorU32(text_colf)) ImGui.RenderText(bb.Min, label, 1, label_end, false) @@ -42894,7 +48919,7 @@ function ImGui.TextLinkOpenURL(label, url) g.PlatformIO.Platform_OpenInShellFn(g, url) end - ImGui.SetItemTooltip(ImGui.LocalizeGetMsg(ImGuiLocKey.OpenLink_s), url) + ImGui.SetItemTooltip(ImGui.LocalizeGetMsg(ImGuiLocKey.OpenLink_s), url) -- It is more reassuring for user to _always_ display URL when it is the same as the label. if ImGui.BeginPopupContextItem() then if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.CopyLink)) then @@ -42906,9 +48931,16 @@ function ImGui.TextLinkOpenURL(label, url) return pressed end ----------------------------------------------------------------- --- [SECTION] Low-level Layout helpers ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Low-level Layout helpers +------------------------------------------------------------------------------- +-- - Spacing() +-- - Dummy() +-- - NewLine() +-- - AlignTextToFramePadding() +-- - SeparatorEx() [Internal] +-- - Separator() +------------------------------------------------------------------------------- function ImGui.Spacing() local window = ImGui.GetCurrentWindow() @@ -42941,8 +48973,7 @@ function ImGui.NewLine() window.DC.LayoutType = ImGuiLayoutType.Vertical window.DC.IsSameLine = false - if window.DC.CurrLineSize.y > 0.0 then - -- In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + if window.DC.CurrLineSize.y > 0.0 then -- In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. ImGui.ItemSize(ImVec2(0, 0)) else ImGui.ItemSize(ImVec2(0.0, g.FontSize)) @@ -42962,6 +48993,9 @@ function ImGui.AlignTextToFramePadding() window.DC.CurrLineTextBaseOffset = ImMax(window.DC.CurrLineTextBaseOffset, g.Style.FramePadding.y) end +-- Horizontal/vertical separating line +-- FIXME: Surprisingly, this seemingly trivial widget is a victim of many different legacy/tricky layout issues. +-- Note how thickness == 1.0f is handled specifically as not moving CursorPos by 'thickness', but other values are. --- @param flags ImGuiSeparatorFlags --- @param thickness float function ImGui.SeparatorEx(flags, thickness) @@ -43001,13 +49035,18 @@ function ImGui.SeparatorEx(flags, thickness) -- We currently don't need to provide the same feature for tables because tables naturally have border features. local columns = (bit32.band(flags, ImGuiSeparatorFlags.SpanAllColumns) ~= 0) and window.DC.CurrentColumns or nil if columns then - x1 = window.Pos.x + window.DC.Indent.x -- Used to be Pos.x before 2023/10/03 + x1 = window.Pos.x + window.DC.Indent.x -- Used to be Pos.x before 2023/10/03 x2 = window.Pos.x + window.Size.x ImGui.PushColumnsBackground() end -- We don't provide our width to the layout so that it doesn't get feed back into AutoFit -- FIXME: This prevents ->CursorMaxPos based bounding box evaluation from working (e.g. TableEndCell) + + -- Between 1.71 and 1.92.7, we maintained a hack where a 1.0f thin Separator() would not impact layout. + -- This was mostly chosen to allow backward compatibility with user's code assuming zero-height when calculating height for layout (e.g. bottom alignment of a status bar). + -- In order to handle scaling we need to scale separator thickness and it would not makes sense to have a disparity depending on height. + ----float thickness_for_layout = (thickness == 1.0f) ? 0.0f : thickness; // FIXME: See 1.70/1.71 Separator() change: makes legacy 1-px separator not affect layout yet. Should change. local bb = ImRect(ImVec2(x1, window.DC.CursorPos.y), ImVec2(x2, window.DC.CursorPos.y + thickness)) ImGui.ItemSize(ImVec2(0.0, thickness)) @@ -43066,7 +49105,7 @@ function ImGui.SeparatorTextEx(id, label, label_end, extra_w) local min_size = ImVec2(label_size.x + extra_w + padding.x * 2.0, ImMax(label_size.y + padding.y * 2.0, separator_thickness)) local bb = ImRect(pos, ImVec2(window.WorkRect.Max.x, pos.y + min_size.y)) - local text_baseline_y = ImTrunc((bb:GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.999) -- ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f)) + local text_baseline_y = ImTrunc((bb:GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.999) --ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f)) ImGui.ItemSize(min_size, text_baseline_y) if not ImGui.ItemAdd(bb, id) then @@ -43078,7 +49117,7 @@ function ImGui.SeparatorTextEx(id, label, label_end, extra_w) local seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5 + 0.999) local label_avail_w = ImMax(0.0, sep2_x2 - sep1_x1 - padding.x * 2.0) - local label_pos = ImVec2(pos.x + padding.x + ImMax(0.0, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y) -- FIXME-ALIGN + local label_pos = ImVec2(pos.x + padding.x + ImMax(0.0, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y) -- FIXME-ALIGN -- This allows using SameLine() to position something in the 'extra_w' window.DC.CursorPosPrevLine.x = label_pos.x + label_size.x @@ -43120,12 +49159,26 @@ function ImGui.SeparatorText(label) return end + -- The SeparatorText() vs SeparatorTextEx() distinction is designed to be considerate that we may want: + -- - allow separator-text to be draggable items (would require a stable ID + a noticeable highlight) + -- - this high-level entry point to allow formatting? (which in turns may require ID separate from formatted string) + -- - because of this we probably can't turn 'string label' into 'string fmt, ...' + -- Otherwise, we can decide that users wanting to drag this would layout a dedicated drag-item, + -- and then we can turn this into a format function. ImGui.SeparatorTextEx(0, label, ImGui.FindRenderedTextEnd(label), 0.0) end ----------------------------------------------------------------- --- [SECTION] COMBO BOX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: ComboBox +------------------------------------------------------------------------------- +-- - CalcMaxPopupHeightFromItemCount() [Internal] +-- - BeginCombo() +-- - BeginComboPopup() [Internal] +-- - EndCombo() +-- - BeginComboPreview() [Internal] +-- - EndComboPreview() [Internal] +-- - Combo() +------------------------------------------------------------------------------- --- @param items_count float --- @return float @@ -43147,7 +49200,7 @@ function ImGui.BeginCombo(label, preview_value, flags) local window = ImGui.GetCurrentWindow() local backup_next_window_data_flags = g.NextWindowData.HasFlags - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values if window.SkipItems then return false end @@ -43194,6 +49247,7 @@ function ImGui.BeginCombo(label, preview_value, flags) return false end + -- Open on click local pressed, hovered, held = ImGui.ButtonBehavior(bb, id) local popup_id = ImHashStr("##ComboPopup", nil, id) local popup_open = ImGui.IsPopupOpen(popup_id, ImGuiPopupFlags.None) @@ -43262,6 +49316,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) return false end + -- Set popup size local w = bb:GetWidth() if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) ~= 0 then g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w) @@ -43269,7 +49324,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) if bit32.band(flags, ImGuiComboFlags.HeightMask_) == 0 then flags = bit32.bor(flags, ImGuiComboFlags.HeightRegular) end - IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiComboFlags.HeightMask_))) + IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiComboFlags.HeightMask_))) -- Only one local popup_max_height_in_items = -1 if bit32.band(flags, ImGuiComboFlags.HeightRegular) ~= 0 then popup_max_height_in_items = 8 @@ -43280,7 +49335,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) end local constraint_min = ImVec2(0.0, 0.0) local constraint_max = ImVec2(FLT_MAX, FLT_MAX) - if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.x <= 0.0 then + if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.x <= 0.0 then -- Don't apply constraints if user specified a size constraint_min.x = w end if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.y <= 0.0 then @@ -43290,7 +49345,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) end -- This is essentially a specialized version of BeginPopupEx() - local name = ImFormatString("##Combo_%02d", g.BeginComboDepth) + local name = ImFormatString("##Combo_%02d", g.BeginComboDepth) -- Recycle windows based on depth -- Set position given a custom constraint (peak into expected window size so we can position it) -- FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function? @@ -43300,7 +49355,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) if popup_window.WasActive then -- Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us. local size_expected = ImGui.CalcWindowNextAutoFitSize(popup_window) - popup_window.AutoPosLastDirection = (bit32.band(flags, ImGuiComboFlags.PopupAlignLeft) ~= 0) and ImGuiDir.Left or ImGuiDir.Down + popup_window.AutoPosLastDirection = (bit32.band(flags, ImGuiComboFlags.PopupAlignLeft) ~= 0) and ImGuiDir.Left or ImGuiDir.Down -- Left = "Below, Toward Left", Down = "Below, Toward Right (default)" local r_outer = ImGui.GetPopupAllowedExtentRect(popup_window) local pos pos, popup_window.AutoPosLastDirection = ImGui.FindBestWindowPosForPopupEx(bb:GetBL(), size_expected, popup_window.AutoPosLastDirection, r_outer, bb, ImGuiPopupPositionPolicy.ComboBox) @@ -43340,8 +49395,11 @@ function ImGui.EndCombo() ImGui.EndPopup() end --- Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements --- (Experimental, see GitHub issues: #1658, #4168) +-- Submit preview contents for BeginCombo()/EndCombo(), to display contents that's more than just a text label. +-- - [BETA] See GitHub issues: #1658, #4168. +-- - Call directly after the BeginCombo/EndCombo block (requires ImGuiComboFlags.CustomPreview). +-- - The preview is designed to only host non-interactive elements. +-- - Not compatible with ImGuiComboFlags.WidthFitPreview. function ImGui.BeginComboPreview() local g = GImGui local window = g.CurrentWindow @@ -43379,6 +49437,7 @@ function ImGui.EndComboPreview() local window = g.CurrentWindow local preview_data = g.ComboPreviewData + -- FIXME: Using CursorMaxPos approximation instead of correct AABB which we will store in ImDrawCmd in the future local draw_list = window.DrawList if window.DC.CursorMaxPos.x < preview_data.PreviewRect.Max.x and window.DC.CursorMaxPos.y < preview_data.PreviewRect.Max.y then if draw_list.CmdBuffer.Size > 1 then -- Unlikely case that the PushClipRect() didn't create a command @@ -43391,7 +49450,7 @@ function ImGui.EndComboPreview() ImGui.PopClipRect() ImVec2_Copy(window.DC.CursorPos, preview_data.BackupCursorPos) - ImVec2_Copy(window.DC.CursorMaxPos, ImMax(window.DC.CursorMaxPos, preview_data.BackupCursorMaxPos)) + ImVec2_Copy(window.DC.CursorMaxPos, ImMax(window.DC.CursorMaxPos, preview_data.BackupCursorMaxPos)) -- No need to do the same with IdealMaxPos ImVec2_Copy(window.DC.CursorPosPrevLine, preview_data.BackupCursorPosPrevLine) window.DC.PrevLineTextBaseOffset = preview_data.BackupPrevLineTextBaseOffset window.DC.LayoutType = preview_data.BackupLayout @@ -43454,6 +49513,7 @@ function ImGui.Combo(label, current_item, a, b, c, d) local getter, user_data, items_count, popup_max_height_in_items = Items_ResolveArgs(a, b, c, d) if popup_max_height_in_items == nil then popup_max_height_in_items = -1 end + -- Call the getter to obtain the preview string which is a parameter to BeginCombo() local preview_value = nil if bit32.band(bit32.bor(g.NextItemData.ItemFlagsSet, g.CurrentItemFlags), ImGuiItemFlags.MixedValue) ~= 0 then preview_value = "" @@ -43461,6 +49521,7 @@ function ImGui.Combo(label, current_item, a, b, c, d) preview_value = getter(user_data, current_item) end + -- 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 and bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) == 0 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))) end @@ -43469,6 +49530,7 @@ function ImGui.Combo(label, current_item, a, b, c, d) return current_item, false end + -- Display items local value_changed = false local clipper = ImGuiListClipper() clipper:Begin(items_count) @@ -43501,9 +49563,18 @@ function ImGui.Combo(label, current_item, a, b, c, d) return current_item, value_changed end ----------------------------------------------------------------- --- [SECTION] DATA TYPE & DATA FORMATTING [Internal] ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Data Type and Data Formatting Helpers [Internal] +------------------------------------------------------------------------------- +-- - DataTypeGetInfo() +-- - DataTypeFormatString() +-- - DataTypeApplyOp() +-- - DataTypeApplyFromText() +-- - DataTypeCompare() +-- - DataTypeClamp() +-- - GetMinimumStepAtDecimalPrecision +-- - RoundScalarWithFormat<>() +------------------------------------------------------------------------------- local function float(val) return val end local function double(val) return val end @@ -43524,16 +49595,16 @@ local function ImGuiDataTypeInfo(size, name, print_fmt, scan_fmt) end local GDataTypeInfo = { - ImGuiDataTypeInfo(1, "S8", "%d", "%d"), + ImGuiDataTypeInfo(1, "S8", "%d", "%d"), -- ImGuiDataType.S8 ImGuiDataTypeInfo(1, "U8", "%u", "%u"), - ImGuiDataTypeInfo(2, "S16", "%d", "%d"), + ImGuiDataTypeInfo(2, "S16", "%d", "%d"), -- ImGuiDataType.S16 ImGuiDataTypeInfo(2, "U16", "%u", "%u"), - ImGuiDataTypeInfo(4, "S32", "%d", "%d"), + ImGuiDataTypeInfo(4, "S32", "%d", "%d"), -- ImGuiDataType.S32 ImGuiDataTypeInfo(4, "U32", "%u", "%u"), - ImGuiDataTypeInfo(4, "float", "%.3f", "%f"), - ImGuiDataTypeInfo(8, "double", "%f", "%lf"), - ImGuiDataTypeInfo(1, "bool", "%d", "%d"), - ImGuiDataTypeInfo(0, "string", "%s", "%s") + ImGuiDataTypeInfo(4, "float", "%.3f", "%f"), -- ImGuiDataType.Float + ImGuiDataTypeInfo(8, "double", "%f", "%lf"), -- ImGuiDataType.Double + ImGuiDataTypeInfo(1, "bool", "%d", "%d"), -- ImGuiDataType.Bool + ImGuiDataTypeInfo(0, "string", "%s", "%s") -- ImGuiDataType.String } --- @param data_type ImGuiDataType @@ -43633,12 +49704,15 @@ end local ImParseFormatSanitizeForScanning +-- User can input math operators (e.g. +100) to edit a numerical values. +-- NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess.. --- @param buf char[] --- @param data_type ImGuiDataType --- @param data number --- @param format string --- @param data_when_empty? number function ImGui.DataTypeApplyFromText(buf, data_type, data, format, data_when_empty) + -- Copy the value so we can compare at the end of the function if it changed at all. local type_info = ImGui.DataTypeGetInfo(data_type) local data_backup = data @@ -43654,16 +49728,19 @@ function ImGui.DataTypeApplyFromText(buf, data_type, data, format, data_when_emp return data, false end + -- Sanitize format + -- - For float/double we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in, so force them into %f and %lf local format_sanitized, format_sanitized_size = {}, 32 if (data_type == ImGuiDataType.Float or data_type == ImGuiDataType.Double) then format = type_info.ScanFmt else format = ImParseFormatSanitizeForScanning(format, format_sanitized, format_sanitized_size) if format[1] == 0 then - format = type_info.ScanFmt + format = type_info.ScanFmt -- Format doesn't want us to show the number currently, but we still need to parse the resulting input end end + -- Small types need a 32-bit buffer to receive the result from scanf() local v32 = 0 local res = {} if ImStd.sscanf(buf, 1, format, res) < 1 then @@ -43724,6 +49801,7 @@ end --- @param v_max? T --- @return T, boolean local function DataTypeClampT(v, v_min, v_max) + -- Clamp, both sides are optional, return true if modified if v_min and v < v_min then return v_min, true end if v_max and v > v_max then return v_max, true end return v, false @@ -43788,16 +49866,37 @@ function ImGui.RoundScalarWithFormatT(format, data_type, v) -- TODO: Sanitize format + -- Format value with our rounding, and read back local str = ImFormatString(format, v) v = ImAtof(str) or v return v end ----------------------------------------------------------------- --- [SECTION] INPUTXXX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +------------------------------------------------------------------------------- +-- - ImParseFormatFindStart() [Internal] +-- - ImParseFormatFindEnd() [Internal] +-- - ImParseFormatTrimDecorations() [Internal] +-- - ImParseFormatSanitizeForScanning() [Internal] +-- - ImParseFormatPrecision() [Internal] +-- - TempInputText() [Internal] +-- - TempInputScalar() [Internal] +-- - InputScalar() +-- - InputScalarN() +-- - InputFloat() +-- - InputFloat2() +-- - InputFloat3() +-- - InputFloat4() +-- - InputInt() +-- - InputInt2() +-- - InputInt3() +-- - InputInt4() +-- - InputDouble() +------------------------------------------------------------------------------- +-- We don't use strchr() because our strings are usually very short and often start with '%' --- @param fmt string function ImParseFormatFindStart(fmt) local len = #fmt @@ -43818,7 +49917,7 @@ end --- @param fmt string --- @param pos int local function ImParseFormatFindEnd(fmt, pos) - -- Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format + -- Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format. if string.byte(fmt, pos) ~= 37 then -- '%' return pos end @@ -43838,6 +49937,10 @@ local function ImParseFormatFindEnd(fmt, pos) return len + 1 end +-- Extract the format out of a format string with leading or trailing decorations +-- fmt = "blah blah" -> return "" +-- fmt = "%.3f" -> return "%.3f" +-- fmt = "hello %.3f" -> return "%.3f" -- TODO: temporary patch. does not look good --- @param fmt string local function ImParseFormatTrimDecorations(fmt) @@ -43853,13 +49956,14 @@ local function ImParseFormatTrimDecorations(fmt) return string.sub(fmt, fmt_start, fmt_end) end +-- - For scanning we need to remove all width and precision fields and flags "%+3.7f" -> "%f". BUT don't strip types like "%I64d" which includes digits. ! "%07I64d" -> "%I64d" --- @param fmt_in string --- @param fmt_out char[] --- @param fmt_out_size size_t function ImParseFormatSanitizeForScanning(fmt_in, fmt_out, fmt_out_size) local fmt_end = ImParseFormatFindEnd(fmt_in, 1) -- IM_UNUSED(fmt_out_size) - IM_ASSERT(fmt_end < fmt_out_size) + IM_ASSERT(fmt_end < fmt_out_size) -- Format is too long, let us know if this happens to you! local has_type = false local fmt_in_begin = 1 local fmt_out_begin = 1 @@ -43872,15 +49976,15 @@ function ImParseFormatSanitizeForScanning(fmt_in, fmt_out, fmt_out_size) break end - has_type = has_type or ((c >= 97 and c <= 122) or (c >= 65 and c <= 90)) - if c ~= 39 and c ~= 36 and c ~= 95 then + has_type = has_type or ((c >= 97 and c <= 122) or (c >= 65 and c <= 90)) -- Stop skipping digits + if c ~= 39 and c ~= 36 and c ~= 95 then -- Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '. fmt_out[fmt_out_begin] = c fmt_out_begin = fmt_out_begin + 1 end until true end - -- fmt_out[fmt_out_begin] = 0 + -- fmt_out[fmt_out_begin] = 0 -- Zero-terminate return string.char(unpack(fmt_out)) -- FIXME: not ideal end @@ -43907,6 +50011,8 @@ local function ImAtoi(str, pos) return negative and -v or v, pos end +-- Parse display precision back from the display format string +-- FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed. --- @param fmt string --- @param default_precision int local function ImParseFormatPrecision(fmt, default_precision) @@ -43939,6 +50045,9 @@ local function ImParseFormatPrecision(fmt, default_precision) return (precision == INT_MAX) and default_precision or precision end +-- Create text input in place of another active widget (e.g. used when doing a Ctrl+Click on drag/slider widgets) +-- - This must be submitted right after the item it is overlaying. +-- FIXME: Facilitate using this in variety of other situations. --- @param bb ImRect --- @param id ImGuiID --- @param label string @@ -43950,6 +50059,8 @@ end function ImGui.TempInputText(bb, id, label, buf, buf_size, flags, callback, user_data) if flags == nil then flags = 0 end + -- On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id. + -- We clear ActiveID on the first frame to allow the InputText() taking it back. local g = GImGui local window = g.CurrentWindow @@ -43962,10 +50073,11 @@ function ImGui.TempInputText(bb, id, label, buf, buf_size, flags, callback, user local backup_pos = ImVec2() ImVec2_Copy(backup_pos, window.DC.CursorPos) ImVec2_Copy(window.DC.CursorPos, bb.Min) - g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowDuplicateId) + g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowDuplicateId) -- Using ImGuiInputTextFlags.MergedItem above will skip ItemAdd() so we poke here. local value_changed = ImGui.InputTextEx(label, nil, buf, buf_size, bb:GetSize(), bit32.bor(flags, ImGuiInputTextFlags.TempInput, ImGuiInputTextFlags.AutoSelectAll), callback, user_data) - ImGui.KeepAliveID(id) + ImGui.KeepAliveID(id) -- Not done because of ImGuiInputTextFlags.TempInput if (not is_active and not is_deactivated) then + -- First frame we started displaying the InputText widget, we expect it to take the active id. IM_ASSERT(g.ActiveId == id) g.TempInputId = g.ActiveId end @@ -43977,6 +50089,9 @@ function ImGui.TempInputText(bb, id, label, buf, buf_size, flags, callback, user return value_changed end +-- Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags.AlwaysClamp flag is set! +-- This is intended: this way we allow Ctrl+Click manual input to set a value out of bounds, for maximum flexibility. +-- However this may not be ideal for all uses, as some user code may break on out of bound values. --- @param bb ImRect --- @param id ImGuiID --- @param label string @@ -43986,6 +50101,8 @@ end --- @param clamp_min? number --- @param clamp_max? number function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min, clamp_max) + -- FIXME: May need to clarify display behavior if format doesn't contain %. + -- "%d" -> "%d" / "There are %d items" -> "%d" / "items" -> "%d" (fallback). Also see #6405 local g = GImGui local type_info = ImGui.DataTypeGetInfo(data_type) local data_buf, data_buf_size = {}, 32 @@ -43997,14 +50114,16 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min ImStd.ImStrTrimBlanks(data_buf) local flags = bit32.bor(ImGuiInputTextFlags.AutoSelectAll, ImGuiInputTextFlags.LocalizeDecimalPoint) - g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited) + g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited) -- Because TempInputText() uses ImGuiInputTextFlags.MergedItem it doesn't submit a new item, so we poke LastItemData. g.LastItemData.ItemFlags = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0) and bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputText) or bit32.band(g.LastItemData.ItemFlags, bit32.bnot(ImGuiItemFlags.LiveEditOnInputText)) if not ImGui.TempInputText(bb, id, label, data_buf, data_buf_size, flags) then return data, false end + -- Backup old value local data_backup = data + -- Apply new value (or operations) then clamp data = ImGui.DataTypeApplyFromText(data_buf, data_type, data, format, nil) if clamp_min or clamp_max then if clamp_min and clamp_max and ImGui.DataTypeCompare(data_type, clamp_min, clamp_max) > 0 then @@ -44013,6 +50132,7 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min data = ImGui.DataTypeClamp(data_type, data, clamp_min, clamp_max) end + -- Only mark as edited if new value is different g.LastItemData.ItemFlags = bit32.band(g.LastItemData.ItemFlags, bit32.bnot(ImGuiItemFlags.NoMarkEdited)) local value_changed = data_backup ~= data if value_changed then @@ -44022,6 +50142,8 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min return data, value_changed end +-- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For an Input widget, step and step_fast are optional. +-- Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @param label string --- @param data_type ImGuiDataType --- @param data number @@ -44039,6 +50161,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag local g = GImGui local style = g.Style + -- IM_ASSERT((flags & ImGuiInputTextFlags.EnterReturnsTrue) == 0) -- Not supported by InputScalar(). Please open an issue if you this would be useful to you. Otherwise use IsItemDeactivatedAfterEdit()! if format == nil then format = ImGui.DataTypeGetInfo(data_type).PrintFmt @@ -44053,6 +50176,8 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag ImGui.DataTypeFormatString(buf, buf_size, data_type, data, format) end + -- Disable the MarkItemEdited() call in InputText but keep ImGuiItemStatusFlags.Edited. + -- We call MarkItemEdited() ourselves by comparing the actual data rather than the string. g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoMarkEdited) flags = bit32.bor(flags, ImGuiInputTextFlags.AutoSelectAll, ImGuiInputTextFlags.LocalizeDecimalPoint) @@ -44060,18 +50185,21 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag local button_size = has_step_buttons and ImGui.GetFrameHeight() or 0.0 local ret if has_step_buttons then - ImGui.BeginGroup() + -- With Step Buttons + ImGui.BeginGroup() -- The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() ImGui.PushID(label) ImGui.SetNextItemWidth(ImMax(1.0, ImGui.CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)) - ret = ImGui.InputText("", buf, buf_size, flags) + ret = ImGui.InputText("", buf, buf_size, flags) -- PushID(label) + "" gives us the expected ID from outside point of view -- IMGUI_TEST_ENGINE_ITEM_INFO() else + -- Without Step Buttons ret = ImGui.InputText(label, buf, buf_size, flags) end + -- Apply local value_changed = false if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0 then - local input_edited = bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal) ~= 0 + local input_edited = bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal) ~= 0 -- We would be using 'ret' if ImGuiInputTextFlags.EnterReturnsTrue was not involved. if input_edited then data, value_changed = ImGui.DataTypeApplyFromText(buf, data_type, data, format, bit32.band(flags, ImGuiInputTextFlags.ParseEmptyRefVal) ~= 0 and data_default or nil) end @@ -44084,6 +50212,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag end end + -- Step buttons if has_step_buttons then local backup_frame_padding = ImVec2() ImVec2_Copy(backup_frame_padding, style.FramePadding) @@ -44216,6 +50345,7 @@ function ImGui.InputInt(label, v, step, step_fast, flags) if step_fast == nil then step_fast = 100 end if flags == nil then flags = 0 end + -- Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. local format = (bit32.band(flags, ImGuiInputTextFlags.CharsHexadecimal) ~= 0) and "%08X" or "%d" return ImGui.InputScalar(label, ImGuiDataType.S32, v, (step > 0) and step or nil, (step_fast > 0) and step_fast or nil, format, flags) end @@ -44248,9 +50378,24 @@ function ImGui.InputDouble(label, v, step, step_fast, format, flags) return ImGui.InputScalar(label, ImGuiDataType.Double, v, (step > 0.0 and step or nil), (step_fast > 0.0 and step_fast or nil), format, flags) end ----------------------------------------------------------------- --- [SECTION] DRAGXXX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +------------------------------------------------------------------------------- +-- - DragBehaviorT<>() [Internal] +-- - DragBehavior() [Internal] +-- - DragScalar() +-- - DragScalarN() +-- - DragFloat() +-- - DragFloat2() +-- - DragFloat3() +-- - DragFloat4() +-- - DragFloatRange2() +-- - DragInt() +-- - DragInt2() +-- - DragInt3() +-- - DragInt4() +-- - DragIntRange2() +------------------------------------------------------------------------------- -- This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) --- @generic T : number @@ -44314,7 +50459,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m end adjust_delta = adjust_delta * v_speed - -- For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter + -- For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter. if axis == ImGuiAxis.Y then adjust_delta = -adjust_delta end @@ -44369,7 +50514,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m v_cur = ImGui.RoundScalarWithFormatT(format, data_type, v_cur) end - -- Preserve remainder after rounding has been applied. This also allow slow tweaking of values + -- Preserve remainder after rounding has been applied. This also allow slow tweaking of values. g.DragCurrentAccumDirty = false if is_logarithmic then -- Convert to parametric space, apply delta, convert back @@ -44379,7 +50524,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m g.DragCurrentAccum = g.DragCurrentAccum - ((SIGNEDTYPE)(v_cur) - (SIGNEDTYPE)(v)) end - -- This does nothing + -- Lose zero sign for float/double if v_cur == (TYPE)(-0) then v_cur = (TYPE)(0) end @@ -44394,7 +50539,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m v_cur = (TYPE)(v_cur - (TYPE)((TYPE)(v_max - v_min) - (is_floating_point and 0 or 1))) end else - -- Clamp values + handle overflow/wrap-around for integer types + -- Clamp values + handle overflow/wrap-around for integer types. if v_cur < v_min or (v_cur > v and adjust_delta < 0.0 and not is_floating_point) then v_cur = (TYPE)(v_min) end @@ -44422,8 +50567,10 @@ end --- @param flags ImGuiSliderFlags function ImGui.DragBehavior(id, data_type, v, v_speed, min, max, format, flags) + -- Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. IM_ASSERT((flags == 1 or bit32.band(flags, ImGuiSliderFlags.InvalidMask_) == 0), "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.") + -- Things we can do easily outside the DragBehaviorT<> template, saves code generation. local g = GImGui if g.ActiveId == id then if g.ActiveIdSource == ImGuiInputSource.Mouse and not g.IO.MouseDown[0] then @@ -44461,6 +50608,7 @@ function ImGui.DragBehavior(id, data_type, v, v_speed, min, max, format, flags) return v, false end +-- Only clamp Ctrl+Click input when ImGuiSliderFlags.ClampOnInput is set (generally via ImGuiSliderFlags.AlwaysClamp) --- @param flags ImGuiSliderFlags --- @param data_type ImGuiDataType --- @param min number @@ -44469,7 +50617,7 @@ local function TempInputIsClampEnabled(flags, data_type, min, max) if bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 and (min ~= nil or max ~= nil) then local clamp_range_dir = 0 if min ~= nil and max ~= nil then - clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) + clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) -- -1 when min < max, == 0 when min == max end if min == nil or max == nil or clamp_range_dir < 0 then return true @@ -44504,6 +50652,8 @@ function FormatCached(format, v) return r end +-- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a Drag widget, min and max are optional. +-- Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, flags) if v_speed == nil then v_speed = 1.0 end @@ -44538,6 +50688,7 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla local hovered = ImGui.ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags) local temp_input_is_active = temp_input_allowed and ImGui.TempInputIsActive(id) if not temp_input_is_active then + -- Tabbing or Ctrl+Click on Drag turns it into an InputText local clicked = hovered and ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, id) local double_clicked = (hovered and g.IO.MouseClickedCount[0] == 2 and ImGui.TestKeyOwner(ImGuiKey.MouseLeft, id)) local make_active = (clicked or double_clicked or g.NavActivateId == id) @@ -44597,7 +50748,7 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla -- TODO: ImGui.DataTypeFormatString() should be used here instead of ImFormatString() - -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value + -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value. ImGui.RenderTextClipped(frame_bb.Min, frame_bb.Max, FormatCached(format, data), nil, nil, DRAG_TEXT_ALIGN) if label_size.x > 0.0 then @@ -44624,6 +50775,7 @@ function ImGui.DragFloat(label, v, v_speed, v_min, v_max, format, flags) return ImGui.DragScalar(label, ImGuiDataType.Float, v, v_speed, v_min, v_max, format, flags) end +-- NB: v_speed is float to allow adjusting the drag speed with more precision --- @param label string --- @param v int --- @param v_speed? float @@ -44700,7 +50852,7 @@ ImGui.DragInt2 = DragIntN(2) ImGui.DragInt3 = DragIntN(3) ImGui.DragInt4 = DragIntN(4) --- NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. +-- NB: You likely want to specify the ImGuiSliderFlags.AlwaysClamp when using this. --- @return float v_current_min --- @return float v_current_max --- @return bool value_changed @@ -44748,9 +50900,28 @@ function ImGui.DragIntRange2(label, v_current_min, v_current_max, v_speed, v_min return DragRange2(ImGuiDataType.S32, label, v_current_min, v_current_max, v_speed or 1.0, v_min or 0, v_max or 0, format or "%d", format_max, flags or 0) end ----------------------------------------------------------------- --- [SECTION] SLIDERXXX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +------------------------------------------------------------------------------- +-- - ScaleRatioFromValueT<> [Internal] +-- - ScaleValueFromRatioT<> [Internal] +-- - SliderBehaviorT<>() [Internal] +-- - SliderBehavior() [Internal] +-- - SliderScalar() +-- - SliderScalarN() +-- - SliderFloat() +-- - SliderFloat2() +-- - SliderFloat3() +-- - SliderFloat4() +-- - SliderAngle() +-- - SliderInt() +-- - SliderInt2() +-- - SliderInt3() +-- - SliderInt4() +-- - VSliderScalar() +-- - VSliderFloat() +-- - VSliderInt() +------------------------------------------------------------------------------- -- Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT) --- @param data_type ImGuiDataType @@ -44896,7 +51067,11 @@ function ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, t, v_min, v_max local is_floating_point = (data_type == ImGuiDataType.Float) or (data_type == ImGuiDataType.Double) if is_floating_point then result = ImLerp(v_min, v_max, t) - elseif t < 1.0 then + elseif t < 1.0 then -- t is already < 1.0 here + -- - For integer values we want the clicking position to match the grab box so we round above + -- This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. + -- - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64 + -- range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits. local v_new_off_f = (SIGNEDTYPE)((v_max - v_min)) * t result = (TYPE)((SIGNEDTYPE)(v_min) + (SIGNEDTYPE)(v_new_off_f + 0)) -- LUA: + 0 instead of + ((v_min > v_max) and -0.5 or 0.5) end @@ -44905,6 +51080,7 @@ function ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, t, v_min, v_max return result end +-- FIXME: Try to move more of the code into shared SliderBehavior() --- @generic T : number --- @param TYPE fun(val: number): T --- @param SIGNEDTYPE fun(val: number): T @@ -44926,27 +51102,30 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ local axis = (bit32.band(flags, ImGuiSliderFlags.Vertical) ~= 0) and ImGuiAxis.Y or ImGuiAxis.X local is_logarithmic = bit32.band(flags, ImGuiSliderFlags.Logarithmic) ~= 0 local is_floating_point = (data_type == ImGuiDataType.Float) or (data_type == ImGuiDataType.Double) - local v_range_f = (v_min < v_max) and (v_max - v_min) or (v_min - v_max) + local v_range_f = (v_min < v_max) and (v_max - v_min) or (v_min - v_max) -- We don't need high precision for what we do with it. - local grab_padding = 2.0 + -- Calculate bounds + local grab_padding = 2.0 -- FIXME: Should be part of style. local slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0 local grab_sz = style.GrabMinSize - if not is_floating_point and v_range_f >= 0.0 then - grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize) + if not is_floating_point and v_range_f >= 0.0 then -- v_range_f < 0 may happen on integer overflows + grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize) -- For integer sliders: if possible have the grab size represent 1 unit end grab_sz = ImMin(grab_sz, slider_sz) local slider_usable_sz = slider_sz - grab_sz local slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5 local slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5 - local logarithmic_zero_epsilon = 0.0 - local zero_deadzone_halfsize = 0.0 + local logarithmic_zero_epsilon = 0.0 -- Only valid when is_logarithmic is true + local zero_deadzone_halfsize = 0.0 -- Only valid when is_logarithmic is true if is_logarithmic then + -- When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. local decimal_precision = is_floating_point and ImParseFormatPrecision(format, 3) or 1 logarithmic_zero_epsilon = ImPow(0.1, decimal_precision) zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5) / ImMax(slider_usable_sz, 1.0) end + -- Process interacting with the slider local value_changed = false if g.ActiveId == id then local set_new_value = false @@ -44962,7 +51141,7 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ grab_t = 1.0 - grab_t end local grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t) - local clicked_around_grab = (mouse_abs_pos >= grab_pos - grab_sz * 0.5 - 1.0) and (mouse_abs_pos <= grab_pos + grab_sz * 0.5 + 1.0) + local clicked_around_grab = (mouse_abs_pos >= grab_pos - grab_sz * 0.5 - 1.0) and (mouse_abs_pos <= grab_pos + grab_sz * 0.5 + 1.0) -- No harm being extra generous here. g.SliderGrabClickOffset = (clicked_around_grab and is_floating_point) and (mouse_abs_pos - grab_pos) or 0.0 end if slider_usable_sz > 0.0 then @@ -44975,7 +51154,7 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ end elseif g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad then if g.ActiveIdIsJustActivated then - g.SliderCurrentAccum = 0.0 + g.SliderCurrentAccum = 0.0 -- Reset any stored nav delta upon activation g.SliderCurrentAccumDirty = false end @@ -44985,13 +51164,13 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ local tweak_fast = ImGui.IsKeyDown((g.NavInputSource == ImGuiInputSource.Gamepad) and ImGuiKey.NavGamepadTweakFast or ImGuiKey.NavKeyboardTweakFast) local decimal_precision = is_floating_point and ImParseFormatPrecision(format, 3) or 0 if decimal_precision > 0 then - input_delta = input_delta / 100.0 + input_delta = input_delta / 100.0 -- Keyboard/Gamepad tweak speeds in % of slider bounds if tweak_slow then input_delta = input_delta / 10.0 end else if (v_range_f >= -100.0 and v_range_f <= 100.0 and v_range_f ~= 0.0) or tweak_slow then - input_delta = ((input_delta < 0.0) and -1.0 or 1.0) / v_range_f + input_delta = ((input_delta < 0.0) and -1.0 or 1.0) / v_range_f -- Keyboard/Gamepad tweak speeds in integer steps else input_delta = input_delta / 100.0 end @@ -45010,14 +51189,15 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ elseif g.SliderCurrentAccumDirty then clicked_t = ImGui.ScaleRatioFromValueT(data_type, v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) - if (clicked_t >= 1.0 and delta > 0.0) or (clicked_t <= 0.0 and delta < 0.0) then + if (clicked_t >= 1.0 and delta > 0.0) or (clicked_t <= 0.0 and delta < 0.0) then -- This is to avoid applying the saturation when already past the limits set_new_value = false - g.SliderCurrentAccum = 0.0 + g.SliderCurrentAccum = 0.0 -- If pushing up against the limits, don't continue to accumulate else set_new_value = true local old_clicked_t = clicked_t clicked_t = ImSaturate(clicked_t + delta) + -- Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator local v_new = ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) if is_floating_point and bit32.band(flags, ImGuiSliderFlags.NoRoundToFormat) == 0 then v_new = ImGui.RoundScalarWithFormatT(format, data_type, v_new) @@ -45044,10 +51224,12 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ if set_new_value then local v_new = ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) + -- Round to user desired precision based on format string if is_floating_point and bit32.band(flags, ImGuiSliderFlags.NoRoundToFormat) == 0 then v_new = ImGui.RoundScalarWithFormatT(format, data_type, v_new) end + -- Apply result if v ~= v_new then v = v_new value_changed = true @@ -45058,6 +51240,7 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ if slider_sz < 1.0 then ImRect_Copy(out_grab_bb, ImRect(bb.Min, bb.Min)) else + -- Output grab position so it can be displayed by the caller local grab_t = ImGui.ScaleRatioFromValueT(data_type, v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) if axis == ImGuiAxis.Y then grab_t = 1.0 - grab_t @@ -45073,6 +51256,9 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ return v, value_changed end +-- For 32-bit and larger types, slider bounds are limited to half the natural type range. +-- So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. +-- It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. --- @generic T : number --- @param bb ImRect --- @param id ImGuiID @@ -45086,8 +51272,9 @@ end --- @return T v --- @return bool value_changed function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out_grab_bb) + -- Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. IM_ASSERT((flags == 1 or bit32.band(flags, ImGuiSliderFlags.InvalidMask_) == 0), "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.") - IM_ASSERT(bit32.band(flags, ImGuiSliderFlags.WrapAround) == 0) + IM_ASSERT(bit32.band(flags, ImGuiSliderFlags.WrapAround) == 0) -- Not supported by SliderXXX(), only by DragXXX() if data_type == ImGuiDataType.S8 then local v32 = (ImS32)((ImS8)(v)); local r @@ -45127,6 +51314,8 @@ function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out return v, false end +-- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a slider, min and max are required. +-- Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @generic T : number --- @param label string --- @param data_type ImGuiDataType @@ -45162,6 +51351,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) return data, false end + -- Default format string when passing NULL if format == nil then format = ImGui.DataTypeGetInfo(data_type).PrintFmt end @@ -45169,6 +51359,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) local hovered = ImGui.ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags) local temp_input_is_active = temp_input_allowed and ImGui.TempInputIsActive(id) if not temp_input_is_active then + -- Tabbing or Ctrl+Click on Slider turns it into an input box local clicked = hovered and ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, id) local make_active = clicked or g.NavActivateId == id if make_active and clicked then @@ -45180,6 +51371,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) end end + -- Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert) if make_active then g.ActiveIdValueOnActivation = data end @@ -45193,10 +51385,12 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) end if temp_input_is_active then - local clamp_enabled = bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 + -- Only clamp Ctrl+Click input when ImGuiSliderFlags.ClampOnInput is set (generally via ImGuiSliderFlags.AlwaysClamp) + local clamp_enabled = bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 -- Don't use TempInputIsClampEnabled() return ImGui.TempInputScalar(frame_bb, id, label, data_type, data, format, clamp_enabled and min or nil, clamp_enabled and max or nil) end + -- Draw frame local frame_col = ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.FrameBgActive or (hovered and ImGuiCol.FrameBgHovered or ImGuiCol.FrameBg)) ImGui.RenderNavCursor(frame_bb, id) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding) @@ -45205,6 +51399,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) end ImGui.RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding) + -- Slider behavior local grab_bb = ImRect() local value_changed data, value_changed = ImGui.SliderBehavior(frame_bb, id, data_type, data, min, max, format, flags, grab_bb) @@ -45212,12 +51407,14 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) ImGui.MarkItemEdited(id) end + -- Render grab if grab_bb.Max.x > grab_bb.Min.x then window.DrawList:AddRectFilled(grab_bb.Min, grab_bb.Max, ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.SliderGrabActive or ImGuiCol.SliderGrab), style.GrabRounding) end -- TODO: ImGui.DataTypeFormatString() should be used here instead of ImFormatString() + -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value. -- if g.LogEnabled then -- ImGui.LogSetNextTextDecoration("{", "}") -- end @@ -45231,6 +51428,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) return data, value_changed end +-- Add multiple sliders on 1 line for compact edition of multiple components --- @param label string --- @param data_type ImGuiDataType --- @param v table @@ -45399,6 +51597,7 @@ function ImGui.VSliderScalar(label, size, data_type, data, min, max, format, fla return data, false end + -- Default format string when passing NULL if format == nil then format = ImGui.DataTypeGetInfo(data_type).PrintFmt end @@ -45415,10 +51614,12 @@ function ImGui.VSliderScalar(label, size, data_type, data, min, max, format, fla g.ActiveIdUsingNavDirMask = bit32.bor(g.ActiveIdUsingNavDirMask, bit32.lshift(1, ImGuiDir.Up), bit32.lshift(1, ImGuiDir.Down)) end + -- Draw frame local frame_col = ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.FrameBgActive or (hovered and ImGuiCol.FrameBgHovered or ImGuiCol.FrameBg)) ImGui.RenderNavCursor(frame_bb, id) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding) + -- Slider behavior local grab_bb = ImRect() local value_changed data, value_changed = ImGui.SliderBehavior(frame_bb, id, data_type, data, min, max, format, bit32.bor(flags or 0, ImGuiSliderFlags.Vertical), grab_bb) @@ -45426,10 +51627,13 @@ function ImGui.VSliderScalar(label, size, data_type, data, min, max, format, fla ImGui.MarkItemEdited(id) end + -- Render grab if grab_bb.Max.y > grab_bb.Min.y then window.DrawList:AddRectFilled(grab_bb.Min, grab_bb.Max, ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.SliderGrabActive or ImGuiCol.SliderGrab), style.GrabRounding) end + -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + -- For the vertical slider we allow centered text to overlap the frame padding -- local value_buf, value_buf_size = {}, 64 -- TODO: ImGui.DataTypeFormatString() ImGui.RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, ImFormatString(format, data), nil, nil, ImVec2(0.5, 0.0)) @@ -45467,9 +51671,16 @@ function ImGui.VSliderInt(label, size, v, v_min, v_max, format, flags) return ImGui.VSliderScalar(label, size, ImGuiDataType.S32, v, v_min, v_max, format, flags) end ----------------------------------------------------------------- --- [SECTION] INPUT TEXT ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint +------------------------------------------------------------------------------- +-- - imstb_textedit.h include +-- - InputText() +-- - InputTextWithHint() +-- - InputTextMultiline() +-- - InputTextEx() [Internal] +-- - DebugNodeInputTextState() [Internal] +------------------------------------------------------------------------------- --- @param label string --- @param buf char[] @@ -45480,7 +51691,7 @@ end function ImGui.InputText(label, buf, buf_size, flags, callback, user_data) if flags == nil then flags = 0 end - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) -- call InputTextMultiline() return ImGui.InputTextEx(label, nil, buf, buf_size, ImVec2(0, 0), flags, callback, user_data) end @@ -45528,6 +51739,11 @@ local function InputTextCalcTextSize(ctx, text, text_begin, text_end_display, te return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, obj.WrapWidth, text, text_begin, text_end_display, text_end, out_offset, flags) end +-- 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) +-- With our UTF-8 use of stb_textedit: +-- - STB_TEXTEDIT_GETCHAR is nothing more than a a "GETBYTE". It's only used to compare to ascii or to copy blocks of text so we are fine. +-- - One exception is the STB_TEXTEDIT_IS_SPACE feature which would expect a full char in order to handle full-width space such as 0x3000 (see ImCharIsBlankW). +-- - ...but we don't use that feature. --- @param obj ImGuiInputTextState --- @return int function ImStb.TEXTEDIT_STRINGLEN(obj) return obj.TextLen end @@ -45598,7 +51814,7 @@ end --- @param obj ImGuiInputTextState --- @param idx int function ImStb.is_word_boundary_from_right(obj, idx) - -- When ImGuiInputTextFlags.Password is set, we don't want actions such as Ctrl+Arrow to leak the fact that underlying data are blanks or separators + -- When ImGuiInputTextFlags.Password is set, we don't want actions such as Ctrl+Arrow to leak the fact that underlying data are blanks or separators. if bit32.band(obj.Flags, ImGuiInputTextFlags.Password) ~= 0 or idx <= 1 then return false end @@ -45675,7 +51891,7 @@ function ImStb.TEXTEDIT_MOVEWORDRIGHT(obj, idx) end end --- Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping +-- Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping. --- @param obj ImGuiInputTextState --- @param state STB_TexteditState --- @param cursor int @@ -45752,6 +51968,7 @@ end --- @param pos int --- @param n int function ImStb.TEXTEDIT_DELETECHARS(obj, pos, n) + -- Offset remaining text (+ copy zero terminator) IM_ASSERT(obj.TextSrc == obj.TextA.Data) ImStd.memmove(obj.TextA.Data, pos, obj.TextA.Data, pos + n, obj.TextLen - n - pos + 2) obj.EditedBefore = true @@ -45769,10 +51986,10 @@ function ImStb.TEXTEDIT_INSERTCHARS(obj, pos, new_text, new_text_pos, new_text_l local text_len = obj.TextLen IM_ASSERT(pos <= text_len + 1) - -- We support partial insertion (with a mod in stb_textedit) + -- We support partial insertion (with a mod in stb_textedit.h) local avail = obj.BufCapacity - 1 - obj.TextLen if not is_resizable and new_text_len > avail then - new_text_len = math.floor(ImStd.ImTextFindValidUtf8CodepointEnd(new_text, new_text_pos, new_text_len + 1, avail) - new_text_pos) -- Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion + new_text_len = math.floor(ImStd.ImTextFindValidUtf8CodepointEnd(new_text, new_text_pos, new_text_len + 1, avail) - new_text_pos) -- Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion. end if new_text_len == 0 then return 0 @@ -45801,6 +52018,8 @@ end stbte = IM_INCLUDE"imstb_textedit.lua" +-- stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling +-- the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?) --- @param str ImGuiInputTextState --- @param state STB_TexteditState --- @param text IMSTB_TEXTEDIT_CHARTYPE[] @@ -45859,8 +52078,8 @@ function MT.ImGuiInputTextState:OnCharPressed(c) self:CursorAnimReset() end --- After a user-input the cursor stays on for a while without blinking -function MT.ImGuiInputTextState:CursorAnimReset() self.CursorAnim = -0.30 end +-- Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header. +function MT.ImGuiInputTextState:CursorAnimReset() self.CursorAnim = -0.30 end -- After a user-input the cursor stays on for a while without blinking function MT.ImGuiInputTextState:CursorClamp() self.Stb.cursor = ImMin(self.Stb.cursor, self.TextLen + 1) @@ -45905,6 +52124,7 @@ function ImGui.PopPasswordFont() IM_ASSERT(backup.IndexAdvanceX.Size == 0 and backup.IndexLookup.Size == 0) end +-- Return false to discard a character. Returns (char, ok). --- @param ctx ImGuiContext --- @param state ImGuiInputTextState --- @param char unsigned_int @@ -46045,7 +52265,7 @@ 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 +-- 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. --- @param state ImGuiInputTextState --- @param old_buf ImStringBuffer --- @param old_length int @@ -46088,6 +52308,10 @@ local function InputTextReconcileUndoState(state, old_buf, old_length, new_buf, end end +-- As InputText() retain textual data and we currently provide a path for user to not retain it (via local variables) +-- we need some form of hook to reapply data back to user buffer on deactivation frame. (#4714) +-- It would be more desirable that we discourage users from taking advantage of the "user not retaining data" trick, +-- but that more likely be attractive when we do have _NoLiveEdit flag available. --- @param id ImGuiID function ImGui.InputTextDeactivateHook(id) local g = GImGui @@ -46103,7 +52327,7 @@ function ImGui.InputTextDeactivateHook(id) g.InputTextDeactivatedState.ID = state.ID g.InputTextDeactivatedState.ElapseFrame = g.FrameCount + 1 if bit32.band(state.Flags, ImGuiInputTextFlags.ReadOnly) ~= 0 then - g.InputTextDeactivatedState.TextA:resize(0) -- In theory this data won't be used, but clear to be neat + g.InputTextDeactivatedState.TextA:resize(0) -- In theory this data won't be used, but clear to be neat. else IM_ASSERT(state.TextA.Data ~= nil) -- IM_ASSERT(state.TextA[state.TextLen + 1] == 0) @@ -46112,6 +52336,8 @@ function ImGui.InputTextDeactivateHook(id) end end +-- 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) --- @param flags ImGuiInputTextFlags --- @param line_index ImGuiTextIndex --- @param buf char[] @@ -46240,6 +52466,8 @@ local function InputTextLineIndexGetPosOffset(g, state, line_index, buf, buf_end end -- Edit a string of text +-- - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!". +-- - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect. --- @param label string --- @param hint? char[] --- @param buf char[] @@ -46270,9 +52498,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback IM_ASSERT(buf ~= nil and buf_size >= 0) IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.CallbackHistory) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Can't use both together (they both use up/down keys) IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.CallbackCompletion) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0)) -- Can't use both together (they both use tab key) - IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Multiline does not not work with left-trimming - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Password) == 0) -- WordWrap does not work with Password mode - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0) -- WordWrap does not work in single-line mode + IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Multiline does not work with left-trimming + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Password) == 0) -- WordWrap does not work with Password mode. + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0) -- WordWrap does not work in single-line mode. local g = GImGui --[[@as ImGuiContext]] local io = g.IO @@ -46309,18 +52537,18 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback ImGuiLastItemData_Copy(item_data_backup, g.LastItemData) ImVec2_Copy(window.DC.CursorPos, backup_pos) - -- Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping + -- Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping. if g.NavActivateId == id and (bit32.band(g.NavActivateFlags, ImGuiActivateFlags.FromTabbing) ~= 0) and (bit32.band(g.NavActivateFlags, ImGuiActivateFlags.FromFocusApi) == 0) and (bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0) then g.NavActivateId = 0 end - -- Prevent NavActivate reactivating in BeginChild() when we are already active + -- Prevent NavActivate reactivating in BeginChild() when we are already active. local backup_activate_id = g.NavActivateId if g.ActiveId == id then -- Prevent reactivation g.NavActivateId = 0 end - -- We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug + -- We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug. ImGui.PushStyleColor(ImGuiCol.ChildBg, style.Colors[ImGuiCol.FrameBg]) ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.FrameRounding) ImGui.PushStyleVar(ImGuiStyleVar.ChildBorderSize, style.FrameBorderSize) @@ -46335,7 +52563,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback return false end draw_window = g.CurrentWindow -- Child window - draw_window.DC.NavLayersActiveMaskNext = bit32.bor(draw_window.DC.NavLayersActiveMaskNext, bit32.lshift(1, draw_window.DC.NavLayerCurrent)) -- This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it + draw_window.DC.NavLayersActiveMaskNext = bit32.bor(draw_window.DC.NavLayersActiveMaskNext, bit32.lshift(1, draw_window.DC.NavLayerCurrent)) -- This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it. ImVec2_Copy(draw_window.DC.CursorPos, draw_window.DC.CursorPos + style.FramePadding) inner_size.x = inner_size.x - draw_window.ScrollbarSizes.x @@ -46344,6 +52572,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback g.LastItemData.ItemFlags = item_data_backup.ItemFlags g.LastItemData.StatusFlags = item_data_backup.StatusFlags else + -- Support for internal ImGuiInputTextFlags.MergedItem flag, which could be redesigned as an ItemFlags if needed (with test performed in ItemAdd) ImGui.ItemSize(total_bb, style.FramePadding.y) if bit32.band(flags, ImGuiInputTextFlags.TempInput) == 0 then @@ -46362,7 +52591,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback hovered = false end - -- We are only allowed to access the state if we are already the active widget + -- We are only allowed to access the state if we are already the active widget. local state = ImGui.GetInputTextState(id) if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.ReadOnly) ~= 0 then @@ -46397,8 +52626,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local scroll_y = is_multiline and draw_window.Scroll.y or FLT_MAX local init_reload_from_user_buf = (state ~= nil and state.WantReloadUserBuf) - local init_changed_specs_multiline = (state ~= nil and (state.Stb.single_line ~= (not is_multiline))) - local init_changed_specs_readonly = (state ~= nil and (bit32.band(bit32.bxor(state.Flags, flags), ImGuiInputTextFlags.ReadOnly) ~= 0)) -- state ~= nil means it's our state + local init_changed_specs_multiline = (state ~= nil and (state.Stb.single_line ~= (not is_multiline))) -- state ~= nil means its our state. + local init_changed_specs_readonly = (state ~= nil and (bit32.band(bit32.bxor(state.Flags, flags), ImGuiInputTextFlags.ReadOnly) ~= 0)) -- state ~= nil means its our state. local init_make_active = (input_requested_by_user or input_requested_by_nav or input_requested_by_reactivate or user_scroll_finish) if init_reload_from_user_buf then local new_len = ImStd.ImStrlen(buf) @@ -46406,14 +52635,14 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.WantReloadUserBuf = false --- @cast state ImGuiInputTextState InputTextReconcileUndoState(state, state.TextA.Data, state.TextLen, buf, new_len) - state.TextA:resize(buf_size + 1) + 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 ImStd.memmove(state.TextA.Data, 1, buf, 1, state.TextLen + 1) state.Stb.select_start = state.ReloadSelectionStart state.Stb.cursor = state.ReloadSelectionEnd state.Stb.select_end = state.ReloadSelectionEnd -- will be clamped to bounds below elseif (init_make_active and g.ActiveId ~= id) or init_changed_specs_multiline or init_changed_specs_readonly then - -- Access state even if we don't own it yet + -- Access state even if we don't own it yet. state = g.InputTextState state:CursorAnimReset() @@ -46427,7 +52656,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local buf_len = ImStd.ImStrlen(buf) IM_ASSERT(((buf_len + 1 <= buf_size) or (buf_len == 0 and buf_size == 0)), "Is your input buffer properly zero-terminated?") if not user_scroll_finish then - state.TextToRevertTo:resize(buf_len + 1) + 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. ImStd.memmove(state.TextToRevertTo.Data, 1, buf, 1, buf_len + 1) end @@ -46443,7 +52672,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.TextLen = buf_len state.EditedBefore = false if not is_readonly then - state.TextA:resize(buf_size + 1) + state.TextA:resize(buf_size + 1) -- we use +1 to make sure that .Data is always pointing to at least an empty string. ImStd.memmove(state.TextA.Data, 1, buf, 1, state.TextLen + 1) end @@ -46454,7 +52683,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end -- 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 + -- Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. if not recycle_state then stbte.initialize_state(state.Stb, not is_multiline) end @@ -46488,8 +52717,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end if g.ActiveId == id then - -- 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 combination into individual shortcuts + -- 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 combination into individual shortcuts. local always_owned_keys = { ImGuiKey.LeftArrow, ImGuiKey.RightArrow, ImGuiKey.Delete, ImGuiKey.Backspace, ImGuiKey.Home, ImGuiKey.End } for _, key in ipairs(always_owned_keys) do ImGui.SetKeyOwner(key, id) @@ -46548,7 +52777,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local value_changed = false local validated = false - -- Select the buffer to render + -- Select the buffer to render. local buf_display_from_state = (render_cursor or render_selection or g.ActiveId == id) and not is_readonly and state ~= nil local is_displaying_hint = (hint ~= nil and (buf_display_from_state and state.TextA.Data or buf)[1] == 0) @@ -46577,7 +52806,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback 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 + -- Down the line we should have a cleaner library-wide concept of Selected vs Active. g.ActiveIdAllowOverlap = not io.MouseDown[0] -- Edit in progress @@ -46608,7 +52837,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback else -- Triple-click: Select line local is_eol = ImStb.TEXTEDIT_GETCHAR(state, state.Stb.cursor) == 10 - state.WrapWidth = 0.0 -- Temporarily disable wrapping so we use real line start + state.WrapWidth = 0.0 -- Temporarily disable wrapping so we use real line start. state:OnKeyPressed(STB_TEXTEDIT_K_LINESTART) state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_LINEEND, STB_TEXTEDIT_K_SHIFT)) state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_RIGHT, STB_TEXTEDIT_K_SHIFT)) @@ -46638,6 +52867,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.SelectedAllMouseLock = false end + -- We expect backends to emit a Tab key but some also emit a Tab character which we ignore (#2467, #1336) + -- (For Tab and Enter: Win32/SFML/Allegro are sending both keys and chars, GLFW and SDL are only sending keys. For Space they all send all threes) if bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0 and not is_readonly then if ImGui.Shortcut(ImGuiKey.Tab, ImGuiInputFlags.Repeat, id) then local c = 9 -- Insert TAB @@ -46649,9 +52880,12 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end -- FIXME: Implement Shift+Tab + -- if ImGui.Shortcut(bit32.bor(ImGuiKey.Tab, ImGuiMod_Shift), ImGuiInputFlags.Repeat, id) then + -- end end - -- Process regular text input + -- Process regular text input (before we check for Return because using some IME will effectively send a Return?) + -- We ignore Ctrl inputs, but need to allow Alt+Ctrl as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. local ignore_char_inputs = io.KeyCtrl and not io.KeyAlt if io.InputQueueCharacters.Size > 0 then if not ignore_char_inputs and not is_readonly and not input_requested_by_nav then @@ -46659,7 +52893,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback repeat -- Insert character if they pass filtering local c = io.InputQueueCharacters[n] - if c == 9 then -- Skip Tab, see above + if c == 9 then -- Skip Tab, see above. break end @@ -46688,9 +52922,11 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.Stb.row_count_per_page = row_count_per_page local k_mask = (io.KeyShift and STB_TEXTEDIT_K_SHIFT or 0) - local is_wordmove_key_down = is_osx and io.KeyAlt or io.KeyCtrl - local is_startend_key_down = is_osx and io.KeyCtrl and not io.KeySuper and not io.KeyAlt + local is_wordmove_key_down = is_osx and io.KeyAlt or io.KeyCtrl -- OS X style: Text editing cursor movement using Alt instead of Ctrl + local is_startend_key_down = is_osx and io.KeyCtrl and not io.KeySuper and not 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: former would be handled by InputText) + -- Otherwise we could simply assume that we own the keys as we are active. local f_repeat = ImGuiInputFlags.Repeat local is_cut = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.X), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Shift, ImGuiKey.Delete), f_repeat, id)) and not is_readonly and not is_password and (not is_multiline or state:HasSelection()) local is_copy = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.C), 0, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Insert), 0, id)) and not is_password and (not is_multiline or state:HasSelection()) @@ -46699,6 +52935,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local is_redo = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Y), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Z), f_repeat, id)) and not is_readonly and is_undoable local is_select_all = ImGui.Shortcut(bit32.bor(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. local nav_gamepad_active = (bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0) and (bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0) local is_enter = ImGui.Shortcut(ImGuiKey.Enter, f_repeat, id) or ImGui.Shortcut(ImGuiKey.KeypadEnter, f_repeat, id) local is_ctrl_enter = ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Enter), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.KeypadEnter), f_repeat, id) @@ -46706,6 +52943,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local is_gamepad_validate = nav_gamepad_active and ImGui.IsKeyPressed(ImGuiKey.NavGamepadActivate, false) local is_cancel = ImGui.Shortcut(ImGuiKey.Escape, f_repeat, id) or (nav_gamepad_active and ImGui.Shortcut(ImGuiKey.NavGamepadCancel, f_repeat, id)) + -- FIXME: Should use more Shortcut() and reduce IsKeyPressed()+SetKeyOwner(), but requires modifiers combination to be taken account of. + -- FIXME-OSX: Missing support for Alt(option)+Right/Left = go to end of line, or next line if already in end of line. if ImGui.IsKeyPressed(ImGuiKey.LeftArrow) then state:OnKeyPressed(bit32.bor(is_startend_key_down and STB_TEXTEDIT_K_LINESTART or (is_wordmove_key_down and STB_TEXTEDIT_K_WORDLEFT or STB_TEXTEDIT_K_LEFT), k_mask)) elseif ImGui.IsKeyPressed(ImGuiKey.RightArrow) then @@ -46734,6 +52973,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state:OnKeyPressed(io.KeyCtrl and bit32.bor(STB_TEXTEDIT_K_TEXTEND, k_mask) or bit32.bor(STB_TEXTEDIT_K_LINEEND, k_mask)) elseif ImGui.IsKeyPressed(ImGuiKey.Delete) and not is_readonly and not is_cut then if not state:HasSelection() then + -- OSX doesn't seem to have Super+Delete to delete until end-of-line, so we don't emulate that (as opposed to Super+Backspace) if is_wordmove_key_down then state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_WORDRIGHT, STB_TEXTEDIT_K_SHIFT)) end @@ -46749,17 +52989,20 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_BACKSPACE, k_mask)) elseif is_enter or is_ctrl_enter or is_shift_enter or is_gamepad_validate then + -- Determine if we turn Enter into a \n character local ctrl_enter_for_new_line = bit32.band(flags, ImGuiInputTextFlags.CtrlEnterForNewLine) ~= 0 local is_new_line = is_multiline and not is_gamepad_validate and (is_shift_enter or (is_enter and not ctrl_enter_for_new_line) or (is_ctrl_enter and ctrl_enter_for_new_line)) if not is_new_line then validated = true clear_active_id = true if io.ConfigInputTextEnterKeepActive and not is_multiline and not is_ctrl_enter and not is_shift_enter then - state:SelectAll() - g.InputTextReactivateId = id + -- Queue reactivation, so that e.g. IsItemDeactivatedAfterEdit() will work. (#9001) + state:SelectAll() -- No need to scroll + g.InputTextReactivateId = id -- Mark for reactivation on next frame end elseif not is_readonly then - local c = 10 -- Insert new line + -- Insert new line + local c = 10 local ret2 c, ret2 = InputTextFilterCharacter(g, state, c, callback, callback_user_data) if ret2 then @@ -46788,7 +53031,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state:SelectAll() state.CursorFollow = true elseif is_cut or is_copy then + -- Cut, Copy if g.PlatformIO.Platform_SetClipboardTextFn ~= nil then + -- SetClipboardText() only takes null terminated strings + state.TextSrc may point to read-only user buffer, so we need to make a copy. local ib = state:HasSelection() and ImMin(state.Stb.select_start, state.Stb.select_end) or 1 local ie = state:HasSelection() and ImMax(state.Stb.select_start, state.Stb.select_end) or state.TextLen + 1 g.TempBuffer:reserve(ie - ib + 1) @@ -46806,6 +53051,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback elseif is_paste then local clipboard = ImGui.GetClipboardText() if clipboard then + -- Filter pasted buffer local clipboard_len = #clipboard local clipboard_end = clipboard_len + 1 local clipboard_filtered = ImVector() @@ -46832,7 +53078,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback until true end - if clipboard_filtered.Size > 0 then + if clipboard_filtered.Size > 0 then -- If everything was filtered, ignore the pasting operation clipboard_filtered:push_back(0) stbte.paste(state, state.Stb, clipboard_filtered.Data, clipboard_filtered.Size - 1) state.CursorFollow = true @@ -46840,6 +53086,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end + -- Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame. render_selection = render_selection or (state:HasSelection() and (RENDER_SELECTION_WHEN_INACTIVE or render_cursor)) end @@ -46852,6 +53099,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback if revert_edit and not is_readonly then if bit32.band(flags, ImGuiInputTextFlags.EscapeClearsAll) ~= 0 then + -- Clear input IM_ASSERT(state.TextA.Data[1] ~= 0) apply_new_text = {0} apply_new_text_length = 0 @@ -46862,14 +53110,19 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback 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 ImStb.stb_textedit_replace(state, state.Stb, state.TextToRevertTo.Data, state.TextToRevertTo.Size - 1) end end + -- User callback if bit32.band(flags, bit32.bor(ImGuiInputTextFlags.CallbackCompletion, ImGuiInputTextFlags.CallbackHistory, ImGuiInputTextFlags.CallbackEdit, ImGuiInputTextFlags.CallbackAlways)) ~= 0 then IM_ASSERT(callback ~= nil) + -- The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. + local event_flag = 0 local event_key = ImGuiKey.None if bit32.band(flags, ImGuiInputTextFlags.CallbackCompletion) ~= 0 and ImGui.Shortcut(ImGuiKey.Tab, 0, id) then @@ -46896,6 +53149,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback callback_data.EventActivated = (g.ActiveId == state.ID and g.ActiveIdIsJustActivated) callback_data.UserData = callback_user_data + -- FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925 local callback_buf = is_readonly and buf or state.TextA.Data IM_ASSERT(callback_buf == state.TextSrc) state.CallbackTextBackup:resize(state.TextLen + 1) @@ -46910,10 +53164,12 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback callback_data.SelectionStart = state.Stb.select_start callback_data.SelectionEnd = state.Stb.select_end + -- Call user code callback(callback_data) - callback_buf = is_readonly and buf or state.TextA.Data - IM_ASSERT(callback_data.Buf == callback_buf) + -- Read back what user may have modified + callback_buf = is_readonly and buf or 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.BufCapacity) IM_ASSERT(callback_data.Flags == flags) if callback_data.BufDirty or callback_data.CursorPos ~= state.Stb.cursor then @@ -46923,15 +53179,18 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.Stb.select_start = ImClamp(callback_data.SelectionStart, 0, callback_data.BufTextLen) state.Stb.select_end = ImClamp(callback_data.SelectionEnd, 0, callback_data.BufTextLen) if callback_data.BufDirty then - IM_ASSERT(callback_data.BufTextLen == ImStd.ImStrlen(callback_data.Buf)) + -- Callback may update buffer and thus set buf_dirty even in read-only mode. + IM_ASSERT(callback_data.BufTextLen == ImStd.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 + state.TextLen = callback_data.BufTextLen -- Assume correct length and valid UTF-8 from user, saves us an extra strlen() state.EditedBefore = true; state.EditedThisFrame = true state:CursorAnimReset() end end end + -- Write back result string if modified. + -- FIXME-OPT: Could mark dirty state from the stb_textedit callbacks if not is_readonly then if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0 then -- Apply when modified @@ -46949,6 +53208,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end + -- Handle reapplying final data on deactivation (see InputTextDeactivateHook() for details) + -- This is used when e.g. losing focus or tabbing out into another InputText() which may already be using the temp buffer. if g.InputTextDeactivatedState.ID == id then -- The state only exists after an Edit. IsItemDeactivatedAfterEdit() is not valid in every code path (see "widgets_inputtext_status_noliveedit" test). if ((g.ActiveId ~= id and ImGui.IsItemDeactivated()) or (g.ActiveId == id and bit32.band(flags, ImGuiInputTextFlags.TempInput) ~= 0)) then @@ -46962,6 +53223,12 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback g.InputTextDeactivatedState.ID = 0 end + -- Write back result to user buffer. This can currently only happen when (g.ActiveId == id) or when just deactivated. + -- - As soon as the InputText() is active, our stored in-widget value gets priority over any underlying modification of the user buffer. + -- - Make sure we always reapply the live buffer back to the input/user buffer before clearing ActiveId, even thought strictly speaking + -- it was not modified on this frame. This allows the user to use InputText() without maintaining any user-side storage. + -- (PS: if you use this property together with ImGuiInputTextFlags.CallbackResize, you are at the risk of recreating a temporary + -- allocated/string object every frame. Which in the grand scheme of scheme is nothing, but isn't dear imgui vibe). if apply_new_text ~= nil then IM_ASSERT(apply_new_text_length >= 0) if is_resizable then @@ -46983,7 +53250,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1) IM_ASSERT(apply_new_text_length <= buf_size) end + -- IMGUI_DEBUG_PRINT("InputText(\"%s\"): apply_new_text length %d\n", label, apply_new_text_length); + -- If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size. ImStd.ImStrncpy(buf, 1, apply_new_text, 1, ImMin(apply_new_text_length + 1, buf_size)) end @@ -47035,7 +53304,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback if render_cursor or render_selection or g.ActiveId == id then buf_display_end = state.TextLen + 1 elseif is_multiline and not is_wordwrap then - buf_display_end = nil -- Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path + buf_display_end = nil -- Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path. else buf_display_end = ImStd.ImStrlen(buf_display) + 1 end @@ -47047,10 +53316,13 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize) end + -- Build line index for easy data access (makes code below simpler and faster) local line_index = g.InputTextLineIndex line_index.Offsets:resize(0) local line_count = 1 if is_multiline then + -- If scrolling is expected to change build full index. + -- FIXME-OPT: Could append to index when new value of line_visible_n1 becomes bigger, see second call to CalcClipRectVisibleItemsY() below. local will_scroll_y = state and ((state.CursorFollow and render_cursor) or (state.CursorCenterY and (render_cursor or render_selection))) --- @cast buf_display_end int local out_buf_end @@ -47062,19 +53334,32 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback line_index.EndOffset = buf_display_end - 1 line_visible_n1 = ImMin(line_visible_n1, line_count + 1) + -- Store text height (we don't need width) local text_size_y = line_count * g.FontSize + -- ImGui.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 --- @cast buf_display_end int local cursor_offset = (render_cursor and state) and InputTextLineIndexGetPosOffset(g, state, line_index, buf_display, buf_display_end, state.Stb.cursor) or ImVec2(0.0, 0.0) local draw_scroll = ImVec2() + -- Render text. We currently only render selection when the widget is active or while scrolling. local text_col = ImGui.GetColorU32(is_displaying_hint and ImGuiCol.TextDisabled or ImGuiCol.Text) if render_cursor or render_selection then + -- 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) + -- - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) + -- - 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. IM_ASSERT(state ~= nil) state.LineCount = line_count + -- Scroll local new_scroll_y = scroll_y if render_cursor and state.CursorFollow then + -- Horizontal scroll in chunks of quarter width if bit32.band(flags, ImGuiInputTextFlags.NoHorizontalScroll) == 0 then local scroll_increment_x = inner_size.x * 0.25 local visible_width = inner_size.x - style.FramePadding.x @@ -47087,7 +53372,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.Scroll.x = 0.0 end + -- Vertical scroll if is_multiline then + -- Test if cursor is vertically visible if cursor_offset.y - g.FontSize < scroll_y then new_scroll_y = ImMax(0.0, cursor_offset.y - g.FontSize) elseif cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0) >= scroll_y then @@ -47106,18 +53393,19 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback if new_scroll_y ~= scroll_y then local scroll_max_y = ImMax((text_size_y + style.FramePadding.y * 2.0) - inner_size.y, 0.0) scroll_y = ImClamp(new_scroll_y, 0.0, scroll_max_y) - draw_pos.y = draw_pos.y + (draw_window.Scroll.y - scroll_y) + draw_pos.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 line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize) line_visible_n1 = ImMin(line_visible_n1, line_count) end + -- Draw selection draw_scroll.x = state.Scroll.x if render_selection then - local bg_color = ImGui.GetColorU32(ImGuiCol.TextSelectedBg, render_cursor and 1.0 or 0.6) - local bg_offy_up = is_multiline and 0.0 or -1.0 + local bg_color = ImGui.GetColorU32(ImGuiCol.TextSelectedBg, render_cursor and 1.0 or 0.6) -- FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. + local bg_offy_up = is_multiline and 0.0 or -1.0 -- FIXME-DPI: those offsets should be part of the style? they don't play so well with multi-line selection. local bg_offy_dn = is_multiline and 0.0 or 2.0 - local bg_eol_width = IM_TRUNC(g.FontBaked:GetCharAdvance(32) * 0.50) + local bg_eol_width = IM_TRUNC(g.FontBaked:GetCharAdvance(32) * 0.50) -- So we can see selected empty lines local text_selected_begin = ImMin(state.Stb.select_start, state.Stb.select_end) local text_selected_end = ImMax(state.Stb.select_start, state.Stb.select_end) @@ -47137,7 +53425,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback rect_width = rect_width + ImGui.CalcTextSizeEx(buf_display, line_selected_begin, line_selected_end).x end if text_selected_begin <= p_eol and text_selected_end > p_eol and not p_eol_is_wrap then - rect_width = rect_width + bg_eol_width + rect_width = rect_width + bg_eol_width -- So we can see selected empty lines end if rect_width == 0.0 then break @@ -47157,10 +53445,13 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end + -- Find render position for right alignment (single-line only) if g.ActiveId ~= id and bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and not render_cursor and not render_selection then draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - ImGui.CalcTextSize(buf_display, nil).x - style.FramePadding.x) end + -- draw_scroll.x = state.Scroll.x -- Preserve scroll when inactive? + -- Render text if (is_multiline or (buf_display_end - 1) < buf_display_max_length) and bit32.band(text_col, IM_COL32_A_MASK) ~= 0 and line_visible_n0 < line_visible_n1 then g.Font:RenderText(draw_window.DrawList, g.FontSize, draw_pos - draw_scroll + ImVec2(0.0, (line_visible_n0 - 1) * g.FontSize), @@ -47171,6 +53462,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback wrap_width, bit32.bor(ImDrawTextFlags.WrapKeepBlanks, ImDrawTextFlags.CpuFineClip)) end + -- Render blinking cursor if render_cursor then state.CursorAnim = state.CursorAnim + io.DeltaTime local cursor_is_visible = (not g.IO.ConfigInputTextCursorBlink) or (state.CursorAnim <= 0.0) or (ImFmod(state.CursorAnim, 1.20) <= 0.80) @@ -47182,8 +53474,11 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback draw_window.DrawList:AddLineV(cursor_screen_rect.Min.x, cursor_screen_rect.Min.y, cursor_screen_rect.Max.y, ImGui.GetColorU32(ImGuiCol.InputTextCursor), style.InputTextCursorSize) end + -- 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 not is_readonly and g.ActiveId == id then - local ime_data = g.PlatformImeData + local ime_data = g.PlatformImeData -- (this is a public struct, passed to io.Platform_SetImeDataFn() handler) ime_data.WantVisible = true ime_data.WantTextInput = true ImVec2_Copy(ime_data.InputPos, ImVec2(cursor_screen_pos.x - 1.0, cursor_screen_pos.y - g.FontSize)) @@ -47242,13 +53537,23 @@ end function ImGui.InputTextWithHint(label, hint, buf, buf_size, flags, callback, user_data) if flags == nil then flags = 0 end - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) -- call InputTextMultiline() or InputTextEx() manually if you need multi-line + hint. return ImGui.InputTextEx(label, hint, buf, buf_size, ImVec2(0, 0), flags, callback, user_data) end ----------------------------------------------------------------- --- [SECTION] COLOR EDIT / PICKER ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +------------------------------------------------------------------------------- +-- - ColorEdit3() +-- - ColorEdit4() +-- - ColorPicker3() +-- - RenderColorRectWithAlphaCheckerboard() [Internal] +-- - ColorPicker4() +-- - ColorButton() +-- - ColorTooltip() [Internal] +-- - ColorEditOptionsPopup() [Internal] +-- - ColorPickerOptionsPopup() [Internal] +------------------------------------------------------------------------------- --- @param col float[] --- @param H float @@ -47263,6 +53568,8 @@ local function ColorEditRestoreH(col, H) return H end +-- ColorEdit supports RGB and HSV inputs. In case of RGB input resulting color may have undefined hue and/or saturation. +-- Since widget displays both RGB and HSV values we must preserve hue and saturation to prevent these values resetting. --- @param col float[] --- @param H float --- @param S float @@ -47304,6 +53611,9 @@ local fmt_table_float = { { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } -- Long display for HSVA } +-- 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. --- @param label string --- @param col float[] --- @param flags ImGuiColorEditFlags @@ -47405,6 +53715,7 @@ function ImGui.ColorEdit4(label, col, flags) window.DC.CursorPos.x = pos.x + inputs_offset_x if bit32.band(flags, bit32.bor(ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.DisplayHSV)) ~= 0 and bit32.band(flags, ImGuiColorEditFlags.NoInputs) == 0 then + -- RGB/HSV 0..255 Sliders local w_items = w_inputs - style.ItemInnerSpacing.x * (components - 1) local w_per_component = IM_TRUNC(w_items / components) local draw_color_marker = bit32.band(flags, bit32.bor(ImGuiColorEditFlags.DisplayHSV, ImGuiColorEditFlags.NoColorMarkers)) == 0 @@ -47432,7 +53743,7 @@ function ImGui.ColorEdit4(label, col, flags) ImGui.SetNextItemColorMarker(GDefaultRgbaColorMarkers[n]) end - -- FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0 + -- FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0. if bit32.band(flags, ImGuiColorEditFlags.Float) ~= 0 then local changed f[n], changed = ImGui.DragFloat(ids[n], f[n], 1.0 / 255.0, 0.0, hdr and 0.0 or 1.0, fmt_table_float[fmt_idx][n], drag_flags) @@ -47470,15 +53781,15 @@ function ImGui.ColorEdit4(label, col, flags) p = p + 1 end i[1], i[2], i[3] = 0, 0, 0 - i[4] = 0xFF + i[4] = 0xFF -- alpha default to 255 is not parsed by scanf (e.g. inputting #FFFFFF omitting alpha) local r if alpha then - r = ImStd.sscanf(buf, p, "%02X%02X%02X%02X", i) + r = ImStd.sscanf(buf, p, "%02X%02X%02X%02X", i) -- Treat at unsigned (%X is unsigned) else r = ImStd.sscanf(buf, p, "%02X%02X%02X", i) end - -- IM_UNUSED(r) + -- IM_UNUSED(r) -- Fixes C6031: Return value ignored: 'sscanf'. end if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then @@ -47522,7 +53833,7 @@ function ImGui.ColorEdit4(label, col, flags) if label ~= "" and label_display_end > 1 and bit32.band(flags, ImGuiColorEditFlags.NoLabel) == 0 then -- Position not necessarily next to last submitted button (e.g. if style.ColorButtonPosition == ImGuiDir_Left), - -- but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this + -- but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this. ImGui.SameLine(0.0, style.ItemInnerSpacing.x) window.DC.CursorPos.x = pos.x + ((bit32.band(flags, ImGuiColorEditFlags.NoInputs) ~= 0) and w_button or (w_full + style.ItemInnerSpacing.x)) ImGui.TextEx(label, label_display_end) @@ -47563,7 +53874,7 @@ function ImGui.ColorEdit4(label, col, flags) -- Drag and Drop Target -- TODO: - -- When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4() + -- When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4(). if picker_active_window and g.ActiveId ~= 0 and g.ActiveIdWindow == picker_active_window then g.LastItemData.ID = g.ActiveId end @@ -47598,6 +53909,7 @@ function ImGui.ColorPicker3(label, col, flags) return true end +-- This allowed passing 0 to set default, whereas NewFrame() will assert if one of missing. Abide to old logic. function ImGui.SetColorEditOptions(flags) local g = GImGui local def = ImGuiColorEditFlags.DefaultOptions_ @@ -47627,6 +53939,9 @@ do --[[ColorPicker4]] local backup_initial_col = {0, 0, 0, 0} +-- Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags.NoAlpha flag is set. +-- FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) +-- FIXME: this is trying to be aware of style.Alpha but not fully correct. Also, the color wheel will have overlapping glitches with (style.Alpha < 1.0) --- @param label string --- @param col float[] --- @param flags ImGuiColorEditFlags @@ -47692,8 +54007,8 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) local picker_pos = ImVec2() ImVec2_Copy(picker_pos, window.DC.CursorPos) local square_sz = ImGui.GetFrameHeight() - local bars_width = square_sz -- Arbitrary smallish width of Hue/Alpha picking bars - local sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar and 2 or 1) * (bars_width + style.ItemInnerSpacing.x)) -- Saturation/Value picking box + local bars_width = square_sz -- Arbitrary smallish width of Hue/Alpha picking bars + local sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar and 2 or 1) * (bars_width + style.ItemInnerSpacing.x)) -- Saturation/Value picking box local bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x local bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x local bars_triangles_half_sz = IM_TRUNC(bars_width * 0.20) @@ -47709,9 +54024,9 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) local triangle_rotate = bit32.band(flags, ImGuiColorEditFlags.PickerNoRotate) == 0 local triangle_r = wheel_r_inner - math.floor(sv_picker_size * 0.027) local triangle_pa, triangle_pb, triangle_pc - if triangle_rotate then triangle_pa = ImVec2( triangle_r, 0.0) else triangle_pa = ImVec2( triangle_r * 0.866, triangle_r * 0.5) end -- Hue point - if triangle_rotate then triangle_pb = ImVec2(triangle_r * -0.5, triangle_r * -0.866) else triangle_pb = ImVec2( 0.0, -triangle_r) end -- Black point - if triangle_rotate then triangle_pc = ImVec2(triangle_r * -0.5, triangle_r * 0.866) else triangle_pc = ImVec2(triangle_r * -0.866, triangle_r * 0.5) end -- White point + if triangle_rotate then triangle_pa = ImVec2( triangle_r, 0.0) else triangle_pa = ImVec2( triangle_r * 0.866, triangle_r * 0.5) end -- Hue point. + if triangle_rotate then triangle_pb = ImVec2(triangle_r * -0.5, triangle_r * -0.866) else triangle_pb = ImVec2( 0.0, -triangle_r) end -- Black point. + if triangle_rotate then triangle_pc = ImVec2(triangle_r * -0.5, triangle_r * 0.866) else triangle_pc = ImVec2(triangle_r * -0.866, triangle_r * 0.5) end -- White point. local H = col[1]; local S = col[2]; local V = col[3] local R = col[1]; local G = col[2]; local B = col[3] @@ -47771,7 +54086,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) if ImGui.IsItemActive() and not is_readonly then S = ImSaturate((io.MousePos.x - picker_pos.x) / ImMax(sv_picker_size - 1, 0.0001)) V = 1.0 - ImSaturate((io.MousePos.y - picker_pos.y) / ImMax(sv_picker_size - 1, 0.0001)) - H = ColorEditRestoreH(col, H) -- Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square. + H = ColorEditRestoreH(col, H) -- Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square. value_changed = true value_changed_sv = true end @@ -47799,7 +54114,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) value_changed = true end end - ImGui.PopItemFlag() + ImGui.PopItemFlag() -- ImGuiItemFlags.NoNav if bit32.band(flags, ImGuiColorEditFlags.NoSidePreview) == 0 then ImGui.SameLine(0, style.ItemInnerSpacing.x) @@ -47989,8 +54304,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) draw_list:AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black) ImGui.RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0) - -- Sneakily prevent the circle to stick out too much - sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2) + sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2) -- Sneakily prevent the circle to stick out too much sv_cursor_pos.y = ImClamp(IM_ROUND(picker_pos.y + ImSaturate(1 - V) * sv_picker_size), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2) -- Render Hue Bar @@ -48005,7 +54319,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) -- Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range) local sv_cursor_rad = value_changed_sv and (wheel_thickness * 0.55) or (wheel_thickness * 0.40) - local sv_cursor_segments = draw_list:_CalcCircleAutoSegmentCount(sv_cursor_rad) -- Lock segment count so the +1 one matches others. + local sv_cursor_segments = draw_list:_CalcCircleAutoSegmentCount(sv_cursor_rad) -- Lock segment count so the +1 one matches others. draw_list:AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, sv_cursor_segments) draw_list:AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, sv_cursor_segments) draw_list:AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, sv_cursor_segments) @@ -48050,6 +54364,10 @@ end end +-- A little color square. Return true when clicked. +-- FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. +-- 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. +-- Note that 'col' may be encoded in HSV if ImGuiColorEditFlags.InputHSV is set. --- @param desc_id string --- @param col ImVec4 --- @param flags? ImGuiColorEditFlags @@ -48104,6 +54422,7 @@ function ImGui.ColorButton(desc_id, col, flags, size_arg) end window.DrawList:AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), ImGui.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 local col_source = (bit32.band(flags, ImGuiColorEditFlags.AlphaOpaque) ~= 0) and col_rgb_without_alpha or col_rgb if col_source.w < 1.0 and bit32.band(flags, ImGuiColorEditFlags.AlphaNoBg) == 0 then ImGui.RenderColorRectWithAlphaCheckerboard(window.DrawList, bb_inner.Min, bb_inner.Max, ImGui.GetColorU32(col_source), grid_step, ImVec2(off, off), rounding) @@ -48116,7 +54435,7 @@ function ImGui.ColorButton(desc_id, col, flags, size_arg) if g.Style.FrameBorderSize > 0.0 then ImGui.RenderFrameBorder(bb.Min, bb.Max, rounding) else - window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), rounding) + window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), rounding) -- Color buttons are often in need of some sort of border end end @@ -48142,6 +54461,7 @@ function ImGui.ColorButton(desc_id, col, flags, size_arg) return pressed end +-- Note: only access 3 floats if ImGuiColorEditFlags.NoAlpha flag is set. --- @param text? string --- @param col ImVec4 --- @param flags ImGuiColorEditFlags @@ -48279,6 +54599,7 @@ function ImGui.ColorPickerOptionsPopup(ref_col, flags) local picker_size = ImVec2(g.FontSize * 8, ImMax(g.FontSize * 8 - (ImGui.GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0)) -- FIXME: Picker size copied from main picker function ImGui.PushItemWidth(picker_size.x) for picker_type = 0, 1 do + -- Draw small/thumbnail version of each picker type (over an invisible button for selection) if picker_type > 0 then ImGui.Separator() end @@ -48291,8 +54612,7 @@ function ImGui.ColorPickerOptionsPopup(ref_col, flags) picker_flags = bit32.bor(picker_flags, ImGuiColorEditFlags.PickerHueWheel) end local backup_pos = ImGui.GetCursorScreenPos() - -- By default, Selectable() is closing popup - if ImGui.Selectable("##selectable", false, 0, picker_size) then + if ImGui.Selectable("##selectable", false, 0, picker_size) then -- By default, Selectable() is closing popup g.IO.ConfigColorEditFlags = bit32.bor(bit32.band(g.IO.ConfigColorEditFlags, bit32.bnot(ImGuiColorEditFlags.PickerMask_)), bit32.band(picker_flags, ImGuiColorEditFlags.PickerMask_)) end ImGui.SetCursorScreenPos(backup_pos) @@ -48315,9 +54635,21 @@ function ImGui.ColorPickerOptionsPopup(ref_col, flags) ImGui.EndPopup() end ----------------------------------------------------------------- --- [SECTION] TREES ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +------------------------------------------------------------------------------- +-- - TreeNode() +-- - TreeNodeV() +-- - TreeNodeEx() +-- - TreeNodeExV() +-- - TreeNodeStoreStackData() [Internal] +-- - TreeNodeBehavior() [Internal] +-- - TreePush() +-- - TreePop() +-- - GetTreeNodeToLabelSpacing() +-- - SetNextItemOpen() +-- - CollapsingHeader() +------------------------------------------------------------------------------- -- va_list variants: identical in Lua (varargs) ImGui.TextColoredV = function(...) return ImGui.TextColored(...) end @@ -48381,6 +54713,8 @@ function ImGui.TreeNodeExV(str_id, flags, fmt, ...) return ImGui.TreeNodeBehavior(id, flags, label, #label + 1) end +-- The reason those two functions are not yet in public API is because I would like to design a more feature-full and generic API for this. +-- They are otherwise function (cc: #3823, #9251, #7553, #6754, #5423, #2958, #2079, #1947, #1131, #722) --- @param storage_id ImGuiID function ImGui.TreeNodeGetOpen(storage_id) local g = GImGui @@ -48399,10 +54733,12 @@ end --- @param storage_id ImGuiID --- @param flags ImGuiTreeNodeFlags function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) + -- Leaf node always open a new tree/id scope. If you never use it, add ImGuiTreeNodeFlags.NoTreePushOnOpen. if bit32.band(flags, ImGuiTreeNodeFlags.Leaf) ~= 0 then return true end + -- We only write to the tree storage if the user clicks, or explicitly use the SetNextItemOpen function local g = GImGui local window = g.CurrentWindow local storage = window.DC.StateStorage @@ -48413,6 +54749,7 @@ function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) is_open = g.NextItemData.OpenVal ImGui.TreeNodeSetOpen(storage_id, is_open) else + -- We treat ImGuiCond.Once and ImGuiCond.FirstUseEver the same because tree node state are not saved persistently. local stored_value = storage[storage_id] if stored_value == nil then is_open = g.NextItemData.OpenVal @@ -48425,6 +54762,8 @@ function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) is_open = (storage[storage_id] == nil) and (bit32.band(flags, ImGuiTreeNodeFlags.DefaultOpen) ~= 0) or storage[storage_id] end + -- When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). + -- NB- If we are above max depth we still allow manually opened nodes to be logged. if g.LogEnabled and bit32.band(flags, ImGuiTreeNodeFlags.NoAutoOpenOnLog) == 0 and (window.DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand then is_open = true end @@ -48432,6 +54771,8 @@ function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) return is_open end +-- Store ImGuiTreeNodeStackData for just submitted node. +-- Currently only supports 32 level deep. Easy to increase to e.g. 64. --- @param flags ImGuiTreeNodeFlags --- @param x1 float local function TreeNodeStoreStackData(flags, x1) @@ -48445,6 +54786,7 @@ local function TreeNodeStoreStackData(flags, x1) tree_node_data.ItemFlags = g.LastItemData.ItemFlags ImRect_Copy(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. local draw_lines = bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DrawLinesToNodes)) ~= 0 tree_node_data.DrawLinesX1 = draw_lines and (x1 + g.FontSize * 0.5 + g.Style.FramePadding.x) or FLT_MAX tree_node_data.DrawLinesTableColumn = (draw_lines and g.CurrentTable) and g.CurrentTable.CurrentColumn or -1 @@ -48469,6 +54811,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local g = GImGui local style = g.Style + -- When not framed, we vertically increase height up to typical framed widget height local display_frame = bit32.band(flags, ImGuiTreeNodeFlags.Framed) ~= 0 local use_frame_padding = display_frame or (bit32.band(flags, ImGuiTreeNodeFlags.FramePadding) ~= 0) local padding @@ -48483,9 +54826,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end local label_size = ImGui.CalcTextSize(label, label_end, false) - local text_offset_x = g.FontSize + (display_frame and (padding.x * 3) or (padding.x * 2)) - local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset - local text_width = g.FontSize + label_size.x + padding.x * 2 + local text_offset_x = g.FontSize + (display_frame and (padding.x * 3) or (padding.x * 2)) -- Collapsing arrow width + Spacing + local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset -- Latch before ItemSize changes it + local text_width = g.FontSize + label_size.x + padding.x * 2 -- Include collapsing arrow local frame_height = label_size.y + padding.y * 2 local span_all_columns = bit32.band(flags, ImGuiTreeNodeFlags.SpanAllColumns) ~= 0 and (g.CurrentTable ~= nil) @@ -48496,7 +54839,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) frame_bb.Max.x = span_all_columns and window.ParentWorkRect.Max.x or (bit32.band(flags, ImGuiTreeNodeFlags.SpanLabelWidth) ~= 0 and window.DC.CursorPos.x + text_width + padding.x or window.WorkRect.Max.x) frame_bb.Max.y = window.DC.CursorPos.y + (text_offset_y - padding.y) + frame_height if display_frame then - local outer_extend = IM_TRUNC(window.WindowPadding.x * 0.5) + local outer_extend = IM_TRUNC(window.WindowPadding.x * 0.5) -- Framed header expand a little outside of current limits frame_bb.Min.x = frame_bb.Min.x - outer_extend frame_bb.Max.x = frame_bb.Max.x + outer_extend end @@ -48504,17 +54847,20 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local text_pos = ImVec2(window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y) ImGui.ItemSize(ImVec2(text_width, frame_height), padding.y) + -- For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing local interact_bb = ImRect() ImRect_Copy(interact_bb, frame_bb) if bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.Framed, ImGuiTreeNodeFlags.SpanAvailWidth, ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.SpanLabelWidth, ImGuiTreeNodeFlags.SpanAllColumns)) == 0 then interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0 and (style.ItemSpacing.x * 2.0) or 0.0) end + -- Compute open and multi-select states before ItemAdd() as it clear NextItem data. local storage_id = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasStorageID) ~= 0) and g.NextItemData.StorageId or id local is_open = ImGui.TreeNodeUpdateNextOpen(storage_id, flags) local is_visible if span_all_columns or span_all_columns_label then + -- Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. local backup_clip_rect_min_x = window.ClipRect.Min.x local backup_clip_rect_max_x = window.ClipRect.Max.x window.ClipRect.Min.x = window.ParentWorkRect.Min.x @@ -48528,6 +54874,10 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasDisplayRect) ImRect_Copy(g.LastItemData.DisplayRect, frame_bb) + -- 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.NavLeftJumpsToParent by default or move it to ImGuiStyle. local store_tree_node_stack_data = false if bit32.band(flags, ImGuiTreeNodeFlags.DrawLinesMask_) == 0 then flags = bit32.bor(flags, g.Style.TreeLinesFlags) @@ -48546,13 +54896,13 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) if not is_visible then if bit32.band(flags, ImGuiTreeNodeFlags.DrawLinesToNodes) ~= 0 and bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.lshift(1, (window.DC.TreeDepth - 1))) ~= 0 then local parent_data = g.TreeNodeStack.Data[g.TreeNodeStack.Size] - parent_data.DrawLinesToNodesY2 = ImMax(parent_data.DrawLinesToNodesY2, window.DC.CursorPos.y) + 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 then - window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(bit32.lshift(1, (window.DC.TreeDepth - 1)))) + window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(bit32.lshift(1, (window.DC.TreeDepth - 1)))) -- Done end end if is_open and store_tree_node_stack_data then - TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) -- Call before TreePushOverrideID() end if is_open and bit32.band(flags, ImGuiTreeNodeFlags.NoTreePushOnOpen) == 0 then ImGui.TreePushOverrideID(id) @@ -48575,15 +54925,27 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnDragDropHold) end + -- We allow clicking on the arrow section with keyboard modifiers held, in order to easily + -- allow browsing a tree while preserving selection with code implementing multi-selection patterns. + -- When clicking on the rest of the tree node we always disallow keyboard modifiers. local arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x local arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0) + style.TouchExtraPadding.x local is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 and g.IO.MousePos.x < arrow_hit_x2) local is_multi_select = bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0 - if is_multi_select then + if is_multi_select then -- We absolutely need to distinguish open vs select so _OpenOnArrow comes by default flags = bit32.bor(flags, (bit32.band(flags, ImGuiTreeNodeFlags.OpenOnMask_) == 0) and bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick) or ImGuiTreeNodeFlags.OpenOnArrow) end + -- Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags. + -- Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support. + -- - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0) + -- - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0) + -- - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1) + -- - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1) + -- - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0) + -- It is rather standard that arrow click react on Down rather than Up. + -- We set ImGuiButtonFlags.PressedOnClickRelease on OpenOnDoubleClick because we want the item to be active on the initial MouseDown in order for drag and drop to work. if is_mouse_x_over_arrow then button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClick) elseif bit32.band(flags, ImGuiTreeNodeFlags.OpenOnDoubleClick) ~= 0 then @@ -48598,7 +54960,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local selected = bit32.band(flags, ImGuiTreeNodeFlags.Selected) ~= 0 local was_selected = selected + -- Multi-selection support (header) if is_multi_select then + -- Handle multi-select + alter button flags for it selected, button_flags = ImGui.MultiSelectItemHeader(id, selected, button_flags) if is_mouse_x_over_arrow then button_flags = bit32.band(bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClick), bit32.bnot(ImGuiButtonFlags.PressedOnClickRelease)) @@ -48614,20 +54978,20 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) if not is_leaf then if pressed and g.DragDropHoldJustPressedId ~= id then if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnMask_) == 0 or (g.NavActivateId == id and not is_multi_select) then - toggled = true + toggled = true -- Single click end if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnArrow) ~= 0 then - toggled = toggled or (is_mouse_x_over_arrow and not g.NavHighlightItemUnderNav) + toggled = toggled or (is_mouse_x_over_arrow and not g.NavHighlightItemUnderNav) -- Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job end if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnDoubleClick) ~= 0 and g.IO.MouseClickedCount[0] == 2 then - toggled = true + toggled = true -- Double click end elseif pressed and g.DragDropHoldJustPressedId == id then IM_ASSERT(bit32.band(button_flags, ImGuiButtonFlags.PressedOnDragDropHold) ~= 0) - if not is_open then + if not is_open then -- When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again. toggled = true else - pressed = false + pressed = false -- Cancel press so it doesn't trigger selection. end end @@ -48636,7 +55000,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavMoveRequestCancel() end - if g.NavId == id and g.NavMoveDir == ImGuiDir.Right and not is_open then + if g.NavId == id and g.NavMoveDir == ImGuiDir.Right and not is_open then -- If there's something upcoming on the line we may want to give it the priority? toggled = true ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavMoveRequestCancel() @@ -48649,6 +55013,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end end + -- Multi-selection support (footer) if is_multi_select then local pressed_copy = pressed and not toggled selected, pressed_copy = ImGui.MultiSelectItemFooter(id, selected, pressed_copy) @@ -48666,9 +55031,10 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local text_col = ImGui.GetColorU32(ImGuiCol.Text) local nav_render_cursor_flags = ImGuiNavRenderCursorFlags.Compact if is_multi_select then - nav_render_cursor_flags = bit32.bor(nav_render_cursor_flags, ImGuiNavRenderCursorFlags.AlwaysDraw) + nav_render_cursor_flags = bit32.bor(nav_render_cursor_flags, ImGuiNavRenderCursorFlags.AlwaysDraw) -- Always show the nav rectangle end if display_frame then + -- Framed type local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header)) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding) ImGui.RenderNavCursor(frame_bb, id, nav_render_cursor_flags) @@ -48679,7 +55045,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col) elseif not is_leaf then ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 1.0) - else + else -- Leaf without bullet, left-adjusted text text_pos.x = text_pos.x - (text_offset_x - padding.x) end if bit32.band(flags, ImGuiTreeNodeFlags.ClipLabelForTrailingButton) ~= 0 then @@ -48689,6 +55055,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) -- ImGui.LogSetNextTextDecoration("###", "###") -- end else + -- Unframed typed for tree nodes if hovered or selected then local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header)) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false, 0.0) @@ -48711,6 +55078,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5)) end + -- Label if display_frame then ImGui.RenderTextClipped(text_pos, frame_bb.Max, label, label_end, label_size) else @@ -48723,16 +55091,18 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end if is_open and store_tree_node_stack_data then - TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) -- Call before TreePushOverrideID() end if is_open and bit32.band(flags, ImGuiTreeNodeFlags.NoTreePushOnOpen) == 0 then - ImGui.TreePushOverrideID(id) + ImGui.TreePushOverrideID(id) -- Could use TreePush(label) but this avoid computing twice end -- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); return is_open end +-- Draw horizontal line from our parent node +-- This is only called for visible child nodes so we are not too fussy anymore about performances --- @param target_pos ImVec2 function ImGui.TreeNodeDrawLineToChildNode(target_pos) local g = GImGui @@ -48741,6 +55111,7 @@ function ImGui.TreeNodeDrawLineToChildNode(target_pos) return end + -- FIXME: Could this be simplified using new stroke flags? local parent_data = g.TreeNodeStack.Data[g.TreeNodeStack.Size] local x1 = ImTrunc(parent_data.DrawLinesX1) local x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x) @@ -48762,6 +55133,7 @@ function ImGui.TreeNodeDrawLineToChildNode(target_pos) end end +-- Draw vertical line of the hierarchy --- @param data ImGuiTreeNodeStackData function ImGui.TreeNodeDrawLineToTreePop(data) local g = GImGui @@ -48774,7 +55146,7 @@ function ImGui.TreeNodeDrawLineToTreePop(data) y2_full = ImMax(g.CurrentTable.RowPosY2, y2_full) end y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5) - if y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full then + if y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full then -- FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y y2 = y2_full end end @@ -48782,10 +55154,12 @@ function ImGui.TreeNodeDrawLineToTreePop(data) if y2 <= y1 then return end - local x = ImTrunc(data.DrawLinesX1 - g.Style.TreeLinesSize * 0.5) + g.Style.TreeLinesSize * 0.5 + local x = ImTrunc(data.DrawLinesX1 - g.Style.TreeLinesSize * 0.5) + g.Style.TreeLinesSize * 0.5 -- Draw line centered at X1, but snap to pixels boundary. if data.DrawLinesTableColumn ~= -1 then ImGui.TablePushColumnChannel(data.DrawLinesTableColumn) end + + -- We use AddLine() instead of AddLineV() as we provide coordinates for line center (FIXME-OPT) window.DrawList:AddLine(ImVec2(x, y1), ImVec2(x, y2), ImGui.GetColorU32(ImGuiCol.TreeLines), g.Style.TreeLinesSize) if data.DrawLinesTableColumn ~= -1 then ImGui.TablePopColumnChannel() @@ -48821,12 +55195,14 @@ function ImGui.TreePop() local data = g.TreeNodeStack.Data[g.TreeNodeStack.Size] IM_ASSERT(data.ID == window.IDStack:back()) + -- Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags.NavLeftJumpsToParent is enabled) if bit32.band(data.TreeFlags, ImGuiTreeNodeFlags.NavLeftJumpsToParent) ~= 0 then if g.NavIdIsAlive and g.NavMoveDir == ImGuiDir.Left and g.NavWindow == window and ImGui.NavMoveRequestButNoResultYet() then ImGui.NavMoveRequestResolveWithPastTreeNode(g.NavMoveResultLocal, data) end end + -- Draw hierarchy lines if data.DrawLinesX1 ~= FLT_MAX and window.DC.CursorPos.y >= window.ClipRect.Min.y then ImGui.TreeNodeDrawLineToTreePop(data) end @@ -48836,10 +55212,11 @@ function ImGui.TreePop() window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(tree_depth_mask)) end - IM_ASSERT(window.IDStack.Size > 1) + 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. ImGui.PopID() end +-- Set next TreeNode/CollapsingHeader open state. --- @param is_open bool --- @param cond? ImGuiCond function ImGui.SetNextItemOpen(is_open, cond) @@ -48860,6 +55237,7 @@ function ImGui.GetTreeNodeToLabelSpacing() return g.FontSize + (g.Style.FramePadding.x * 2.0) end +-- Set next TreeNode/CollapsingHeader storage id. --- @param storage_id ImGuiID function ImGui.SetNextItemStorageID(storage_id) local g = GImGui @@ -48870,8 +55248,14 @@ function ImGui.SetNextItemStorageID(storage_id) g.NextItemData.StorageId = storage_id end +-- CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags.NoTreePushOnOpen flag). +-- This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags.CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). -- Overloads: CollapsingHeader(label, flags?) -> is_open -- CollapsingHeader(label, p_visible: bool, flags?) -> is_open, p_visible +-- p_visible == nil : regular collapsing header +-- p_visible == true : show a small close button on the corner of the header, clicking the button will set p_visible = false (returned as 2nd value) +-- p_visible == false : do not show the header at all +-- Do not mistake this with the Open state of the header itself, which you can adjust with SetNextItemOpen() or ImGuiTreeNodeFlags.DefaultOpen. --- @param label string function ImGui.CollapsingHeader(label, a, b) @@ -48896,6 +55280,8 @@ function ImGui.CollapsingHeader(label, a, b) local is_open = ImGui.TreeNodeBehavior(id, flags, label) if p_visible ~= nil then -- Create a small overlapping close button + -- FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + -- FIXME: CloseButton can overlap into text, need find a way to clip the text somehow. local g = GImGui local last_item_backup = ImGuiLastItemData() ImGuiLastItemData_Copy(last_item_backup, g.LastItemData) @@ -48912,15 +55298,15 @@ function ImGui.CollapsingHeader(label, a, b) return is_open, p_visible end ----------------------------------------------------------------- --- [SECTION] SELECTABLE ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Selectable +------------------------------------------------------------------------------- -- - Selectable() ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image. -- But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id. --- With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowOverlap are also frequently used flags. +-- With this scheme, ImGuiSelectableFlags.SpanAllColumns and ImGuiSelectableFlags.AllowOverlap are also frequently used flags. -- FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported. --- @param label string --- @param selected? bool @@ -48942,6 +55328,7 @@ function ImGui.Selectable(label, selected, flags, size_arg) local g = GImGui local style = g.Style + -- Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle. local id = window:GetID(label) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) @@ -48976,6 +55363,7 @@ function ImGui.Selectable(label, selected, flags, size_arg) bb.Max.x = bb.Max.x + (spacing_x - spacing_L) bb.Max.y = bb.Max.y + (spacing_y - spacing_U) end + -- if g.IO.KeyCtrl then ImGui.GetForegroundDrawList():AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)) end local disabled_item = bit32.band(flags, ImGuiSelectableFlags.Disabled) ~= 0 local extra_item_flags = disabled_item and ImGuiItemFlags.Disabled or ImGuiItemFlags.None @@ -49000,16 +55388,14 @@ function ImGui.Selectable(label, selected, flags, size_arg) local is_multi_select = bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0 if not is_visible then - if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(bb) then - -- Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd) + if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(bb) then -- Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd) return false, selected end end local disabled_global = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0 - if disabled_item and not disabled_global then - -- Only testing this as an optimization + if disabled_item and not disabled_global then -- Only testing this as an optimization ImGui.BeginDisabled() end @@ -49068,7 +55454,7 @@ function ImGui.Selectable(label, selected, flags, size_arg) -- Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad if pressed or (hovered and bit32.band(flags, ImGuiSelectableFlags.SetNavIdOnHover) ~= 0) then if not g.NavHighlightItemUnderNav and g.NavWindow == window and g.NavLayer == window.DC.NavLayerCurrent then - ImGui.SetNavID(id, window.DC.NavLayerCurrent, g.CurrentFocusScopeId, ImGui.WindowRectAbsToRel(window, bb)) -- (bb == NavRect) + ImGui.SetNavID(id, window.DC.NavLayerCurrent, g.CurrentFocusScopeId, ImGui.WindowRectAbsToRel(window, bb)) -- (bb == NavRect) if g.IO.ConfigNavCursorVisibleAuto then g.NavCursorVisible = false end @@ -49134,15 +55520,25 @@ function ImGui.Selectable(label, selected, flags, size_arg) ImGui.EndDisabled() end - -- Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui::IsItemToggledSelection() to retrieve + -- Selectable() always returns a pressed state! + -- Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui.IsItemToggledSelection() to retrieve -- selection toggle, only useful if you need that state updated (e.g. for rendering purpose) before reaching EndMultiSelect(). return pressed, selected end ----------------------------------------------------------------- --- [SECTION] LISTBOX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: ListBox +------------------------------------------------------------------------------- +-- - BeginListBox() +-- - EndListBox() +-- - ListBox() +------------------------------------------------------------------------------- +-- 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. +-- 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.5f * item_height). --- @param label string --- @param size_arg? ImVec2 function ImGui.BeginListBox(label, size_arg) @@ -49158,6 +55554,8 @@ function ImGui.BeginListBox(label, size_arg) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) + -- Size default to hold ~7.25 items. + -- Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. local size = ImTrunc(ImGui.CalcItemSize(size_arg, ImGui.CalcItemWidth(), ImGui.GetTextLineHeightWithSpacing() * 7.25 + style.FramePadding.y * 2.0)) local frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)) local frame_bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + frame_size) @@ -49167,10 +55565,11 @@ function ImGui.BeginListBox(label, size_arg) if not ImGui.IsRectVisible(bb.Min, bb.Max) then ImGui.ItemSize(bb:GetSize(), style.FramePadding.y) ImGui.ItemAdd(bb, 0, frame_bb) - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values return false end + -- FIXME-OPT: We could omit the BeginGroup() if label_size.x == 0.0f but would need to omit the EndGroup() as well. ImGui.BeginGroup() if label_size.x > 0.0 then local label_pos = ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y) @@ -49189,9 +55588,11 @@ function ImGui.EndListBox() IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0, "Mismatched BeginListBox/EndListBox calls. Did you test the return value of BeginListBox?") ImGui.EndChild() - ImGui.EndGroup() + ImGui.EndGroup() -- This is only required to be able to do IsItemXXX query on the whole ListBox including label end +-- This is merely a helper around BeginListBox(), EndListBox(). +-- Considering using those directly to submit custom data or store selection differently. -- Overloads: (label, current_item, items[], items_count?, height_in_items?) or (label, current_item, getter, user_data, items_count, height_in_items?) --- @param current_item int # 0-based --- @return int current_item @@ -49201,6 +55602,7 @@ function ImGui.ListBox(label, current_item, a, b, c, d) local getter, user_data, items_count, height_in_items = Items_ResolveArgs(a, b, c, d) if height_in_items == nil then height_in_items = -1 end + -- Calculate size from "height_in_items" if height_in_items < 0 then height_in_items = ImMin(items_count, 7) end @@ -49211,9 +55613,11 @@ function ImGui.ListBox(label, current_item, a, b, c, d) return current_item, false end + -- Assume all items have even height (= 1 line of text). If you need items of different height, + -- you can create a custom version of ListBox() in your code without using the clipper. local value_changed = false local clipper = ImGuiListClipper() - clipper:Begin(items_count, ImGui.GetTextLineHeightWithSpacing()) + clipper:Begin(items_count, ImGui.GetTextLineHeightWithSpacing()) -- We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. clipper:IncludeItemByIndex(current_item) while clipper:Step() do for i = clipper.DisplayStart, clipper.DisplayEnd - 1 do @@ -49243,9 +55647,16 @@ function ImGui.ListBox(label, current_item, a, b, c, d) return current_item, value_changed end ----------------------------------------------------------------- --- [SECTION] BASIC PLOTTING ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: PlotLines, PlotHistogram +------------------------------------------------------------------------------- +-- - PlotEx() [Internal] +-- - PlotLines() +-- - PlotHistogram() +------------------------------------------------------------------------------- +-- Plot/Graph widgets are not very good. +-- Consider using ImPlot (https://github.com/epezent/implot) which is much better! +------------------------------------------------------------------------------- --- @param plot_type ImGuiPlotType --- @param label string @@ -49282,6 +55693,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local _, hovered, _ = ImGui.ButtonBehavior(frame_bb, id) + -- Determine scale from values if not specified if scale_min == FLT_MAX or scale_max == FLT_MAX then local v_min = FLT_MAX local v_max = -FLT_MAX @@ -49308,6 +55720,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local res_w = ImMin(math.floor(frame_size.x), values_count) + ((plot_type == ImGuiPlotType.Lines) and -1 or 0) local item_count = values_count + ((plot_type == ImGuiPlotType.Lines) and -1 or 0) + -- Tooltip on hover if hovered and inner_bb:Contains(g.IO.MousePos) then local t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0, 0.999) local v_idx = math.floor(t * item_count) + 1 @@ -49328,8 +55741,8 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local v0 = values_getter(data, (0 + values_offset) % values_count + 1) local t0 = 0.0 - local tp0 = ImVec2(t0, 1.0 - ImSaturate((v0 - scale_min) * inv_scale)) - local histogram_zero_line_t = (scale_min * scale_max < 0.0) and (1 + scale_min * inv_scale) or (scale_min < 0.0 and 0.0 or 1.0) + local tp0 = ImVec2(t0, 1.0 - ImSaturate((v0 - scale_min) * inv_scale)) -- Point in the normalized space of our target rectangle + local histogram_zero_line_t = (scale_min * scale_max < 0.0) and (1 + scale_min * inv_scale) or (scale_min < 0.0 and 0.0 or 1.0) -- Where does the zero line stands local col_base = ImGui.GetColorU32((plot_type == ImGuiPlotType.Lines) and ImGuiCol.PlotLines or ImGuiCol.PlotHistogram) local col_hovered = ImGui.GetColorU32((plot_type == ImGuiPlotType.Lines) and ImGuiCol.PlotLinesHovered or ImGuiCol.PlotHistogramHovered) @@ -49341,6 +55754,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local v1 = values_getter(data, (v1_idx - 1 + values_offset + 1) % values_count + 1) local tp1 = ImVec2(t1, 1.0 - ImSaturate((v1 - scale_min) * inv_scale)) + -- NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. local pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0) local pos1 if plot_type == ImGuiPlotType.Lines then @@ -49363,6 +55777,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value end end + -- Text overlay if overlay_text then ImGui.RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, nil, nil, ImVec2(0.5, 0.0)) end @@ -49371,6 +55786,8 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label, 1, label_end, false) end + -- Return hovered index or -1 if none are hovered. + -- This is currently not exposed in the public API because we need a larger redesign of the whole thing, but in the short-term we are making it available in PlotEx(). return idx_hovered end @@ -49422,6 +55839,7 @@ function ImGui.PlotLines(label, values_or_getter, data, values_count, values_off end end +-- Plot Histogram (the data provided _is_ histogram data. it doesn't compute the histogram of your data) --- @param label string --- @param values_or_getter table|fun(data:table, i:int) # 1-based table or a function --- @param data? table # 1-based table @@ -49447,10 +55865,21 @@ function ImGui.PlotHistogram(label, values_or_getter, data, values_count, values end end ----------------------------------------------------------------- --- [SECTION] MENU RELATED ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] MenuItem, BeginMenu, EndMenu, etc. +------------------------------------------------------------------------------- +-- - ImGuiMenuColumns [Internal] +-- - BeginMenuBar() +-- - EndMenuBar() +-- - BeginMainMenuBar() +-- - EndMainMenuBar() +-- - BeginMenu() +-- - EndMenu() +-- - MenuItemEx() [Internal] +-- - MenuItem() +------------------------------------------------------------------------------- +-- Helpers for internal use --- @param spacing float --- @param window_reappearing bool function MT.ImGuiMenuColumns:Update(spacing, window_reappearing) @@ -49511,7 +55940,7 @@ function ImGui.BeginMenuBar() end IM_ASSERT(not window.DC.MenuBarAppending) - ImGui.BeginGroup() -- FIXME: Misleading to use a group for that backup/restore + ImGui.BeginGroup() -- Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore ImGui.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. @@ -49523,7 +55952,7 @@ function ImGui.BeginMenuBar() clip_rect:ClipWith(window.OuterRectClipped) ImGui.PushClipRect(clip_rect.Min, clip_rect.Max, false) - -- We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags) + -- We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags). ImVec2_Copy(window.DC.CursorPos, ImVec2(bar_rect.Min.x + window.DC.MenuBarOffset.x, bar_rect.Min.y + window.DC.MenuBarOffset.y)) ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorPos) window.DC.LayoutType = ImGuiLayoutType.Horizontal @@ -49545,24 +55974,28 @@ function ImGui.EndMenuBar() IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.MenuBar) ~= 0) 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 + -- Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings. if ImGui.NavMoveRequestButNoResultYet() and (g.NavMoveDir == ImGuiDir.Left or g.NavMoveDir == ImGuiDir.Right) and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then + -- Try to find out if the request is for one of our child menu local nav_earliest_child = g.NavWindow while nav_earliest_child.ParentWindow and bit32.band(nav_earliest_child.ParentWindow.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 do nav_earliest_child = nav_earliest_child.ParentWindow end if nav_earliest_child.ParentWindow == window and nav_earliest_child.DC.ParentLayoutType == ImGuiLayoutType.Horizontal and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) == 0 then + -- To do so we claim focus back, restore NavId and then process the movement request for yet another frame. + -- This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth bothering) local layer = ImGuiNavLayer.Menu - IM_ASSERT(bit32.band(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, layer)) ~= 0) + IM_ASSERT(bit32.band(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, layer)) ~= 0) -- Sanity check (FIXME: Seems unnecessary) ImGui.FocusWindow(window) ImGui.SetNavID(window.NavLastIds[layer], layer, 0, window.NavRectRel[layer]) + -- FIXME-NAV: How to deal with this when not using g.IO.ConfigNavCursorVisibleAuto? if g.NavCursorVisible then - g.NavCursorVisible = false + g.NavCursorVisible = false -- Hide nav cursor for the current frame so we don't see the intermediary selection. Will be set again g.NavCursorHideFrames = 2 end g.NavHighlightItemUnderNav = true g.NavMousePosDirty = true - ImGui.NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags) + ImGui.NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags) -- Repeat end else ImGui.NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags.WrapX) @@ -49570,14 +56003,14 @@ function ImGui.EndMenuBar() ImGui.PopClipRect() ImGui.PopID() - 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 + 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 + -- FIXME: Extremely confusing, cleanup by (a) working on WorkRect stack system (b) not using a Group confusingly here. local group_data = g.GroupStack:back() group_data.EmitItem = false local restore_cursor_max_pos = ImVec2() ImVec2_Copy(restore_cursor_max_pos, group_data.BackupCursorMaxPos) - window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, window.DC.CursorMaxPos.x - window.Scroll.x) -- Convert ideal extents for scrolling layer equivalent + window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, window.DC.CursorMaxPos.x - window.Scroll.x) -- Convert ideal extents for scrolling layer equivalent. ImGui.EndGroup() -- Restore position on layer 0 // FIXME: Misleading to use a group for that backup/restore window.DC.LayoutType = ImGuiLayoutType.Vertical window.DC.IsSameLine = false @@ -49587,6 +56020,8 @@ function ImGui.EndMenuBar() end -- Important: calling order matters! +-- FIXME: Somehow overlapping with docking tech. +-- FIXME: The "rect-cut" aspect of this could be formalized into a lower-level helper (rect-cut: https://halt.software/dead-simple-layouts) --- @param name string --- @param viewport_p? ImGuiViewport --- @param dir ImGuiDir @@ -49598,6 +56033,7 @@ function ImGui.BeginViewportSideBar(name, viewport_p, dir, axis_size, window_fla local bar_window = ImGui.FindWindowByName(name) local viewport = viewport_p or ImGui.GetMainViewport() if bar_window == nil or bar_window.BeginCount == 0 then + -- Calculate and set window size/position local avail_rect = viewport:GetBuildWorkRect() local axis = (dir == ImGuiDir.Up or dir == ImGuiDir.Down) and ImGuiAxis.Y or ImGuiAxis.X local pos = ImVec2(avail_rect.Min.x, avail_rect.Min.y) @@ -49609,6 +56045,7 @@ function ImGui.BeginViewportSideBar(name, viewport_p, dir, axis_size, window_fla ImGui.SetNextWindowPos(pos) ImGui.SetNextWindowSize(size) + -- Report our size into work area (for next frame) using actual window size if dir == ImGuiDir.Up or dir == ImGuiDir.Left then viewport.BuildWorkInsetMin[axis] = viewport.BuildWorkInsetMin[axis] + axis_size elseif dir == ImGuiDir.Down or dir == ImGuiDir.Right then @@ -49619,7 +56056,7 @@ function ImGui.BeginViewportSideBar(name, viewport_p, dir, axis_size, window_fla window_flags = bit32.bor(window_flags or 0, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoDocking) ImGui.SetNextWindowViewport(viewport.ID) ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 0.0) - ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, ImVec2(0, 0)) + ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, ImVec2(0, 0)) -- Lift normal size constraint local _, is_open = ImGui.Begin(name, nil, window_flags) ImGui.PopStyleVar(2) @@ -49630,8 +56067,12 @@ function ImGui.BeginMainMenuBar() local g = GImGui local viewport = ImGui.GetMainViewport() + -- Notify of viewport change so GetFrameHeight() can be accurate in case of DPI change ImGui.SetCurrentViewport(nil, viewport) + -- For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set. + -- FIXME: This could be generalized as an opt-in way to clamp window.DC.CursorStartPos to avoid SafeArea? + -- FIXME: Consider removing support for safe area down the line... it's messy. Nowadays consoles have support for TV calibration in OS settings. g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0)) local window_flags = bit32.bor(ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.MenuBar) local height = ImGui.GetFrameHeight() @@ -49642,6 +56083,7 @@ function ImGui.BeginMainMenuBar() return false end + -- 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 = bit32.band(g.CurrentWindow.Flags, bit32.bnot(ImGuiWindowFlags.NoSavedSettings)) ImGui.BeginMenuBar() return is_open @@ -49649,11 +56091,13 @@ end function ImGui.EndMainMenuBar() local g = GImGui - IM_ASSERT_USER_ERROR_RET(g.CurrentWindow.DC.MenuBarAppending, "Calling EndMainMenuBar() not from a menu-bar!") + IM_ASSERT_USER_ERROR_RET(g.CurrentWindow.DC.MenuBarAppending, "Calling EndMainMenuBar() not from a menu-bar!") -- Not technically testing that it is the main menu bar ImGui.EndMenuBar() - g.CurrentWindow.Flags = bit32.bor(g.CurrentWindow.Flags, ImGuiWindowFlags.NoSavedSettings) + g.CurrentWindow.Flags = bit32.bor(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 nil focus. if g.CurrentWindow == g.NavWindow and g.NavLayer == ImGuiNavLayer.Main and not g.NavAnyRequest and g.ActiveId == 0 then ImGui.FocusTopMostWindowUnderOne(g.NavWindow, nil, nil, bit32.bor(ImGuiFocusRequestFlags.UnlessBelowModal, ImGuiFocusRequestFlags.RestoreFocusedChild)) end @@ -49668,6 +56112,17 @@ local function IsRootOfOpenMenuSet() return false end + -- Initially we used 'upper_popup.OpenParentId == window.IDStack:back()' to differentiate multiple menu sets from each others + -- (e.g. inside menu bar vs loose menu items) based on parent ID. + -- This would however prevent the use of e.g. PushID() user code submitting menus. + -- Previously this worked between popup and a first child menu because the first child menu always had the _ChildWindow flag, + -- making hovering on parent popup possible while first child menu was focused - but this was generally a bug with other side effects. + -- Instead we don't treat Popup specifically (in order to consistently support menu features in them), maybe the first child menu of a Popup + -- doesn't have the _ChildWindow flag, and we rely on this IsRootOfOpenMenuSet() check to allow hovering between root window/popup and first child menu. + -- In the end, lack of ID check made it so we could no longer differentiate between separate menu sets. To compensate for that, we at least check parent window nav layer. + -- This fixes the most common case of menu opening on hover when moving between window content and menu bar. Multiple different menu sets in same nav layer would still + -- open on hover, but that should be a lesser problem, because if such menus are close in proximity in window content then it won't feel weird and if they are far apart + -- it likely won't be a problem anyone runs into. local upper_popup = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1] if window.DC.NavLayerCurrent ~= upper_popup.ParentNavLayer then return false @@ -49689,30 +56144,41 @@ function ImGui.BeginMenuEx(label, icon, enabled) local id = window:GetID(label) local menu_is_open = ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) + -- Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu) + -- The first menu in a hierarchy isn't so hovering doesn't get across (otherwise e.g. resizing borders with ImGuiButtonFlags.FlattenChildren would react), but top-most BeginMenu() will bypass that limitation. local window_flags = bit32.bor(ImGuiWindowFlags.ChildMenu, ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoNavFocus) if bit32.band(window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.ChildWindow) end + -- If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin(). + -- We are relying on a O(N) search - so O(N log N) over the frame - which seems like the most efficient for the expected small amount of BeginMenu() calls per frame. + -- If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used. if g.MenusIdSubmittedThisFrame:contains(id) then if menu_is_open then - menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags) + menu_is_open = ImGui.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() + g.NextWindowData:ClearFlags() -- we behave like Begin() and need to consume those values end return menu_is_open end + -- Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu g.MenusIdSubmittedThisFrame:push_back(id) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) + -- Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent without always being a Child window) + -- This is only done for items for the menu set and not the full parent window. local menuset_is_open = IsRootOfOpenMenuSet() if menuset_is_open then g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoWindowHoverableCheck) end + -- The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu, + -- However the final position is going to be different! It is chosen by FindBestWindowPosForPopup(). + -- e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering. local popup_pos local pos = ImVec2() ImVec2_Copy(pos, window.DC.CursorPos) @@ -49728,6 +56194,9 @@ function ImGui.BeginMenuEx(label, icon, enabled) local selectable_flags = bit32.bor(ImGuiSelectableFlags.SelectOnClick, ImGuiSelectableFlags.NoAutoClosePopups) local offsets = window.DC.MenuColumns if window.DC.LayoutType == ImGuiLayoutType.Horizontal then + -- 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() window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * 0.5) ImGui.PushStyleVarX(ImGuiStyleVar.ItemSpacing, style.ItemSpacing.x * 2.0) local text_pos = ImVec2(window.DC.CursorPos.x + offsets.OffsetLabel, pos.y + window.DC.CurrLineTextBaseOffset) @@ -49735,13 +56204,16 @@ function ImGui.BeginMenuEx(label, icon, enabled) -- TODO: ImGui.LogSetNextTextDecoration("[", "]") ImGui.RenderText(text_pos, label, 1, label_end, false) ImGui.PopStyleVar() - window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) + window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) -- -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). popup_pos = ImVec2(pos.x - 1.0 - IM_TRUNC(style.ItemSpacing.x * 0.5), text_pos.y - style.FramePadding.y + window.MenuBarHeight) else + -- 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.) local icon_w if (icon and icon ~= "") then icon_w = ImGui.CalcTextSize(icon, nil).x else icon_w = 0.0 end local checkmark_w = IM_TRUNC(g.FontSize * 1.20) - local min_w = offsets:DeclColumns(icon_w, label_size.x, 0.0, checkmark_w) + local min_w = offsets:DeclColumns(icon_w, label_size.x, 0.0, checkmark_w) -- Feedback to next frame local extra_w = ImMax(0.0, ImGui.GetContentRegionAvail().x - min_w) local text_pos = ImVec2(window.DC.CursorPos.x, pos.y + window.DC.CurrLineTextBaseOffset) pressed = ImGui.Selectable("", menu_is_open, bit32.bor(selectable_flags, ImGuiSelectableFlags.SpanAvailWidth), ImVec2(min_w, label_size.y)) @@ -49760,6 +56232,8 @@ function ImGui.BeginMenuEx(label, icon, enabled) ImGui.EndDisabled() end + -- Once dragged, release ActiveId + key ownership. This is to allow the idiom of mouse down a menu, dragging elsewhere, up on some other MenuItem(). (#8233, #9394) + -- Could move logic into lower-level ImGuiButtonFlags.AutoReleaseActiveId + ImGuiButtonFlags.AutoReleaseKeyOwner? Easier once we get rid of the Selectable() middle-man here. if g.ActiveId == id and g.HoveredId ~= id and g.ActiveIdSource == ImGuiInputSource.Mouse and ImGui.IsMouseDragging(0) then ImGui.ClearActiveID() ImGui.SetKeyOwner(ImGuiKey.MouseLeft, ImGuiKeyOwner_NoOwner) @@ -49770,12 +56244,14 @@ function ImGui.BeginMenuEx(label, icon, enabled) local want_open = false local want_open_nav_init = false local want_close = false - if window.DC.LayoutType == ImGuiLayoutType.Vertical then + if window.DC.LayoutType == ImGuiLayoutType.Vertical then -- (window.Flags & (ImGuiWindowFlags.Popup|ImGuiWindowFlags.ChildMenu)) + -- Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu + -- Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. local moving_toward_child_menu = false - local child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) and g.OpenPopupStack[g.BeginPopupStack.Size + 1] or nil + local child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) and g.OpenPopupStack[g.BeginPopupStack.Size + 1] or nil -- Popup candidate (testing below) local child_menu_window = (child_popup and child_popup.Window and child_popup.Window.ParentWindow == window) and child_popup.Window or nil if g.HoveredWindow == window and child_menu_window ~= nil then - local ref_unit = g.FontSize + local ref_unit = g.FontSize -- FIXME-DPI local child_dir = (window.Pos.x < child_menu_window.Pos.x) and 1.0 or -1.0 local next_window_rect = child_menu_window:Rect() local ta = (g.IO.MousePos - g.IO.MouseDelta) @@ -49788,46 +56264,53 @@ function ImGui.BeginMenuEx(label, icon, enabled) tb = next_window_rect:GetTR() tc = next_window_rect:GetBR() end - local pad_farmost_h = ImClamp(ImFabs(ta.x - tb.x) * 0.30, ref_unit * 0.5, ref_unit * 2.5) + local pad_farmost_h = ImClamp(ImFabs(ta.x - tb.x) * 0.30, ref_unit * 0.5, ref_unit * 2.5) -- Add a bit of extra slack. ta.x = ta.x + child_dir * -0.5 tb.x = tb.x + child_dir * ref_unit tc.x = tc.x + child_dir * ref_unit - tb.y = ta.y + ImMax((tb.y - pad_farmost_h) - ta.y, -ref_unit * 8.0) + tb.y = ta.y + ImMax((tb.y - pad_farmost_h) - ta.y, -ref_unit * 8.0) -- Triangle has maximum height to limit the slope and the bias toward large sub-menus tc.y = ta.y + ImMin((tc.y + pad_farmost_h) - ta.y, ref_unit * 8.0) moving_toward_child_menu = ImStd.ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos) + -- ImGui.GetForegroundDrawList():AddTriangleFilled(ta, tb, tc, moving_toward_child_menu and IM_COL32(0, 128, 0, 128) or IM_COL32(128, 0, 0, 128)) -- [DEBUG] end + -- The 'HovereWindow == window' check creates an inconsistency (e.g. moving away from menu slowly tends to hit same window, whereas moving away fast does not) + -- But we also need to not close the top-menu menu when moving over void. Perhaps we should extend the triangle check to a larger polygon. + -- (Remember to test this on BeginPopup("A")->BeginMenu("B") sequence which behaves slightly differently as B isn't a Child of A and hovering isn't shared.) if menu_is_open and not hovered and g.HoveredWindow == window and not moving_toward_child_menu and not g.NavHighlightItemUnderNav and g.ActiveId == 0 then want_close = true end - if not menu_is_open and pressed then + -- Open + -- (note: at this point 'hovered' actually includes the NavDisableMouseHover == false test) + if not menu_is_open and pressed then -- Click/activate to open want_open = true - elseif not menu_is_open and hovered and not moving_toward_child_menu then + elseif not menu_is_open and hovered and not moving_toward_child_menu then -- Hover to open want_open = true - elseif not menu_is_open and hovered and g.HoveredIdTimer >= 0.30 and g.MouseStationaryTimer >= 0.30 then + elseif not menu_is_open and hovered and g.HoveredIdTimer >= 0.30 and g.MouseStationaryTimer >= 0.30 then -- Hover to open (timer fallback) want_open = true end - if g.NavId == id and g.NavMoveDir == ImGuiDir.Right then + if g.NavId == id and g.NavMoveDir == ImGuiDir.Right then -- Nav-Right to open want_open = true want_open_nav_init = true ImGui.NavMoveRequestCancel() ImGui.SetNavCursorVisibleAfterMove() end else - if menu_is_open and pressed and menuset_is_open then + -- Menu bar + if menu_is_open and pressed and menuset_is_open then -- Click an open menu again to close it want_close = true want_open = false menu_is_open = false - elseif pressed or (hovered and menuset_is_open and not menu_is_open) then + elseif pressed or (hovered and menuset_is_open and not menu_is_open) then -- First click to open, then hover to open others want_open = true - elseif g.NavId == id and g.NavMoveDir == ImGuiDir.Down then + elseif g.NavId == id and g.NavMoveDir == ImGuiDir.Down then -- Nav-Down to open want_open = true ImGui.NavMoveRequestCancel() end end - if not enabled then + if not enabled then -- explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' want_close = true end if want_close and ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then @@ -49842,32 +56325,38 @@ function ImGui.BeginMenuEx(label, icon, enabled) end if want_open and not menu_is_open and g.OpenPopupStack.Size > g.BeginPopupStack.Size then + -- Don't reopen/recycle same menu level in the same frame if it is a different menu ID, first close the other menu and yield for a frame. ImGui.OpenPopup(label) elseif want_open then menu_is_open = true - ImGui.OpenPopup(label, ImGuiPopupFlags.NoReopen) + ImGui.OpenPopup(label, ImGuiPopupFlags.NoReopen) -- | (want_open_nav_init ? ImGuiPopupFlags.NoReopenAlwaysNavInit : 0)) end if menu_is_open then local last_item_in_parent = ImGuiLastItemData() ImGuiLastItemData_Copy(last_item_in_parent, g.LastItemData) - ImGui.SetNextWindowPos(popup_pos, ImGuiCond.Always) - ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.PopupRounding) - menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags) + ImGui.SetNextWindowPos(popup_pos, ImGuiCond.Always) -- Note: misleading: the value will serve as reference for FindBestWindowPosForPopup(), not actual pos. + ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.PopupRounding) -- First level will use _PopupRounding, subsequent will use _ChildRounding + menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags) -- menu_is_open may be 'false' when the popup is completely clipped (e.g. zero size display) ImGui.PopStyleVar() if menu_is_open then + -- Implement what ImGuiPopupFlags.NoReopenAlwaysNavInit would do: + -- Perform an init request in the case the popup was already open (via a previous mouse hover) if want_open and want_open_nav_init and not g.NavInitRequest then ImGui.FocusWindow(g.CurrentWindow, ImGuiFocusRequestFlags.UnlessBelowModal) ImGui.NavInitWindow(g.CurrentWindow, false) end + + -- Restore LastItemData so IsItemXXXX functions can work after BeginMenu()/EndMenu() + -- (This fixes using IsItemClicked() and IsItemHovered(), but IsItemHovered() also relies on its support for ImGuiItemFlags.NoWindowHoverableCheck) ImGuiLastItemData_Copy(g.LastItemData, last_item_in_parent) if g.HoveredWindow == window then g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end end else - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values end return menu_is_open @@ -49882,11 +56371,12 @@ function ImGui.BeginMenu(label, enabled) end function ImGui.EndMenu() + -- Nav: When a left move request our menu failed, close ourselves. local g = GImGui local window = g.CurrentWindow IM_ASSERT_USER_ERROR_RET(bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.ChildMenu)) == bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.ChildMenu), "Calling EndMenu() in wrong window!") - local parent_window = window.ParentWindow + local parent_window = window.ParentWindow -- Should always be ~= nil is we passed assert. if window.BeginCount == window.BeginCountPreviousFrame then if g.NavMoveDir == ImGuiDir.Left and ImGui.NavMoveRequestButNoResultYet() then if g.NavWindow and g.NavWindow.RootWindowForNav == window and parent_window.DC.LayoutType == ImGuiLayoutType.Vertical then @@ -49920,11 +56410,14 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) + -- See BeginMenuEx() for comments about this. local menuset_is_open = IsRootOfOpenMenuSet() if menuset_is_open then g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoWindowHoverableCheck) end + -- We've been using the equivalent of ImGuiSelectableFlags.SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73), + -- but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only. ImGui.PushID(label) if not enabled then ImGui.BeginDisabled() @@ -49932,11 +56425,14 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) local pressed + -- We use ImGuiSelectableFlags.NoSetKeyOwner to allow down on one menu item, move, up on another. local backup_rounding = style.SelectableRounding style.SelectableRounding = style.MenuItemRounding local selectable_flags = bit32.bor(ImGuiSelectableFlags.SelectOnRelease, ImGuiSelectableFlags.SetNavIdOnHover) local offsets = window.DC.MenuColumns if window.DC.LayoutType == ImGuiLayoutType.Horizontal then + -- Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful + -- Note that in this situation: we don't render the shortcut, we render a highlight instead of the selected tick mark. window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * 0.5) local text_pos = ImVec2(window.DC.CursorPos.x + offsets.OffsetLabel, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset) ImGui.PushStyleVarX(ImGuiStyleVar.ItemSpacing, style.ItemSpacing.x * 2.0) @@ -49945,8 +56441,11 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 then ImGui.RenderText(text_pos, label, 1, label_end, false) end - window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) + window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) -- -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). else + -- 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.) local icon_w = 0.0 if icon and icon ~= "" then icon_w = ImGui.CalcTextSize(icon, nil).x @@ -49955,8 +56454,8 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) if shortcut and shortcut ~= "" then shortcut_w = ImGui.CalcTextSize(shortcut, nil).x end - local checkmark_w = IM_TRUNC(g.FontSize * 1.20) - local min_w = offsets:DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w) + local checkmark_w = IM_TRUNC(g.FontSize * 1.20) -- FIXME: Always accounted for, even in a menu with none, because 'selected' has no neutral setting. + local min_w = offsets:DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w) -- Feedback for next frame local stretch_w = ImMax(0.0, ImGui.GetContentRegionAvail().x - min_w) local text_pos = ImVec2(pos.x, pos.y + window.DC.CurrLineTextBaseOffset) pressed = ImGui.Selectable("", false, bit32.bor(selectable_flags, ImGuiSelectableFlags.SpanAvailWidth), ImVec2(min_w, label_size.y)) @@ -49980,6 +56479,8 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) end style.SelectableRounding = backup_rounding + -- Once dragged, release ActiveId + key ownership. This is to allow the idiom of mouse down a menu, dragging elsewhere, up on some other MenuItem(). (#8233, #9394) + -- Could move logic into lower-level ImGuiButtonFlags_AutoReleaseActiveId + ImGuiButtonFlags_AutoReleaseKeyOwner? Easier once we get rid of the Selectable() middle-man here. local id = g.LastItemData.ID if g.ActiveId == id and g.HoveredId ~= id and g.ActiveIdSource == ImGuiInputSource.Mouse and ImGui.IsMouseDragging(0) then ImGui.ClearActiveID() @@ -50060,12 +56561,18 @@ local function SortTabsByBeginOrder(tab_bar) for i = 1, tab_bar.Tabs.Size do data[i] = arr[i] end end +-- Scrolling happens only in the central section (leading/trailing sections are not scrolling) local function TabBarCalcScrollableWidth(tab_bar, sections) return tab_bar.BarRect:GetWidth() - sections[1].Width - sections[3].Width - sections[2].Spacing end +-- TabCount: Number of tabs in this section. +-- Width: Sum of width of tabs in this section (after shrinking down) +-- Spacing: Horizontal spacing at the end of the section. local function ImGuiTabBarSection() return { TabCount = 0, Width = 0.0, WidthAfterShrinkMinWidth = 0.0, Spacing = 0.0 } end +-- 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. -- items: 1-based array of ImGuiShrinkWidthItem, `first` = 1-based index of first item, `count` items function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) if count <= 0 then return end @@ -50074,6 +56581,7 @@ function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) if it.Width >= 0.0 then it.Width = ImMax(it.Width - width_excess, width_min) end return end + -- Sort largest first, smallest last. local slice = {} for n = 1, count do slice[n] = items[first + n - 1] end table.sort(slice, function(a, b) @@ -50098,6 +56606,9 @@ function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) width_excess = width_excess - w end end + + -- Round width and redistribute remainder + -- Ensure that e.g. the right-most tab of a shrunk tab-bar always reaches exactly at the same distance from the right-most edge of the tab bar separator. width_excess = 0.0 for n = 1, count do local width_rounded = ImTrunc(it[n].Width) @@ -50119,15 +56630,39 @@ function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Widgets: BeginTabBar, EndTabBar, etc. ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - BeginTabBar() +-- - BeginTabBarEx() [Internal] +-- - EndTabBar() +-- - TabBarLayout() [Internal] +-- - TabBarCalcTabID() [Internal] +-- - TabBarCalcMaxTabWidth() [Internal] +-- - TabBarFindTabById() [Internal] +-- - TabBarFindTabByOrder() [Internal] +-- - TabBarFindMostRecentlySelectedTabForActiveWindow() [Internal] +-- - TabBarGetCurrentTab() [Internal] +-- - TabBarGetTabName() [Internal] +-- - TabBarAddTab() [Internal] +-- - TabBarRemoveTab() [Internal] +-- - TabBarCloseTab() [Internal] +-- - TabBarScrollClamp() [Internal] +-- - TabBarScrollToTab() [Internal] +-- - TabBarQueueFocus() [Internal] +-- - TabBarQueueReorder() [Internal] +-- - TabBarProcessReorderFromMousePos() [Internal] +-- - TabBarProcessReorder() [Internal] +-- - TabBarScrollingButtons() [Internal] +-- - TabBarTabListPopupButton() [Internal] +------------------------------------------------------------------------------- function ImGui.TabBarFindByID(id) SyncContext() return GImGui.TabBars:GetByKey(id) end +-- Remove TabBar data (currently only used by TestEngine) function ImGui.TabBarRemove(tab_bar) SyncContext() GImGui.TabBars:Remove(tab_bar.ID, tab_bar) @@ -50146,6 +56681,7 @@ function ImGui.BeginTabBar(str_id, flags) tab_bar.ID = id tab_bar.SeparatorMinX = tab_bar_bb.Min.x - IM_TRUNC(window.WindowPadding.x * 0.5) tab_bar.SeparatorMaxX = tab_bar_bb.Max.x + IM_TRUNC(window.WindowPadding.x * 0.5) + -- if (g.NavWindow and ImGui.IsWindowChildOf(g.NavWindow, window, false, false)) flags = bit32.bor(flags, ImGuiTabBarFlags.IsFocused) return ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) end @@ -50157,14 +56693,16 @@ function ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) if window.SkipItems then return false end IM_ASSERT(tab_bar.ID ~= 0) - if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then + if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then -- Already done ImGui.PushOverrideID(tab_bar.ID) end + -- Add to stack g.CurrentTabBarStack:push_back(tab_bar) g.CurrentTabBar = tab_bar tab_bar.Window = window + -- Append with multiple BeginTabBar()/EndTabBar() pairs. ImVec2_Copy(tab_bar.BackupCursorPos, window.DC.CursorPos) if tab_bar.CurrFrameVisible == g.FrameCount then ImVec2_CopyV(window.DC.CursorPos, tab_bar.BarRect.Min.x, tab_bar.BarRect.Max.y + tab_bar.ItemSpacingY) @@ -50172,21 +56710,23 @@ function ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) return true end + -- Ensure correct ordering when toggling ImGuiTabBarFlags.Reorderable flag, or when a new tab was added while being not reorderable if bit32.band(flags, ImGuiTabBarFlags.Reorderable) ~= bit32.band(tab_bar.Flags, ImGuiTabBarFlags.Reorderable) or (tab_bar.TabsAddedNew and bit32.band(flags, ImGuiTabBarFlags.Reorderable) == 0) then - if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then + if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then -- FIXME: TabBar with DockNode can now be hybrid SortTabsByBeginOrder(tab_bar) end end tab_bar.TabsAddedNew = false + -- Flags if bit32.band(flags, ImGuiTabBarFlags.FittingPolicyMask_) == 0 then flags = bit32.bor(flags, ImGuiTabBarFlags.FittingPolicyDefault_) end tab_bar.Flags = flags tab_bar.BarRect = ImRect(tab_bar_bb.Min, tab_bar_bb.Max) - tab_bar.WantLayout = true + tab_bar.WantLayout = true -- Layout will be done on the first call to ItemTab() tab_bar.PrevFrameVisible = tab_bar.CurrFrameVisible tab_bar.CurrFrameVisible = g.FrameCount tab_bar.PrevTabsContentsHeight = tab_bar.CurrTabsContentsHeight @@ -50197,8 +56737,11 @@ function ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) tab_bar.LastTabItemIdx = -1 tab_bar.BeginCount = 1 + -- Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap ImVec2_CopyV(window.DC.CursorPos, tab_bar.BarRect.Min.x, tab_bar.BarRect.Max.y + tab_bar.ItemSpacingY) + -- Draw separator + -- (it would be misleading to draw this in EndTabBar() suggesting that it may be drawn over tabs, as tab bar are appendable) local col = ImGui.GetColorU32(bit32.band(flags, ImGuiTabBarFlags.IsFocused) ~= 0 and ImGuiCol.TabSelected or ImGuiCol.TabDimmedSelected) if g.Style.TabBarBorderSize > 0.0 then local y = tab_bar.BarRect.Max.y @@ -50216,8 +56759,10 @@ function ImGui.EndTabBar() local tab_bar = g.CurrentTabBar IM_ASSERT(tab_bar ~= nil, "Mismatched BeginTabBar()/EndTabBar()!") + -- Fallback in case no TabItem have been submitted if tab_bar.WantLayout then ImGui.TabBarLayout(tab_bar) end + -- Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). local tab_bar_appearing = (tab_bar.PrevFrameVisible + 1 < g.FrameCount) if tab_bar.VisibleTabWasSubmitted or tab_bar.VisibleTabId == 0 or tab_bar_appearing then tab_bar.CurrTabsContentsHeight = ImMax(window.DC.CursorPos.y - tab_bar.BarRect.Max.y, tab_bar.CurrTabsContentsHeight) @@ -50230,7 +56775,7 @@ function ImGui.EndTabBar() end tab_bar.LastTabItemIdx = -1 - if bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0 then + if bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0 then -- Already done ImGui.PopID() end @@ -50238,22 +56783,27 @@ function ImGui.EndTabBar() if g.CurrentTabBarStack.Size == 0 then g.CurrentTabBar = nil else g.CurrentTabBar = g.CurrentTabBarStack.Data[g.CurrentTabBarStack.Size] end end +-- This is called only once a frame before by the first call to ItemTab() +-- The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions. function ImGui.TabBarLayout(tab_bar) SyncContext() local g = GImGui tab_bar.WantLayout = false + -- Track selected tab when resizing our parent down local 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) local tabs = tab_bar.Tabs local tab_dst_n = 0 local need_sort_by_section = false - local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- 1-based: [1]=Leading,[2]=Central,[3]=Trailing + local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- Layout sections: Leading, Central, Trailing (1-based: [1]=Leading,[2]=Central,[3]=Trailing) for tab_src_n = 0, tabs.Size - 1 do local tab = tabs.Data[tab_src_n + 1] if tab.LastFrameVisible < tab_bar.PrevFrameVisible or tab.WantClose then + -- Remove tab if tab_bar.VisibleTabId == tab.ID then tab_bar.VisibleTabId = 0 end if tab_bar.SelectedTabId == tab.ID then tab_bar.SelectedTabId = 0 end if tab_bar.NextSelectedTabId == tab.ID then tab_bar.NextSelectedTabId = 0 end @@ -50261,6 +56811,7 @@ function ImGui.TabBarLayout(tab_bar) if tab_dst_n ~= tab_src_n then tabs.Data[tab_dst_n + 1] = tab end tab.IndexDuringLayout = tab_dst_n + -- We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another) local curr_tab_section_n = TabItemGetSectionIdx(tab) if tab_dst_n > 0 then local prev_tab = tabs.Data[tab_dst_n] @@ -50279,10 +56830,12 @@ function ImGui.TabBarLayout(tab_bar) if need_sort_by_section then SortTabsBySection(tab_bar) end + -- Calculate spacing between sections local tab_spacing = g.Style.ItemInnerSpacing.x sections[1].Spacing = (sections[1].TabCount > 0 and (sections[2].TabCount + sections[3].TabCount) > 0) and tab_spacing or 0.0 sections[2].Spacing = (sections[2].TabCount > 0 and sections[3].TabCount > 0) and tab_spacing or 0.0 + -- Setup next selected tab local scroll_to_tab_id = 0 if tab_bar.NextScrollToTabId ~= 0 then scroll_to_tab_id = tab_bar.NextScrollToTabId @@ -50294,6 +56847,7 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.SelectedTabId end + -- Process order change request (we could probably process it when requested but it's just saner to do it in a single spot). if tab_bar.ReorderRequestTabId ~= 0 then if ImGui.TabBarProcessReorder(tab_bar) then if tab_bar.ReorderRequestTabId == tab_bar.SelectedTabId then @@ -50303,23 +56857,28 @@ function ImGui.TabBarLayout(tab_bar) tab_bar.ReorderRequestTabId = 0 end + -- Tab List Popup (will alter tab_bar.BarRect and therefore the available width!) local tab_list_popup_button = bit32.band(tab_bar.Flags, ImGuiTabBarFlags.TabListPopupButton) ~= 0 if tab_list_popup_button then - local tab_to_select = ImGui.TabBarTabListPopupButton(tab_bar) + local tab_to_select = ImGui.TabBarTabListPopupButton(tab_bar) -- NB: Will alter BarRect.Min.x! if tab_to_select then tab_bar.SelectedTabId = tab_to_select.ID scroll_to_tab_id = tab_to_select.ID end end - -- shrink buffer layout: leading, trailing, central (0-based offsets) + -- Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central + -- (whereas our tabs are stored as: leading, central, trailing) + -- (shrink_buffer_indexes holds 0-based offsets) local shrink_buffer_indexes = { 0, sections[1].TabCount + sections[3].TabCount, sections[1].TabCount } local swb = g.ShrinkWidthBuffer swb:resize(tabs.Size) for i = 1, tabs.Size do if swb.Data[i] == nil then swb.Data[i] = ImGuiShrinkWidthItem() end end + -- Minimum shrink width local shrink_min_width = (bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyMixed) ~= 0) and g.Style.TabMinWidthShrink or 1.0 + -- Compute ideal tabs widths + store them into shrink buffer local most_recently_selected_tab = nil local curr_section_n = -1 local found_selected_tab_id = false @@ -50333,6 +56892,9 @@ function ImGui.TabBarLayout(tab_bar) if tab.ID == tab_bar.SelectedTabId then found_selected_tab_id = true end if scroll_to_tab_id == 0 and g.NavJustMovedToId == tab.ID then scroll_to_tab_id = tab.ID end + -- Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar. + -- Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet, + -- and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window. local tab_name = ImGui.TabBarGetTabName(tab_bar, tab) local has_close_button_or_unsaved_marker = bit32.band(tab.Flags, ImGuiTabItemFlags.NoCloseButton) == 0 or bit32.band(tab.Flags, ImGuiTabItemFlags.UnsavedDocument) ~= 0 tab.ContentWidth = (tab.RequestedWidth >= 0.0) and tab.RequestedWidth or ImGui.TabItemCalcSize(tab_name, has_close_button_or_unsaved_marker).x @@ -50346,6 +56908,7 @@ function ImGui.TabBarLayout(tab_bar) section.WidthAfterShrinkMinWidth = section.WidthAfterShrinkMinWidth + ImMin(tab.ContentWidth, shrink_min_width) + ((section_n == curr_section_n) and tab_spacing or 0.0) curr_section_n = section_n + -- Store data so we can build an array sorted by width if we need to shrink tabs down local item = swb.Data[shrink_buffer_indexes[section_n + 1] + 1] shrink_buffer_indexes[section_n + 1] = shrink_buffer_indexes[section_n + 1] + 1 item.Index = tab_n @@ -50354,6 +56917,7 @@ function ImGui.TabBarLayout(tab_bar) tab.Width = ImMax(tab.ContentWidth, 1.0) end + -- Compute total ideal width (used for e.g. auto-resizing a window) local width_all_tabs_after_min_width_shrink = 0.0 tab_bar.WidthAllTabsIdeal = 0.0 for section_n = 1, 3 do @@ -50361,6 +56925,9 @@ function ImGui.TabBarLayout(tab_bar) width_all_tabs_after_min_width_shrink = width_all_tabs_after_min_width_shrink + sections[section_n].WidthAfterShrinkMinWidth + sections[section_n].Spacing end + -- Horizontal scrolling buttons + -- - Important: note that TabBarScrollButtons() will alter BarRect.Max.x. + -- - Selection skips buttons and might cross through sections if there are Tabs in Leading/Trailing sections. local can_scroll = bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyScroll) ~= 0 or bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyMixed) ~= 0 local width_all_tabs_to_use_for_scroll = (bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyScroll) ~= 0) and tab_bar.WidthAllTabs or width_all_tabs_after_min_width_shrink tab_bar.ScrollButtonEnabled = (width_all_tabs_to_use_for_scroll > tab_bar.BarRect:GetWidth() and tabs.Size > 1) @@ -50378,23 +56945,26 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.SelectedTabId end + -- Shrink widths if full tabs don't fit in their allocated space local section_0_w = sections[1].Width + sections[1].Spacing local section_1_w = sections[2].Width + sections[2].Spacing local section_2_w = sections[3].Width + sections[3].Spacing local central_section_is_visible = (section_0_w + section_2_w) < tab_bar.BarRect:GetWidth() local width_excess if central_section_is_visible then - width_excess = ImMax(section_1_w - (tab_bar.BarRect:GetWidth() - section_0_w - section_2_w), 0.0) + width_excess = ImMax(section_1_w - (tab_bar.BarRect:GetWidth() - section_0_w - section_2_w), 0.0) -- Excess used to shrink central section else - width_excess = (section_0_w + section_2_w) - tab_bar.BarRect:GetWidth() + width_excess = (section_0_w + section_2_w) - tab_bar.BarRect:GetWidth() -- Excess used to shrink leading/trailing section end + -- With ImGuiTabBarFlags.FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore local can_shrink = bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyShrink) ~= 0 or bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyMixed) ~= 0 if width_excess >= 1.0 and (can_shrink or not central_section_is_visible) then local shrink_data_count = central_section_is_visible and sections[2].TabCount or (sections[1].TabCount + sections[3].TabCount) local shrink_data_offset = central_section_is_visible and (sections[1].TabCount + sections[3].TabCount) or 0 ImGui.ShrinkWidths(swb.Data, shrink_data_offset + 1, shrink_data_count, width_excess, shrink_min_width) + -- Apply shrunk values into tabs and sections for tab_n = shrink_data_offset, shrink_data_offset + shrink_data_count - 1 do local item = swb.Data[tab_n + 1] local tab = tabs.Data[item.Index + 1] @@ -50428,6 +56998,7 @@ function ImGui.TabBarLayout(tab_bar) section_tab_index = section_tab_index + section.TabCount end + -- If we have lost the selected tab, select the next most recently active one local tab_bar_appearing = (tab_bar.PrevFrameVisible + 1 < g.FrameCount) if found_selected_tab_id == false and not tab_bar_appearing then tab_bar.SelectedTabId = 0 @@ -50437,6 +57008,7 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.SelectedTabId end + -- Lock in visible tab tab_bar.VisibleTabId = tab_bar.SelectedTabId tab_bar.VisibleTabWasSubmitted = false @@ -50446,6 +57018,7 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.VisibleTabId end + -- Apply request requests if scroll_to_tab_id ~= 0 then ImGui.TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections) elseif tab_bar.ScrollButtonEnabled and ImGui.IsMouseHoveringRect(tab_bar.BarRect.Min, tab_bar.BarRect.Max, true) and ImGui.IsWindowContentHoverable(g.CurrentWindow) then @@ -50459,9 +57032,12 @@ function ImGui.TabBarLayout(tab_bar) ImGui.SetKeyOwner(wheel_key, tab_bar.ID) end + -- Update scrolling tab_bar.ScrollingAnim = ImGui.TabBarScrollClamp(tab_bar, tab_bar.ScrollingAnim) tab_bar.ScrollingTarget = ImGui.TabBarScrollClamp(tab_bar, tab_bar.ScrollingTarget) if tab_bar.ScrollingAnim ~= tab_bar.ScrollingTarget then + -- Scrolling speed adjust itself so we can always reach our target in 1/3 seconds. + -- Teleport if we are aiming far off the visible line tab_bar.ScrollingSpeed = ImMax(tab_bar.ScrollingSpeed, 70.0 * g.FontSize) tab_bar.ScrollingSpeed = ImMax(tab_bar.ScrollingSpeed, math.abs(tab_bar.ScrollingTarget - tab_bar.ScrollingAnim) / 0.3) local teleport = (tab_bar.PrevFrameVisible + 1 < g.FrameCount) or (tab_bar.ScrollingTargetDistToVisibility > 10.0 * g.FontSize) @@ -50472,12 +57048,14 @@ function ImGui.TabBarLayout(tab_bar) tab_bar.ScrollingRectMinX = tab_bar.BarRect.Min.x + sections[1].Width + sections[1].Spacing tab_bar.ScrollingRectMaxX = tab_bar.BarRect.Max.x - sections[3].Width - sections[2].Spacing + -- Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame) local window = g.CurrentWindow ImVec2_Copy(window.DC.CursorPos, tab_bar.BarRect.Min) ImGui.ItemSize(ImVec2(tab_bar.WidthAllTabs, tab_bar.BarRect:GetHeight()), tab_bar.FramePadding.y) window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, tab_bar.BarRect.Min.x + tab_bar.WidthAllTabsIdeal) end +-- Dockable windows uses Name/ID in the global namespace. Non-dockable items use the ID stack. function ImGui.TabBarCalcTabID(tab_bar, label, docked_window) if docked_window ~= nil then IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) ~= 0) @@ -50502,6 +57080,7 @@ function ImGui.TabBarFindTabByID(tab_bar, tab_id) return nil end +-- Order = visible order, not submission order! (which is tab.BeginOrder) --- @param order int # 0-based visible order function ImGui.TabBarFindTabByOrder(tab_bar, order) if order < 0 or order >= tab_bar.Tabs.Size then return nil end @@ -50514,6 +57093,7 @@ function ImGui.TabBarGetTabOrder(tab_bar, tab) return i and (i - 1) or -1 end +-- FIXME: See references to #2304 in TODO.txt function ImGui.TabBarFindMostRecentlySelectedTabForActiveWindow(tab_bar) local most_recently_selected_tab = nil for n = 1, tab_bar.Tabs.Size do @@ -50543,22 +57123,25 @@ function ImGui.TabBarGetTabPos(tab_bar, tab) return tab_bar.BarRect.Min + ImVec2(tab.Offset, 0.0) end +-- The purpose of this call is to register tab in advance so we can control their order at the time they appear. +-- Otherwise calling this is unnecessary as tabs are appending as needed by the BeginTabItem() function. function ImGui.TabBarAddTab(tab_bar, tab_flags, window) local g = ImGui.GetCurrentContext() IM_ASSERT(ImGui.TabBarFindTabByID(tab_bar, window.TabId) == nil) - IM_ASSERT(g.CurrentTabBar ~= tab_bar) + IM_ASSERT(g.CurrentTabBar ~= tab_bar) -- Can't work while the tab bar is active as our tab doesn't have an X offset yet, in theory we could/should test something like (tab_bar.CurrFrameVisible < g.FrameCount) but we'd need to solve why triggers the commented early-out assert in BeginTabBarEx() (probably dock node going from implicit to explicit in same frame) if not window.HasCloseButton then - tab_flags = bit32.bor(tab_flags, ImGuiTabItemFlags.NoCloseButton) + tab_flags = bit32.bor(tab_flags, ImGuiTabItemFlags.NoCloseButton) -- Set _NoCloseButton immediately because it will be used for first-frame width calculation. end local new_tab = ImGuiTabItem() new_tab.ID = window.TabId new_tab.Flags = tab_flags - new_tab.LastFrameVisible = tab_bar.CurrFrameVisible + new_tab.LastFrameVisible = tab_bar.CurrFrameVisible -- Required so BeginTabBar() doesn't ditch the tab if new_tab.LastFrameVisible == -1 then new_tab.LastFrameVisible = g.FrameCount - 1 end - new_tab.Window = window + new_tab.Window = window -- Required so tab bar layout can compute the tab width before tab submission tab_bar.Tabs:push_back(new_tab) end +-- The *TabId fields are already set by the docking system _before_ the actual TabItem was created, so we clear them regardless. function ImGui.TabBarRemoveTab(tab_bar, tab_id) local tab = ImGui.TabBarFindTabByID(tab_bar, tab_id) if tab then tab_bar.Tabs:erase(tab_bar.Tabs:find_index(tab)) end @@ -50567,9 +57150,13 @@ function ImGui.TabBarRemoveTab(tab_bar, tab_id) if tab_bar.NextSelectedTabId == tab_id then tab_bar.NextSelectedTabId = 0 end end +-- Called on manual closure attempt function ImGui.TabBarCloseTab(tab_bar, tab) - if bit32.band(tab.Flags, ImGuiTabItemFlags.Button) ~= 0 then return end + if bit32.band(tab.Flags, ImGuiTabItemFlags.Button) ~= 0 then return end -- A button appended with TabItemButton(). + if bit32.band(tab.Flags, bit32.bor(ImGuiTabItemFlags.UnsavedDocument, ImGuiTabItemFlags.NoAssumedClosure)) == 0 then + -- This will remove a frame of lag for selecting another tab on closure. + -- However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure tab.WantClose = true if tab_bar.VisibleTabId == tab.ID then tab.LastFrameVisible = -1 @@ -50577,6 +57164,7 @@ function ImGui.TabBarCloseTab(tab_bar, tab) tab_bar.NextSelectedTabId = 0 end else + -- Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup) if tab_bar.VisibleTabId ~= tab.ID then ImGui.TabBarQueueFocus(tab_bar, tab) end end end @@ -50586,10 +57174,13 @@ function ImGui.TabBarScrollClamp(tab_bar, scrolling) return ImMax(scrolling, 0.0) end +-- Note: we may scroll to tab that are not selected! e.g. using keyboard arrow keys function ImGui.TabBarScrollToTab(tab_bar, tab_id, sections) local tab = ImGui.TabBarFindTabByID(tab_bar, tab_id) if tab == nil then return end + -- Clamp attempt to scroll to leading/trailing sections items. + -- This could be done at the TabBarScrollingButtons() call site as well, but here works. if bit32.band(tab.Flags, ImGuiTabItemFlags.Leading) ~= 0 then tab = tab_bar.Tabs.Data[sections[1].TabCount + 1] elseif bit32.band(tab.Flags, ImGuiTabItemFlags.Trailing) ~= 0 then @@ -50597,18 +57188,25 @@ function ImGui.TabBarScrollToTab(tab_bar, tab_id, sections) end if tab == nil or bit32.band(tab.Flags, ImGuiTabItemFlags.SectionMask_) ~= 0 then return end + -- When scrolling to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) + -- Disable the margin if the scrolling section is too small for the target tab: prefer displaying a maximum of the label. local g = ImGui.GetCurrentContext() local margin = ImClamp(tab_bar.ScrollingRectMaxX - tab_bar.ScrollingRectMinX - tab.Width, g.Style.ItemInnerSpacing.x, g.FontSize * 1.0) local order = ImGui.TabBarGetTabOrder(tab_bar, tab) + + -- Scrolling happens only in the central section (leading/trailing sections are not scrolling) local scrollable_width = TabBarCalcScrollableWidth(tab_bar, sections) + -- We make all tabs positions all relative Sections[0].Width to make code simpler local tab_x1 = tab.Offset - sections[1].Width + ((order > sections[1].TabCount - 1) and -margin or 0.0) local tab_x2 = tab.Offset - sections[1].Width + tab.Width + ((order + 1 < tab_bar.Tabs.Size - sections[3].TabCount) and margin or 1.0) tab_bar.ScrollingTargetDistToVisibility = 0.0 if tab_bar.ScrollingTarget > tab_x1 or (tab_x2 - tab_x1 >= scrollable_width) then + -- Scroll to the left tab_bar.ScrollingTargetDistToVisibility = ImMax(tab_bar.ScrollingAnim - tab_x2, 0.0) tab_bar.ScrollingTarget = tab_x1 elseif tab_bar.ScrollingTarget < tab_x2 - scrollable_width then + -- Scroll to the right tab_bar.ScrollingTargetDistToVisibility = ImMax((tab_x1 - scrollable_width) - tab_bar.ScrollingAnim, 0.0) tab_bar.ScrollingTarget = tab_x2 - scrollable_width end @@ -50617,7 +57215,7 @@ end --- TabBarQueueFocus(tab_bar, tab) or TabBarQueueFocus(tab_bar, tab_name) function ImGui.TabBarQueueFocus(tab_bar, tab) if type(tab) == "string" then - IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0) + IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0) -- Only supported for manual/explicit tab bars tab_bar.NextSelectedTabId = ImGui.TabBarCalcTabID(tab_bar, tab, nil) return end @@ -50640,17 +57238,22 @@ function ImGui.TabBarQueueReorderFromMousePos(tab_bar, src_tab, mouse_pos) local is_central_section = bit32.band(src_tab.Flags, ImGuiTabItemFlags.SectionMask_) == 0 local bar_offset = tab_bar.BarRect.Min.x - (is_central_section and tab_bar.ScrollingTarget or 0) + -- Count number of contiguous tabs we are crossing over local dir = ((bar_offset + src_tab.Offset) > mouse_pos.x) and -1 or 1 local src_idx = ImGui.TabBarGetTabOrder(tab_bar, src_tab) local dst_idx = src_idx local i = src_idx while i >= 0 and i < tab_bar.Tabs.Size do + -- Reordered tabs must share the same section local dst_tab = tab_bar.Tabs.Data[i + 1] if bit32.band(dst_tab.Flags, ImGuiTabItemFlags.NoReorder) ~= 0 then break end if bit32.band(dst_tab.Flags, ImGuiTabItemFlags.SectionMask_) ~= bit32.band(src_tab.Flags, ImGuiTabItemFlags.SectionMask_) then break end dst_idx = i + + -- Include spacing after tab, so when mouse cursor is between tabs we would not continue checking further tabs that are not hovered. local x1 = bar_offset + dst_tab.Offset - tab_spacing local x2 = bar_offset + dst_tab.Offset + dst_tab.Width + tab_spacing + -- ImGui.GetForegroundDrawList():AddRect(ImVec2(x1, tab_bar.BarRect.Min.y), ImVec2(x2, tab_bar.BarRect.Max.y), IM_COL32(255, 0, 0, 255)) if (dir < 0 and mouse_pos.x > x1) or (dir > 0 and mouse_pos.x < x2) then break end i = i + dir end @@ -50664,10 +57267,13 @@ function ImGui.TabBarProcessReorder(tab_bar) local tab1 = ImGui.TabBarFindTabByID(tab_bar, tab_bar.ReorderRequestTabId) if tab1 == nil or bit32.band(tab1.Flags, ImGuiTabItemFlags.NoReorder) ~= 0 then return false end + -- IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.Reorderable) ~= 0) -- <- this may happen when using debug tools local tab1_order = ImGui.TabBarGetTabOrder(tab_bar, tab1) local tab2_order = tab1_order + tab_bar.ReorderRequestOffset if tab2_order < 0 or tab2_order >= tab_bar.Tabs.Size then return false end + -- Reordered tabs must share the same section + -- (Note: TabBarQueueReorderFromMousePos() also has a similar test but since we allow direct calls to TabBarQueueReorder() we do it here too) local tab2 = tab_bar.Tabs.Data[tab2_order + 1] if bit32.band(tab2.Flags, ImGuiTabItemFlags.NoReorder) ~= 0 then return false end if bit32.band(tab1.Flags, ImGuiTabItemFlags.SectionMask_) ~= bit32.band(tab2.Flags, ImGuiTabItemFlags.SectionMask_) then return false end @@ -50688,6 +57294,7 @@ function ImGui.TabBarScrollingButtons(tab_bar) local scrolling_buttons_width = arrow_button_size.x * 2.0 local backup_cursor_pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y) + -- window.DrawList:AddRect(ImVec2(tab_bar.BarRect.Max.x - scrolling_buttons_width, tab_bar.BarRect.Min.y), ImVec2(tab_bar.BarRect.Max.x, tab_bar.BarRect.Max.y), IM_COL32(255,0,0,255)) local select_dir = 0 local tc = g.Style.Colors[ImGuiCol.Text] @@ -50716,9 +57323,15 @@ function ImGui.TabBarScrollingButtons(tab_bar) if tab_item then local selected_order = ImGui.TabBarGetTabOrder(tab_bar, tab_item) local target_order = selected_order + select_dir + + -- Skip tab item buttons until another tab item is found or end is reached while tab_to_scroll_to == nil do + -- If we are at the end of the list, still scroll to make our tab visible local idx = (target_order >= 0 and target_order < tab_bar.Tabs.Size) and target_order or selected_order tab_to_scroll_to = tab_bar.Tabs.Data[idx + 1] + + -- Cross through buttons + -- (even if first/last item is a button, return it so we can update the scroll) if bit32.band(tab_to_scroll_to.Flags, ImGuiTabItemFlags.Button) ~= 0 then target_order = target_order + select_dir selected_order = selected_order + select_dir @@ -50737,6 +57350,7 @@ function ImGui.TabBarTabListPopupButton(tab_bar) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow + -- We use g.Style.FramePadding.y to match the square ArrowButton size local tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y local backup_cursor_pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y) ImVec2_CopyV(window.DC.CursorPos, tab_bar.BarRect.Min.x - g.Style.FramePadding.y, tab_bar.BarRect.Min.y) @@ -50766,9 +57380,18 @@ function ImGui.TabBarTabListPopupButton(tab_bar) return tab_to_select end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Widgets: BeginTabItem, EndTabItem, etc. ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - BeginTabItem() +-- - EndTabItem() +-- - TabItemButton() +-- - TabItemEx() [Internal] +-- - SetTabItemClosed() +-- - TabItemCalcSize() [Internal] +-- - TabItemBackground() [Internal] +-- - TabItemLabelAndCloseButton() [Internal] +------------------------------------------------------------------------------- --- @return bool visible, bool? p_open function ImGui.BeginTabItem(label, p_open, flags) @@ -50779,13 +57402,13 @@ function ImGui.BeginTabItem(label, p_open, flags) local tab_bar = g.CurrentTabBar IM_ASSERT(tab_bar ~= nil, "Needs to be called between BeginTabBar() and EndTabBar()!") - IM_ASSERT(bit32.band(flags, ImGuiTabItemFlags.Button) == 0) + IM_ASSERT(bit32.band(flags, ImGuiTabItemFlags.Button) == 0) -- BeginTabItem() Can't be used with button flags, use TabItemButton() instead! local ret ret, p_open = ImGui.TabItemEx(tab_bar, label, p_open, flags, nil) if ret and bit32.band(flags, ImGuiTabItemFlags.NoPushId) == 0 then local tab = tab_bar.Tabs.Data[tab_bar.LastTabItemIdx + 1] - ImGui.PushOverrideID(tab.ID) + ImGui.PushOverrideID(tab.ID) -- We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label) end return ret, p_open end @@ -50826,6 +57449,7 @@ end --- @return bool ret, bool? p_open function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) + -- Layout whole tab bar if not already done local g = ImGui.GetCurrentContext() if tab_bar.WantLayout then local backup_next_item_data = {} @@ -50839,14 +57463,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) local style = g.Style local id = ImGui.TabBarCalcTabID(tab_bar, label, docked_window) + -- If the user called us with p_open == false, we early out and don't render. + -- We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. if p_open ~= nil and not p_open then ImGui.ItemAdd(ImRect(), id, nil, ImGuiItemFlags.NoNav) return false, p_open end IM_ASSERT(p_open == nil or bit32.band(flags, ImGuiTabItemFlags.Button) == 0) - IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) ~= bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) + IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) ~= bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) -- Can't use both Leading and Trailing + -- Store into ImGuiTabItemFlags.NoCloseButton, also honor ImGuiTabItemFlags.NoCloseButton passed by user (although not documented) local has_p_open = (p_open ~= nil) if bit32.band(flags, ImGuiTabItemFlags.NoCloseButton) ~= 0 then has_p_open = false @@ -50854,6 +57481,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) flags = bit32.bor(flags, ImGuiTabItemFlags.NoCloseButton) end + -- Acquire tab data local tab = ImGui.TabBarFindTabByID(tab_bar, id) local tab_is_new = false if tab == nil then @@ -50865,6 +57493,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end tab_bar.LastTabItemIdx = ImGui.TabBarGetTabOrder(tab_bar, tab) + -- Calculate tab contents size local size = ImGui.TabItemCalcSize(label, has_p_open or bit32.band(flags, ImGuiTabItemFlags.UnsavedDocument) ~= 0) tab.RequestedWidth = -1.0 if bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasWidth) ~= 0 then @@ -50885,6 +57514,8 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) tab.Flags = flags tab.Window = docked_window + -- Append name (port: stored on tab.Name) + -- (regular tabs are permitted in a DockNode tab bar, but window tabs not permitted in a non-DockNode tab bar) if docked_window ~= nil then IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) ~= 0) tab.NameOffset = -1 @@ -50894,26 +57525,32 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) tab.Name = label end + -- Update selected tab if not is_tab_button then if tab_appearing and bit32.band(tab_bar.Flags, ImGuiTabBarFlags.AutoSelectNewTabs) ~= 0 and tab_bar.NextSelectedTabId == 0 then if not tab_bar_appearing or tab_bar.SelectedTabId == 0 then - ImGui.TabBarQueueFocus(tab_bar, tab) + ImGui.TabBarQueueFocus(tab_bar, tab) -- New tabs gets activated end end - if bit32.band(flags, ImGuiTabItemFlags.SetSelected) ~= 0 and tab_bar.SelectedTabId ~= id then + if bit32.band(flags, ImGuiTabItemFlags.SetSelected) ~= 0 and tab_bar.SelectedTabId ~= id then -- _SetSelected can only be passed on explicit tab bar ImGui.TabBarQueueFocus(tab_bar, tab) end end + -- Lock visibility + -- (Note: tab_contents_visible ~= tab_selected... because Ctrl+Tab operations may preview some tabs without selecting them!) local tab_contents_visible = (tab_bar.VisibleTabId == id) if tab_contents_visible then tab_bar.VisibleTabWasSubmitted = true end + -- On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches if not tab_contents_visible and tab_bar.SelectedTabId == 0 and tab_bar_appearing and docked_window == nil then if tab_bar.Tabs.Size == 1 and bit32.band(tab_bar.Flags, ImGuiTabBarFlags.AutoSelectNewTabs) == 0 then tab_contents_visible = true end end + -- Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted + -- and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. if tab_appearing and (not tab_bar_appearing or tab_is_new) then ImGui.ItemAdd(ImRect(), id, nil, ImGuiItemFlags.NoNav) if is_tab_button then return false, p_open end @@ -50922,14 +57559,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) if tab_bar.SelectedTabId == id then tab.LastFrameSelected = g.FrameCount end + -- Backup current layout position local backup_main_cursor_pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y) + -- Layout local is_central_section = bit32.band(tab.Flags, ImGuiTabItemFlags.SectionMask_) == 0 size.x = tab.Width local pos = ImGui.TabBarGetTabPos(tab_bar, tab) ImVec2_Copy(window.DC.CursorPos, pos) local bb = ImRect(pos, pos + size) + -- We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) local want_clip_rect = is_central_section and (bb.Min.x < tab_bar.ScrollingRectMinX or bb.Max.x > tab_bar.ScrollingRectMaxX) if want_clip_rect then ImGui.PushClipRect(ImVec2(ImClamp(bb.Min.x, tab_bar.ScrollingRectMinX, tab_bar.ScrollingRectMaxX), bb.Min.y - 1), ImVec2(tab_bar.ScrollingRectMaxX, bb.Max.y), true) @@ -50945,8 +57585,9 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) return tab_contents_visible, p_open end + -- Click to Select a tab local button_flags = bit32.bor(is_tab_button and ImGuiButtonFlags.PressedOnClickRelease or ImGuiButtonFlags.PressedOnClick, ImGuiButtonFlags.AllowOverlap) - if g.DragDropActive and not ImGuiPayload_IsDataType(g.DragDropPayload, IMGUI_PAYLOAD_TYPE_WINDOW) then + if g.DragDropActive and not ImGuiPayload_IsDataType(g.DragDropPayload, IMGUI_PAYLOAD_TYPE_WINDOW) then -- FIXME: May be an opt-in property of the payload to disable this button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnDragDropHold) end local hovered, held, pressed @@ -50957,18 +57598,24 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end if pressed and not is_tab_button then ImGui.TabBarQueueFocus(tab_bar, tab) end + -- Transfer active id window so the active id is not owned by the dock host (as StartMouseMovingWindow() + -- will only do it on the drag). This allows FocusWindow() to be more conservative in how it clears active id. if held and docked_window and g.ActiveId == id and g.ActiveIdIsJustActivated then g.ActiveIdWindow = docked_window end + -- Drag and drop a single floating window node moves it local node = docked_window and docked_window.DockNode or nil local single_floating_window_node = node and node:IsFloatingNode() and (node.Windows.Size == 1) if held and single_floating_window_node and ImGui.IsMouseDragging(0, 0.0) then + -- Move ImGui.StartMouseMovingWindow(docked_window) elseif held and not tab_appearing and ImGui.IsMouseDragging(0) then + -- Drag and drop: re-order tabs local drag_dir = 0 local drag_distance_from_edge_x = 0.0 if not g.DragDropActive and (bit32.band(tab_bar.Flags, ImGuiTabBarFlags.Reorderable) ~= 0 or docked_window ~= nil) then + -- While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x if g.IO.MouseDelta.x < 0.0 and g.IO.MousePos.x < bb.Min.x then drag_dir = -1 drag_distance_from_edge_x = bb.Min.x - g.IO.MousePos.x @@ -50980,13 +57627,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end end + -- Extract a Dockable window out of it's tab bar local can_undock = docked_window ~= nil and bit32.band(docked_window.Flags, ImGuiWindowFlags.NoMove) == 0 and bit32.band(node.MergedFlags, ImGuiDockNodeFlags.NoUndocking) == 0 if can_undock then + -- We use a variable threshold to distinguish dragging tabs within a tab bar and extracting them out of the tab bar local undocking_tab = (g.DragDropActive and g.DragDropPayload.SourceId == id) - if not undocking_tab then + if not undocking_tab then -- and (not g.IO.ConfigDockingWithShift or g.IO.KeyShift) local threshold_base = g.FontSize local threshold_x = threshold_base * 2.2 local threshold_y = (threshold_base * 1.5) + ImClamp((math.abs(g.IO.MouseDragMaxDistanceAbs[0].x) - threshold_base * 2.0) * 0.20, 0.0, threshold_base * 4.0) + -- ImGui.GetForegroundDrawList():AddRect(ImVec2(bb.Min.x - threshold_x, bb.Min.y - threshold_y), ImVec2(bb.Max.x + threshold_x, bb.Max.y + threshold_y), IM_COL32_WHITE) -- [DEBUG] + local distance_from_edge_y = ImMax(bb.Min.y - g.IO.MousePos.y, g.IO.MousePos.y - bb.Max.y) if distance_from_edge_y >= threshold_y then undocking_tab = true end if drag_distance_from_edge_x > threshold_x then @@ -50997,6 +57648,8 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end if undocking_tab then + -- Undock + -- FIXME: refactor to share more code with e.g. StartMouseMovingWindow ImGui.DockContextQueueUndockWindow(g, docked_window) g.MovingWindow = docked_window ImGui.SetActiveID(g.MovingWindow.MoveId, g.MovingWindow) @@ -51007,6 +57660,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end end + -- Render tab shape local is_visible = bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 and bit32.band(flags, ImGuiTabItemFlags.Invisible) == 0 if is_visible then local display_draw_list = window.DrawList @@ -51016,6 +57670,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) else col_idx = tab_bar_focused and ImGuiCol.Tab or ImGuiCol.TabDimmed end ImGui.TabItemBackground(display_draw_list, bb, flags, ImGui.GetColorU32(col_idx)) if tab_contents_visible and bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DrawSelectedOverline) ~= 0 and style.TabBarOverlineSize > 0.0 then + -- Might be moved to TabItemBackground() ? local tl = ImVec2(bb.Min.x, bb.Min.y + style.TabBarOverlineSize * 0.5) local tr = ImVec2(bb.Max.x, bb.Min.y + style.TabBarOverlineSize * 0.5) local overline_col = ImGui.GetColorU32(tab_bar_focused and ImGuiCol.TabSelectedOverline or ImGuiCol.TabDimmedSelectedOverline) @@ -51030,6 +57685,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end ImGui.RenderNavCursor(bb, id) + -- Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. local hovered_unblocked = ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByPopup) if tab_bar.SelectedTabId ~= tab.ID and hovered_unblocked and (ImGui.IsMouseClicked(1) or ImGui.IsMouseReleased(1)) and not is_tab_button then ImGui.TabBarQueueFocus(tab_bar, tab) @@ -51039,6 +57695,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) flags = bit32.bor(flags, ImGuiTabItemFlags.NoCloseWithMiddleMouseButton) end + -- Render tab label, process close button local close_button_id = has_p_open and ImGui.GetIDWithSeed("#CLOSE", nil, docked_window and docked_window.ID or id) or 0 local label_flags = tab_just_unsaved and bit32.band(flags, bit32.bnot(ImGuiTabItemFlags.UnsavedDocument)) or flags local just_closed, text_clipped = ImGui.TabItemLabelAndCloseButton(display_draw_list, bb, label_flags, tab_bar.FramePadding, label, id, close_button_id, tab_contents_visible) @@ -51047,10 +57704,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) ImGui.TabBarCloseTab(tab_bar, tab) end + -- 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 and (hovered or g.HoveredId == close_button_id) then g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end + -- 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 and g.HoveredId == id and not held then if bit32.band(tab_bar.Flags, ImGuiTabBarFlags.NoTooltip) == 0 and bit32.band(tab.Flags, ImGuiTabItemFlags.NoTooltip) == 0 then local label_end = ImGui.FindRenderedTextEnd(label) @@ -51059,6 +57723,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end end + -- Restore main window position so user can draw there if want_clip_rect then ImGui.PopClipRect() end ImVec2_Copy(window.DC.CursorPos, backup_main_cursor_pos) @@ -51066,6 +57731,9 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) return tab_contents_visible, p_open end +-- [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. +-- To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar(). +-- Tabs closed by the close button will automatically be flagged to avoid this issue. function ImGui.SetTabItemClosed(label) local g = ImGui.GetCurrentContext() local is_within_manual_tab_bar = g.CurrentTabBar and bit32.band(g.CurrentTabBar.Flags, ImGuiTabBarFlags.DockNode) == 0 @@ -51073,7 +57741,7 @@ function ImGui.SetTabItemClosed(label) local tab_bar = g.CurrentTabBar local tab_id = ImGui.TabBarCalcTabID(tab_bar, label, nil) local tab = ImGui.TabBarFindTabByID(tab_bar, tab_id) - if tab then tab.WantClose = true end + if tab then tab.WantClose = true end -- Will be processed by next call to TabBarLayout() else local window = ImGui.FindWindowByName(label) if window and window.DockIsActive then @@ -51097,7 +57765,7 @@ function ImGui.TabItemCalcSize(label, has_close_button_or_unsaved_marker) local label_size = ImGui.CalcTextSize(label, nil, true) local size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0) if has_close_button_or_unsaved_marker then - size.x = size.x + g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize) + size.x = size.x + g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize) -- We use Y intentionally to fit the close button circle. else size.x = size.x + g.Style.FramePadding.x + 1.0 end @@ -51105,11 +57773,12 @@ function ImGui.TabItemCalcSize(label, has_close_button_or_unsaved_marker) end function ImGui.TabItemBackground(draw_list, bb, flags, col) + -- While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it. local g = ImGui.GetCurrentContext() local width = bb:GetWidth() IM_ASSERT(width > 0.0) local rounding = ImMax(0.0, ImMin(bit32.band(flags, ImGuiTabItemFlags.Button) ~= 0 and g.Style.FrameRounding or g.Style.TabRounding, width * 0.5 - 1.0)) - local y1 = bb.Min.y + 1.0 + local y1 = bb.Min.y + 1.0 -- Leave a bit of room in title bars. local y2 = bb.Max.y - g.Style.TabBarBorderSize draw_list:AddRectFilled(ImVec2(bb.Min.x, y1), ImVec2(bb.Max.x, y2), col, rounding, ImDrawFlags.RoundCornersTop) if g.Style.TabBorderSize > 0.0 then @@ -51121,6 +57790,8 @@ function ImGui.TabItemBackground(draw_list, bb, flags, col) end end +-- Render text label (with custom clipping) + Unsaved Document marker + Close Button logic +-- We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. --- @return bool just_closed, bool text_clipped function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, label, tab_id, close_button_id, is_contents_visible) local g = ImGui.GetCurrentContext() @@ -51129,15 +57800,24 @@ function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, l if bb:GetWidth() <= 1.0 then return false, false end + -- Render text label (with clipping + alpha gradient) + unsaved marker local text_ellipsis_clip_bb = ImRect(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 local 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.0, text_clipped and IM_COL32(255, 0, 0, 255) or IM_COL32(0, 255, 0, 255)) local button_sz = g.FontSize local button_pos = ImVec2(ImMax(bb.Min.x, bb.Max.x - frame_padding.x - button_sz), bb.Min.y + frame_padding.y) + -- Close Button & Unsaved Marker + -- We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap() + -- 'hovered' will be true when hovering the Tab but NOT when hovering the close button + -- 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button + -- 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false local close_button_pressed = false local close_button_visible = false - local is_hovered = g.HoveredId == tab_id or g.HoveredId == close_button_id or g.ActiveId == tab_id or g.ActiveId == close_button_id + local is_hovered = g.HoveredId == tab_id or g.HoveredId == close_button_id or g.ActiveId == tab_id or g.ActiveId == close_button_id -- Any interaction account for this too. if close_button_id ~= 0 then if is_contents_visible then @@ -51147,6 +57827,7 @@ function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, l end end + -- When tabs/document is unsaved, the unsaved marker takes priority over the close button. local unsaved_marker_visible = bit32.band(flags, ImGuiTabItemFlags.UnsavedDocument) ~= 0 and (button_pos.x + button_sz <= bb.Max.x) and (not close_button_visible or not is_hovered) if unsaved_marker_visible then local bullet_pos = button_pos + ImVec2(button_sz, button_sz) * 0.5 @@ -51157,11 +57838,15 @@ function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, l if ImGui.CloseButton(close_button_id, button_pos) then close_button_pressed = true end ImGuiLastItemData_Copy(g.LastItemData, last_item_backup) + -- Close with middle mouse button if is_hovered and bit32.band(flags, ImGuiTabItemFlags.NoCloseWithMiddleMouseButton) == 0 and ImGui.IsMouseClicked(2) then close_button_pressed = true end end + -- 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.. local ellipsis_max_x = text_ellipsis_clip_bb.Max.x if close_button_visible or unsaved_marker_visible then local visible_without_hover = unsaved_marker_visible or ((is_contents_visible and g.Style.TabCloseButtonMinWidthSelected or g.Style.TabCloseButtonMinWidthUnselected) < 0.0) @@ -51189,6 +57874,63 @@ __FILES['imstb_rectpack.lua'] = function() -- ALL TABLES IN THIS FILE ARE 1-BASED! -- Avoids table creation when possible +-- [DEAR IMGUI] +-- This is a slightly modified version of stb_rect_pack.h 1.01. +-- Grep for [DEAR IMGUI] to find the changes. +-- +-- stb_rect_pack.h - v1.01 - public domain - rectangle packing +-- Sean Barrett 2014 +-- +-- Useful for e.g. packing rectangular textures into an atlas. +-- Does not do rotation. +-- +-- Not necessarily the awesomest packing method, but better than +-- the totally naive one in stb_truetype (which is primarily what +-- this is meant to replace). +-- +-- Has only had a few tests run, may have issues. +-- +-- More docs to come. +-- +-- Uses table.sort and assert (STBRP_SORT and STBRP_ASSERT below). +-- +-- This library currently uses the Skyline Bottom-Left algorithm. +-- +-- Please note: better rectangle packers are welcome! Please +-- implement them to the same API, but with a different init +-- function. +-- +-- Credits +-- +-- Library +-- Sean Barrett +-- Minor features +-- Martins Mozeiko +-- github:IntellectualKitty +-- +-- Bugfixes / warning fixes +-- Jeremy Jaussaud +-- Fabian Giesen +-- +-- Version history: +-- +-- 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section +-- 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles +-- 0.99 (2019-02-07) warning fixes +-- 0.11 (2017-03-03) return packing success/fail result +-- 0.10 (2016-10-25) remove cast-away-const to avoid warnings +-- 0.09 (2016-08-27) fix compiler warnings +-- 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) +-- 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) +-- 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort +-- 0.05: added STBRP_ASSERT to allow replacing assert +-- 0.04: fixed minor bug in STBRP_LARGE_RECTS support +-- 0.01: initial release +-- +-- LICENSE +-- +-- See end of file for license information. + --- The `prev_link` can be stbrp_context or stbrp_node --- @diagnostic disable @@ -51198,7 +57940,13 @@ local STBRP_SORT = table.sort local STBRP_ASSERT = assert local STBRP__NOTUSED = function(_) end +------------------------------------------------------------------------------- +-- +-- INCLUDE SECTION +-- + local STBRP__MAXVAL = 0x7fffffff +-- Mostly for internal use, but this is the maximum supported coordinate value. --- @enum STBRP_HEURISTIC_Skyline local STBRP_HEURISTIC_Skyline = { @@ -51229,12 +57977,17 @@ local STBRP__PREV_LINK_TYPE = { --- @nodiscard local function stbrp_rect() return { + -- reserved for your use: id = 0, + + -- input: w = 0, h = 0, + + -- output: x = 0, y = 0, - was_packed = 0 + was_packed = 0 -- non-zero if valid packing } end @@ -51277,7 +58030,7 @@ local function stbrp_context() active_head = nil, free_head = nil, - extra = {stbrp_node(), stbrp_node()} + extra = {stbrp_node(), stbrp_node()} -- we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' } end @@ -51298,13 +58051,14 @@ local function stbrp__findresult() } end --------------------------- --------------------------- ---- ---- IMPLEMENTATION SECTION ---- ---- +------------------------------------------------------------------------------- +-- +-- IMPLEMENTATION SECTION +-- +-- Optionally select which packing heuristic the library should use. Different +-- heuristics will produce better/worse results for different data sets. +-- If you call init again, this will be reset to the default. --- @param context stbrp_context --- @param heuristic int local function stbrp_setup_heuristic(context, heuristic) @@ -51316,16 +58070,49 @@ local function stbrp_setup_heuristic(context, heuristic) end end +-- Optionally call this function after init but before doing any packing to +-- change the handling of the out-of-temp-memory scenario, described above. +-- If you call init again, this will be reset to the default (false). --- @param context stbrp_context --- @param allow_out_of_mem boolean local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem) if allow_out_of_mem then + -- if it's ok to run out of memory, then don't bother aligning them; + -- this gives better packing, but may fail due to OOM (even though + -- the rectangles easily fit). @TODO a smarter approach would be to only + -- quantize once we've hit OOM, then we could get rid of this parameter. context.align = 1 else + -- if it's not ok to run out of memory, then quantize the widths + -- so that num_nodes is always enough nodes. + -- + -- I.e. num_nodes * align >= width + -- align >= width / num_nodes + -- align = ceil(width/num_nodes) + context.align = (context.width + context.num_nodes - 1) / context.num_nodes end end +-- Initialize a rectangle packer to: +-- pack a rectangle that is 'width' by 'height' in dimensions +-- using temporary storage provided by the array 'nodes', which is 'num_nodes' long +-- +-- You must call this function every time you start packing into a new target. +-- +-- There is no "shutdown" function. The 'nodes' memory must stay valid for +-- the following stbrp_pack_rects() call (or calls), but can be freed after +-- the call (or calls) finish. +-- +-- Note: to guarantee best results, either: +-- 1. make sure 'num_nodes' >= 'width' +-- or 2. call stbrp_setup_allow_out_of_mem() defined above with 'allow_out_of_mem = true' +-- +-- If you don't do either of the above things, widths will be quantized to multiples +-- of small integers to guarantee the algorithm doesn't run out of temporary storage. +-- +-- If you do #2, then the non-quantized algorithm will be used, but the algorithm +-- may run out of temporary storage and be unable to pack some rectangles. --- @param context stbrp_context --- @param width int --- @param height int @@ -51345,6 +58132,7 @@ function stbrp_init_target(context, width, height, nodes, num_nodes) context.num_nodes = num_nodes stbrp_setup_allow_out_of_mem(context, false) + -- node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) context.extra[1].x = 0 context.extra[1].y = 0 context.extra[1].next = context.extra[2] @@ -51353,6 +58141,8 @@ function stbrp_init_target(context, width, height, nodes, num_nodes) context.extra[2].next = nil end +-- find minimum y position if it starts at x1 +-- Returns (min_y, waste_area) --- @param c stbrp_context --- @param first stbrp_node --- @param x0 int @@ -51366,7 +58156,7 @@ local function stbrp__skyline_find_min_y(c, first, x0, width) STBRP_ASSERT(first.x <= x0) - STBRP_ASSERT(node.next.x > x0) + STBRP_ASSERT(node.next.x > x0) -- we ended up handling this in the caller for efficiency STBRP_ASSERT(node.x <= x0) @@ -51375,14 +58165,19 @@ local function stbrp__skyline_find_min_y(c, first, x0, width) local visited_width = 0 while node.x < x1 do if node.y > min_y then + -- raise min_y higher. + -- we've accounted for all waste up to min_y, + -- but we'll now add more waste for everything we've visited waste_area = waste_area + visited_width * (node.y - min_y) min_y = node.y + -- the first time through, visited_width might be reduced if node.x < x0 then visited_width = visited_width + node.next.x - x0 else visited_width = visited_width + node.next.x - node.x end else + -- add waste area local under_width = node.next.x - node.x if under_width + visited_width > width then under_width = width - visited_width @@ -51408,10 +58203,12 @@ local function stbrp__skyline_find_best_pos(c, width, height) local best_prev_link = nil local best_prev_link_type = nil + -- align to multiple of c.align width = width + c.align - 1 width = width - width % c.align STBRP_ASSERT(width % c.align == 0) + -- if it can't possibly fit, bail immediately if width > c.width or height > c.height then fr.prev_link = nil fr.prev_link_type = nil @@ -51427,7 +58224,8 @@ local function stbrp__skyline_find_best_pos(c, width, height) while (node.x + width <= c.width) do local y, waste = stbrp__skyline_find_min_y(c, node, node.x, width) - if c.heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight then + if c.heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight then -- actually just want to test BL + -- bottom left if y < best_y then best_y = y best_prev_link = prev_link @@ -51435,7 +58233,9 @@ local function stbrp__skyline_find_best_pos(c, width, height) best_x = node.x end else + -- best-fit if y + height <= c.height then + -- can only use it if it first vertically if y < best_y or (y == best_y and waste < best_waste) then best_y = y best_waste = waste @@ -51451,12 +58251,30 @@ local function stbrp__skyline_find_best_pos(c, width, height) node = node.next end + -- if doing best-fit (BF), we also have to try aligning right edge to each node position + -- + -- e.g, if fitting + -- + -- ____________________ + -- |____________________| + -- + -- into + -- + -- | | + -- | ____________| + -- |____________| + -- + -- then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned + -- + -- This makes BF take about 2x the time + if c.heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight then local tail = c.active_head local node_scan = c.active_head local prev_link_scan = c local prev_link_scan_type = STBRP__PREV_LINK_TYPE.ACTIVE_HEAD + -- find first node that's admissible while tail and tail.x < width do tail = tail.next end @@ -51465,6 +58283,7 @@ local function stbrp__skyline_find_best_pos(c, width, height) local xpos = tail.x - width STBRP_ASSERT(xpos >= 0) + -- find the left position that matches this while node_scan.next and node_scan.next.x <= xpos do prev_link_scan = node_scan prev_link_scan_type = STBRP__PREV_LINK_TYPE.NEXT @@ -51480,6 +58299,7 @@ local function stbrp__skyline_find_best_pos(c, width, height) if y <= best_y then if y < best_y or waste < best_waste or (waste == best_waste and xpos < best_x) then best_x = xpos + -- STBRP_ASSERT(y <= best_y); [DEAR IMGUI] best_y = y best_waste = waste best_prev_link = prev_link_scan @@ -51505,19 +58325,29 @@ end --- @param height int --- @return stbrp__findresult local function stbrp__skyline_pack_rectangle(context, width, height) + -- find best position according to heuristic local res = stbrp__skyline_find_best_pos(context, width, height) + -- bail if: + -- 1. it failed + -- 2. the best node doesn't fit (we don't always check this) + -- 3. we're out of memory if res.prev_link == nil or res.y + height > context.height or context.free_head == nil then res.prev_link = nil res.prev_link_type = nil return res end + -- on success, create new node local node = context.free_head node.x = res.x node.y = res.y + height context.free_head = node.next + -- insert the new node into the right starting point, and + -- let 'cur' point to the remaining nodes needing to be + -- stitched back in + local cur if res.prev_link_type == STBRP__PREV_LINK_TYPE.ACTIVE_HEAD then cur = res.prev_link.active_head @@ -51526,6 +58356,7 @@ local function stbrp__skyline_pack_rectangle(context, width, height) end if cur.x < res.x then + -- preserve the existing one, so start testing with the next one local next = cur.next cur.next = node cur = next @@ -51537,13 +58368,17 @@ local function stbrp__skyline_pack_rectangle(context, width, height) end end + -- from here, traverse cur and free the nodes, until we get to one + -- that shouldn't be freed while cur.next and cur.next.x <= res.x + width do local next = cur.next + -- move the current node to the free list cur.next = context.free_head context.free_head = cur cur = next end + -- stitch the list back in node.next = cur if cur.x < res.x + width then @@ -51575,6 +58410,29 @@ local function rect_original_order(a, b) return a.was_packed < b.was_packed end +-- Assign packed locations to rectangles. The rectangles are of type +-- 'stbrp_rect' defined above, stored in the array 'rects', and there +-- are 'num_rects' many of them. +-- +-- Rectangles which are successfully packed have the 'was_packed' flag +-- set to a non-zero value and 'x' and 'y' store the minimum location +-- on each axis (i.e. bottom-left in cartesian coordinates, top-left +-- if you imagine y increasing downwards). Rectangles which do not fit +-- have the 'was_packed' flag set to 0. +-- +-- You should not try to access the 'rects' array from another thread +-- while this function is running, as the function temporarily reorders +-- the array while it executes. +-- +-- To pack into another rectangle, you need to call stbrp_init_target +-- again. To continue packing into the same rectangle, you can call +-- this function again. Calling this multiple times with multiple rect +-- arrays will probably produce worse packing results than calling it +-- a single time with the full rectangle array, but the option is +-- available. +-- +-- The function returns 1 if all of the rectangles were successfully +-- packed and 0 otherwise. --- @param context stbrp_context --- @param rects stbrp_rect[] --- @param num_rects int @@ -51582,15 +58440,17 @@ end local function stbrp_pack_rects(context, rects, num_rects) local all_rects_packed = 1 + -- we use the 'was_packed' field internally to allow sorting/unsorting for i = 1, num_rects do rects[i].was_packed = (i - 1) end + -- sort according to heuristic STBRP_SORT(rects, rect_height_compare) for i = 1, num_rects do if rects[i].w == 0 or rects[i].h == 0 then - rects[i].x = 0 + rects[i].x = 0 -- empty rect needs no space rects[i].y = 0 else local fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h) @@ -51604,8 +58464,10 @@ local function stbrp_pack_rects(context, rects, num_rects) end end + -- unsort STBRP_SORT(rects, rect_original_order) + -- set was_packed flags and all_rects_packed status for i = 1, num_rects do rects[i].was_packed = (rects[i].x == STBRP__MAXVAL and rects[i].y == STBRP__MAXVAL) and 0 or 1 if rects[i].was_packed == 0 then @@ -51613,6 +58475,7 @@ local function stbrp_pack_rects(context, rects, num_rects) end end + -- return the all_rects_packed status return all_rects_packed end @@ -51626,12 +58489,267 @@ return { setup_allow_out_of_mem = stbrp_setup_allow_out_of_mem, setup_heuristic = stbrp_setup_heuristic } + +-- ------------------------------------------------------------------------------ +-- This software is available under 2 licenses -- choose whichever you prefer. +-- ------------------------------------------------------------------------------ +-- ALTERNATIVE A - MIT License +-- Copyright (c) 2017 Sean Barrett +-- Permission is hereby granted, free of charge, to any person obtaining a copy of +-- this software and associated documentation files (the "Software"), to deal in +-- the Software without restriction, including without limitation the rights to +-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +-- of the Software, and to permit persons to whom the Software is furnished to do +-- so, subject to the following conditions: +-- The above copyright notice and this permission notice shall be included in all +-- copies or substantial portions of the Software. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +-- SOFTWARE. +-- ------------------------------------------------------------------------------ +-- ALTERNATIVE B - Public Domain (www.unlicense.org) +-- This is free and unencumbered software released into the public domain. +-- Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +-- software, either in source code form or as a compiled binary, for any purpose, +-- commercial or non-commercial, and by any means. +-- In jurisdictions that recognize copyright laws, the author or authors of this +-- software dedicate any and all copyright interest in the software to the public +-- domain. We make this dedication for the benefit of the public at large and to +-- the detriment of our heirs and successors. We intend this dedication to be an +-- overt act of relinquishment in perpetuity of all present and future rights to +-- this software under copyright law. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +-- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-- ------------------------------------------------------------------------------ end __FILES['imstb_textedit.lua'] = function() --- Dear ImGui -- This is a Lua port of original `imstb_textedit.h` +-- [DEAR IMGUI] +-- This is a slightly modified version of stb_textedit.h 1.14. +-- Those changes would need to be pushed into nothings/stb: +-- - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) +-- - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783) +-- - Added name to struct or it may be forward declared in our code. +-- - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925) +-- - Changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +-- Grep for [DEAR IMGUI] to find some changes. +-- - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_* + +-- stb_textedit.h - v1.14 - public domain - Sean Barrett +-- Development of this library was sponsored by RAD Game Tools +-- +-- This C header file implements the guts of a multi-line text-editing +-- widget; you implement display, word-wrapping, and low-level string +-- insertion/deletion, and stb_textedit will map user inputs into +-- insertions & deletions, plus updates to the cursor position, +-- selection state, and undo state. +-- +-- It is intended for use in games and other systems that need to build +-- their own custom widgets and which do not have heavy text-editing +-- requirements (this library is not recommended for use for editing large +-- texts, as its performance does not scale and it has limited undo). +-- +-- Non-trivial behaviors are modelled after Windows text controls. +-- +-- +-- LICENSE +-- +-- See end of file for license information. +-- +-- +-- DEPENDENCIES +-- +-- Uses the C runtime function 'memmove', which you can override +-- by defining IMSTB_TEXTEDIT_memmove before the implementation. +-- (In this port: ImStb.TEXTEDIT_memmove.) +-- +-- +-- VERSION HISTORY +-- +-- !!!! (2025-10-23) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +-- 1.14 (2021-07-11) page up/down, various fixes +-- 1.13 (2019-02-07) fix bug in undo size management +-- 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash +-- 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield +-- 1.10 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +-- 1.9 (2016-08-27) customizable move-by-word +-- 1.8 (2016-04-02) better keyboard handling when mouse button is down +-- 1.7 (2015-09-13) change y range handling in case baseline is non-0 +-- 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove +-- 1.5 (2014-09-10) add support for secondary keys for OS X +-- 1.4 (2014-08-17) fix signed/unsigned warnings +-- 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary +-- 1.2 (2014-05-27) fix some RAD types that had crept into the new code +-- 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) +-- 1.0 (2012-07-26) improve documentation, initial public release +-- 0.3 (2012-02-24) bugfixes, single-line mode; insert mode +-- 0.2 (2011-11-28) fixes to undo/redo +-- 0.1 (2010-07-08) initial version +-- +-- ADDITIONAL CONTRIBUTORS +-- +-- Ulf Winklemann: move-by-word in 1.1 +-- Fabian Giesen: secondary key inputs in 1.5 +-- Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6 +-- Louis Schnellbach: page up/down in 1.14 +-- +-- Bugfixes: +-- Scott Graham +-- Daniel Keller +-- Omar Cornut +-- Dan Thompson +-- +-- USAGE +-- +-- The basic concept is that you provide a "string" object which +-- behaves like an array of characters. stb_textedit uses indices to +-- refer to positions in the string, implicitly representing positions +-- in the displayed textedit. This is true for both plain text and +-- rich text; even with rich text stb_truetype interacts with your +-- code as if there was an array of all the displayed characters. +-- +-- Symbols you must define for implementation mode (in this port: fields of ImStb, see below): +-- +-- STB_TEXTEDIT_STRING the type of object representing a string being edited, +-- typically this is a wrapper object with other data you need +-- +-- STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) +-- STB_TEXTEDIT_LAYOUTROW(r,obj,n) returns the results of laying out a line of characters +-- starting from character #n (see discussion below) +-- STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character +-- to the xpos of the i+1'th char for a line of characters +-- starting at character #n (i.e. accounts for kerning +-- with previous char) +-- STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 1-based in this port +-- STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize +-- as manually wordwrapping for end-of-line positioning +-- +-- STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i +-- STB_TEXTEDIT_INSERTCHARS(obj,i,c,c_offset,n) try to insert n characters at i (taken from array c starting at c_offset) +-- returns number of characters actually inserted. [DEAR IMGUI] +-- +-- STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key +-- +-- STB_TEXTEDIT_K_LEFT keyboard input to move cursor left +-- STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right +-- STB_TEXTEDIT_K_UP keyboard input to move cursor up +-- STB_TEXTEDIT_K_DOWN keyboard input to move cursor down +-- STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page +-- STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page +-- STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line -- e.g. HOME +-- STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line -- e.g. END +-- STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text -- e.g. ctrl-HOME +-- STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text -- e.g. ctrl-END +-- STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor +-- STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor +-- STB_TEXTEDIT_K_UNDO keyboard input to perform undo +-- STB_TEXTEDIT_K_REDO keyboard input to perform redo +-- +-- STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to +-- STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to +-- STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word -- e.g. ctrl-LEFT +-- STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word -- e.g. ctrl-RIGHT +-- +-- 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, +-- i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. +-- +-- STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed +-- row of characters assuming they start on the i'th character--the width and +-- the height and the number of characters consumed. This allows this library +-- to traverse the entire layout incrementally. You need to compute word-wrapping +-- here. +-- +-- Each textfield keeps its own insert mode state, which is not how normal +-- applications work. To keep an app-wide insert mode, update/copy the +-- "insert_mode" field of STB_TexteditState before/after calling API functions. +-- +-- API (in this port: fields of the table returned by this file) +-- +-- initialize_state(state, is_single_line) +-- +-- click(str, state, x, y) +-- drag(str, state, x, y) +-- cut(str, state) -> bool +-- paste(str, state, text, len) -> bool +-- key(str, state, key) +-- text(str, state, text, text_len) +-- +-- Each of these functions potentially updates the string and updates the +-- state. +-- +-- initialize_state: +-- set the textedit state to a known good default state when initially +-- constructing the textedit. +-- +-- click: +-- call this with the mouse x,y on a mouse down; it will update the cursor +-- and reset the selection start/end to the cursor point. the x,y must +-- be relative to the text widget, with (0,0) being the top left. +-- +-- drag: +-- call this with the mouse x,y on a mouse drag/up; it will update the +-- cursor and the selection end point +-- +-- cut: +-- call this to delete the current selection; returns true if there was +-- one. you should FIRST copy the current selection to the system paste buffer. +-- (To copy, just copy the current selection out of the string yourself.) +-- +-- paste: +-- call this to paste text at the current cursor point or over the current +-- selection if there is one. +-- +-- key: +-- call this for keyboard inputs sent to the textfield. you can use it +-- for "key down" events or for "translated" key events. +-- +-- 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 +-- the STB_TexteditState. +-- +-- +-- Notes: +-- +-- This is designed to be usable in IMGUI, so it allows for the possibility of +-- running in an IMGUI that has NOT cached the multi-line layout. For this +-- reason, it provides an interface that is compatible with computing the +-- layout incrementally--we try to make sure we make as few passes through +-- as possible. (For example, to locate the mouse pointer in the text, we +-- could define functions that return the X and Y positions of characters +-- and binary search Y and then X, but if we're doing dynamic layout this +-- will run the layout algorithm many times, so instead we manually search +-- forward in one pass. Similar logic applies to e.g. up-arrow and +-- down-arrow movement.) +-- +-- If it's run in a widget that *has* cached the layout, then this is less +-- efficient, but it's not horrible on modern computers. But you wouldn't +-- want to edit million-line files with it. + -- ALL TABLES IN THIS FILE ARE 1-BASED! -- Character Indexing: -- idx=n, the n'th char (1-based) @@ -51644,6 +58762,10 @@ local STB_TEXTEDIT_STRINGLEN = ImStb.TEXTEDIT_STRINGLEN local STB_TEXTEDIT_GETCHAR = ImStb.TEXTEDIT_GETCHAR local STB_TEXTEDIT_GETWIDTH = ImStb.TEXTEDIT_GETWIDTH local STB_TEXTEDIT_LAYOUTROW = ImStb.TEXTEDIT_LAYOUTROW +-- [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. local IMSTB_TEXTEDIT_GETNEXTCHARINDEX = ImStb.TEXTEDIT_GETNEXTCHARINDEX local IMSTB_TEXTEDIT_GETPREVCHARINDEX = ImStb.TEXTEDIT_GETPREVCHARINDEX local STB_TEXTEDIT_MOVEWORDLEFT = ImStb.TEXTEDIT_MOVEWORDLEFT @@ -51653,34 +58775,35 @@ local STB_TEXTEDIT_MOVELINEEND = ImStb.TEXTEDIT_MOVELINEEND local STB_TEXTEDIT_DELETECHARS = ImStb.TEXTEDIT_DELETECHARS local STB_TEXTEDIT_INSERTCHARS = ImStb.TEXTEDIT_INSERTCHARS -STB_TEXTEDIT_NEWLINE = 10 +STB_TEXTEDIT_NEWLINE = 10 -- the character returned by _GETCHAR() we recognize as manually wordwrapping for end-of-line positioning STB_TEXTEDIT_K_LEFT = 0x200000 -- keyboard input to move cursor left STB_TEXTEDIT_K_RIGHT = 0x200001 -- keyboard input to move cursor right STB_TEXTEDIT_K_UP = 0x200002 -- keyboard input to move cursor up STB_TEXTEDIT_K_DOWN = 0x200003 -- keyboard input to move cursor down -STB_TEXTEDIT_K_LINESTART = 0x200004 -- keyboard input to move cursor to start of line -STB_TEXTEDIT_K_LINEEND = 0x200005 -- keyboard input to move cursor to end of line -STB_TEXTEDIT_K_TEXTSTART = 0x200006 -- keyboard input to move cursor to start of text -STB_TEXTEDIT_K_TEXTEND = 0x200007 -- keyboard input to move cursor to end of text +STB_TEXTEDIT_K_LINESTART = 0x200004 -- keyboard input to move cursor to start of line -- e.g. HOME +STB_TEXTEDIT_K_LINEEND = 0x200005 -- keyboard input to move cursor to end of line -- e.g. END +STB_TEXTEDIT_K_TEXTSTART = 0x200006 -- keyboard input to move cursor to start of text -- e.g. ctrl-HOME +STB_TEXTEDIT_K_TEXTEND = 0x200007 -- keyboard input to move cursor to end of text -- e.g. ctrl-END STB_TEXTEDIT_K_DELETE = 0x200008 -- keyboard input to delete selection or character under cursor STB_TEXTEDIT_K_BACKSPACE = 0x200009 -- keyboard input to delete selection or character left of cursor STB_TEXTEDIT_K_UNDO = 0x20000A -- keyboard input to perform undo STB_TEXTEDIT_K_REDO = 0x20000B -- keyboard input to perform redo -STB_TEXTEDIT_K_WORDLEFT = 0x20000C -- keyboard input to move cursor left one word -STB_TEXTEDIT_K_WORDRIGHT = 0x20000D -- keyboard input to move cursor right one word +STB_TEXTEDIT_K_WORDLEFT = 0x20000C -- keyboard input to move cursor left one word -- e.g. ctrl-LEFT +STB_TEXTEDIT_K_WORDRIGHT = 0x20000D -- keyboard input to move cursor right one word -- e.g. ctrl-RIGHT STB_TEXTEDIT_K_PGUP = 0x20000E -- keyboard input to move cursor up a page STB_TEXTEDIT_K_PGDOWN = 0x20000F -- keyboard input to move cursor down a page -STB_TEXTEDIT_K_SHIFT = 0x400000 +STB_TEXTEDIT_K_SHIFT = 0x400000 -- a power of two that is or'd in to a keyboard input to represent the shift key -IMSTB_TEXTEDIT_UNDOSTATECOUNT = 99 -local IMSTB_TEXTEDIT_UNDOCHARCOUNT = 999 +IMSTB_TEXTEDIT_UNDOSTATECOUNT = 99 -- the number of undo states to allow +local IMSTB_TEXTEDIT_UNDOCHARCOUNT = 999 -- the number of characters to store in the undo buffer local IMSTB_TEXTEDIT_memmove = ImStb.TEXTEDIT_memmove +-- forward declarations local stb_text_undo local stb_text_redo ----------------------------------------------------------------- ----------------------------------------------------------------- +------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- --- STB_TexteditState --- @@ -51703,6 +58826,7 @@ local stb_text_redo --- @nodiscard local function StbUndoRecord() return { + -- private data where = 1, insert_length = 0, delete_length = 0, @@ -51732,6 +58856,7 @@ local function StbUndoState() end return { + -- private data undo_rec = undo_rec, undo_char = undo_char, @@ -51762,16 +58887,34 @@ end --- @nodiscard function STB_TexteditState() return { - cursor = 0, + --------------------- + -- + -- public data + -- - select_start = 0, + cursor = 0, + -- position of the text cursor within the string + + select_start = 0, -- selection start point select_end = 0, + -- selection start and end point in characters; if equal, no selection. + -- note that start may be less than or greater than end (e.g. when + -- dragging the mouse, start is where the initial click was, and you + -- can drag in either direction) insert_mode = false, + -- each textfield keeps its own insert mode state. to keep an app-wide + -- insert mode, copy this value in/out of the app state row_count_per_page = 0, + -- page size in number of row. + -- this value MUST be set to >0 for pageup or pagedown in multilines documents. - cursor_at_end_of_line = false, + --------------------- + -- + -- private data + -- + cursor_at_end_of_line = false, -- not implemented yet initialized = false, has_preferred_x = false, single_line = false, @@ -51779,7 +58922,7 @@ function STB_TexteditState() padding2 = 0, padding3 = 0, - preferred_x = 0.0, + preferred_x = 0.0, -- this determines where the cursor up/down tries to seek to along x undostate = StbUndoState() } @@ -51790,12 +58933,20 @@ local function STB_TEXT_HAS_SELECTION(s) return s.select_start ~= s.select_end end +------------------------------------------------------------------------------- +--- +--- StbTexteditRow +--- +--- Result of layout query, used by stb_textedit to determine where +--- the text in each row is. + +-- result of layout query --- @class StbTexteditRow ---- @field x0 float # starting x location +--- @field x0 float # starting x location, end x location (allows for align=right, etc) --- @field x1 float # end x location --- @field baseline_y_delta float # position of baseline relative to previous row's baseline ---- @field ymin float # height of row above baseline ---- @field ymax float # height of row below baseline +--- @field ymin float # height of row above and below baseline +--- @field ymax float # height of row above and below baseline --- @field num_chars int --- @return StbTexteditRow @@ -51827,10 +58978,15 @@ end ---------------------------------------- ---------------------------------------- --- ---- Implementation +--- Implementation mode --- --- +------------------------------------------------------------------------------- +--- +--- Mouse input handling +--- + local stb_text_locate_coord do -- only create once, reuse later @@ -51982,6 +59138,7 @@ end --- --- +-- forward declarations local stb_text_makeundo_insert local stb_text_makeundo_delete local stb_text_makeundo_replace @@ -52030,8 +59187,8 @@ function stb_textedit_find_charpos(find, str, n, single_line) local z = STB_TEXTEDIT_STRINGLEN(str) local first - -- special case if it's at the end (may not be needed?) if n == z + 1 and single_line then + -- special case if it's at the end (may not be needed?) STB_TEXTEDIT_LAYOUTROW(r, str, 1) find.y = 0 find.first_char = 1 @@ -52051,18 +59208,18 @@ function stb_textedit_find_charpos(find, str, n, single_line) if n < i + r.num_chars - 1 then break end - if str.LastMoveDirectionLR == ImGuiDir.Right and str.Stb.cursor > 1 and str.Stb.cursor == i + r.num_chars and STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) ~= STB_TEXTEDIT_NEWLINE then -- [IMGUI] Wrapping point handling + if str.LastMoveDirectionLR == ImGuiDir.Right and str.Stb.cursor > 1 and str.Stb.cursor == i + r.num_chars and STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) ~= STB_TEXTEDIT_NEWLINE then -- [DEAR IMGUI] Wrapping point handling break end - if (i - 1) + r.num_chars == z and z > 0 and STB_TEXTEDIT_GETCHAR(str, z) ~= STB_TEXTEDIT_NEWLINE then -- [IMGUI] special handling for last line - break + if (i - 1) + r.num_chars == z and z > 0 and STB_TEXTEDIT_GETCHAR(str, z) ~= STB_TEXTEDIT_NEWLINE then -- [DEAR IMGUI] special handling for last line + break -- [DEAR IMGUI] end prev_start = i i = i + r.num_chars find.y = find.y + r.baseline_y_delta - if i == z + 1 then -- [IMGUI] - r.num_chars = 0 - break + if i == z + 1 then -- [DEAR IMGUI] + r.num_chars = 0 -- [DEAR IMGUI] + break -- [DEAR IMGUI] end end @@ -52110,7 +59267,7 @@ local function stb_textedit_delete(str, state, where, len) state.has_preferred_x = false end --- delete the selection +-- delete the section --- @param str IMSTB_TEXTEDIT_STRING --- @param state STB_TexteditState local function stb_textedit_delete_selection(str, state) @@ -52129,7 +59286,7 @@ local function stb_textedit_delete_selection(str, state) end end --- canonicalize the selection so start <= end +-- canoncialize the selection so start <= end --- @param state STB_TexteditState local function stb_textedit_sortselection(state) if state.select_end < state.select_start then @@ -52210,7 +59367,7 @@ local function stb_textedit_paste_internal(str, state, text, len) end -- API key: process text input --- [IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. +-- [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. --- @param str IMSTB_TEXTEDIT_STRING --- @param state STB_TexteditState --- @param text IMSTB_TEXTEDIT_CHARTYPE[] @@ -52363,7 +59520,7 @@ function stb_textedit_key(str, state, key) break end - -- [IMGUI] + -- [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 then -- break @@ -52560,8 +59717,8 @@ end ----------------------------------------------------- --- --- Undo processing ---- OPTIMIZE: the undo/redo buffer should be circular --- +--- @OPTIMIZE: the undo/redo buffer should be circular --- @param state StbUndoState local function stb_textedit_flush_redo(state) @@ -52581,7 +59738,7 @@ local function stb_textedit_discard_undo(state) IMSTB_TEXTEDIT_memmove(state.undo_char, 1, state.undo_char, n + 1, state.undo_char_point - 1) for i = 1, state.undo_point do if state.undo_rec[i].char_storage >= 0 then - state.undo_rec[i].char_storage = state.undo_rec[i].char_storage - n -- OPTIMIZE: get rid of char_storage and infer it + state.undo_rec[i].char_storage = state.undo_rec[i].char_storage - n -- @OPTIMIZE: get rid of char_storage and infer it end end end @@ -52614,7 +59771,7 @@ local function stb_textedit_discard_redo(state) end -- now move all the redo records towards the end of the buffer; the first one is at 'redo_point' - -- [IMGUI] + -- [DEAR IMGUI] local move_size = IMSTB_TEXTEDIT_UNDOSTATECOUNT - state.redo_point - 1 IMSTB_TEXTEDIT_memmove(state.undo_rec, state.redo_point + 1, state.undo_rec, state.redo_point, move_size) @@ -52760,6 +59917,9 @@ function stb_text_redo(str, state) local u = s.undo_rec[s.undo_point] local r = s.undo_rec[s.redo_point] + -- we KNOW there must be room for the undo record, because the redo record + -- was derived from an undo record + u.delete_length = r.insert_length u.insert_length = r.delete_length u.where = r.where @@ -52768,6 +59928,7 @@ function stb_text_redo(str, state) if r.delete_length > 0 then -- the redo record requires us to delete characters, so the undo record -- needs to store the characters + if s.undo_char_point + u.insert_length > s.redo_char_point then u.insert_length = 0 u.delete_length = 0 @@ -52775,6 +59936,7 @@ function stb_text_redo(str, state) u.char_storage = s.undo_char_point s.undo_char_point = s.undo_char_point + u.insert_length + -- now save the characters for i = 0, u.insert_length - 1 do s.undo_char[u.char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i) end @@ -52784,6 +59946,7 @@ function stb_text_redo(str, state) end if r.insert_length ~= 0 then + -- easy case: need to insert n characters r.insert_length = STB_TEXTEDIT_INSERTCHARS(str, r.where, s.undo_char, r.char_storage, r.insert_length) s.redo_char_point = s.redo_char_point + r.insert_length end @@ -52830,6 +59993,7 @@ function stb_text_makeundo_replace(str, state, where, old_length, new_length) end end +-- reset the state to default --- @param state STB_TexteditState --- @param is_single_line bool local function stb_textedit_clear_state(state, is_single_line) @@ -52853,7 +60017,7 @@ return { click = stb_textedit_click, drag = stb_textedit_drag, createundo = stb_text_createundo, - initialize_state = stb_textedit_clear_state, + initialize_state = stb_textedit_clear_state, -- API initialize text = stb_textedit_text, key = stb_textedit_key, @@ -52867,12 +60031,210 @@ return { HAS_SELECTION = STB_TEXT_HAS_SELECTION } + +------------------------------------------------------------------------------- +-- This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------- +-- ALTERNATIVE A - MIT License +-- Copyright (c) 2017 Sean Barrett +-- Permission is hereby granted, free of charge, to any person obtaining a copy of +-- this software and associated documentation files (the "Software"), to deal in +-- the Software without restriction, including without limitation the rights to +-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +-- of the Software, and to permit persons to whom the Software is furnished to do +-- so, subject to the following conditions: +-- The above copyright notice and this permission notice shall be included in all +-- copies or substantial portions of the Software. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +-- SOFTWARE. +------------------------------------------------------------------------------- +-- ALTERNATIVE B - Public Domain (www.unlicense.org) +-- This is free and unencumbered software released into the public domain. +-- Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +-- software, either in source code form or as a compiled binary, for any purpose, +-- commercial or non-commercial, and by any means. +-- In jurisdictions that recognize copyright laws, the author or authors of this +-- software dedicate any and all copyright interest in the software to the public +-- domain. We make this dedication for the benefit of the public at large and to +-- the detriment of our heirs and successors. We intend this dedication to be an +-- overt act of relinquishment in perpetuity of all present and future rights to +-- this software under copyright law. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +-- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------- end __FILES['imstb_truetype.lua'] = function() --- Dear ImGui -- This is a Lua port of original `imstb_truetype.h` +-- [DEAR IMGUI] +-- This is a slightly modified version of stb_truetype.h 1.26. +-- Mostly fixing for compiler and static analyzer warnings. +-- Grep for [DEAR IMGUI] to find the changes. + +-- stb_truetype.h - v1.26 - public domain +-- authored from 2009-2021 by Sean Barrett / RAD Game Tools +-- +-- ======================================================================= +-- +-- NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES +-- +-- This library does no range checking of the offsets found in the file, +-- meaning an attacker can use it to read arbitrary memory. +-- +-- ======================================================================= +-- +-- This library processes TrueType files: +-- parse files +-- extract glyph metrics +-- extract glyph shapes +-- render glyphs to one-channel bitmaps with antialiasing (box filter) +-- +-- Todo: +-- non-MS cmaps +-- crashproof on bad data +-- hinting? (no longer patented) +-- cleartype-style AA? +-- optimize: build edge-list directly from curves +-- optimize: rasterize directly from curves? +-- +-- ADDITIONAL CONTRIBUTORS +-- +-- Mikko Mononen: compound shape support, more cmap formats +-- Tor Andersson: kerning, subpixel rendering +-- Dougall Johnson: OpenType / Type 2 font handling +-- Daniel Ribeiro Maciel: basic GPOS-based kerning +-- +-- Misc other: +-- Ryan Gordon +-- Simon Glass +-- github:IntellectualKitty +-- Imanol Celaya +-- Daniel Ribeiro Maciel +-- +-- Bug/warning reports/fixes: +-- "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe +-- Cass Everitt Martins Mozeiko github:aloucks +-- stoiko (Haemimont Games) Cap Petschulat github:oyvindjam +-- Brian Hook Omar Cornut github:vassvik +-- Walter van Niftrik Ryan Griege +-- David Gow Peter LaValle +-- David Given Sergey Popov +-- Ivan-Assen Ivanov Giumo X. Clanjor +-- Anthony Pesch Higor Euripedes +-- Johan Duparc Thomas Fields +-- Hou Qiming Derek Vinyard +-- Rob Loach Cort Stratton +-- Kenney Phillis Jr. Brian Costabile +-- Ken Voskuil (kaesve) +-- +-- USAGE +-- +-- "Load" a font file from a memory buffer (you have to keep the buffer loaded) +-- stbtt_InitFont() +-- stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +-- +-- Character advance/positioning +-- stbtt_GetFontVMetrics() +-- +-- Starting with version 1.06, the rasterizer was replaced with a new, +-- faster and generally-more-precise rasterizer. The new rasterizer more +-- accurately measures pixel coverage for anti-aliasing, except in the case +-- where multiple shapes overlap, in which case it overestimates the AA pixel +-- coverage. Thus, anti-aliasing of intersecting shapes may look wrong. +-- (This port only implements the new rasterizer.) +-- +-- ADDITIONAL DOCUMENTATION +-- +-- Some important concepts to understand to use this library: +-- +-- Codepoint +-- Characters are defined by unicode codepoints, e.g. 65 is +-- uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is +-- the hiragana for "ma". +-- +-- Glyph +-- A visual character shape (every codepoint is rendered as +-- some glyph) +-- +-- Glyph index +-- A font-specific integer ID representing a glyph +-- +-- Baseline +-- Glyph shapes are defined relative to a baseline, which is the +-- bottom of uppercase characters. Characters extend both above +-- and below the baseline. +-- +-- Current Point +-- As you draw text to the screen, you keep track of a "current point" +-- which is the origin of each character. The current point's vertical +-- position is the baseline. Even "baked fonts" use this model. +-- +-- Vertical Font Metrics +-- The vertical qualities of the font, used to vertically position +-- and space the characters. See docs for stbtt_GetFontVMetrics. +-- +-- Font Size in Pixels or Points +-- The preferred interface for specifying font sizes in stb_truetype +-- is to specify how tall the font's vertical extent should be in pixels. +-- +-- DETAILED USAGE: +-- +-- Scale: +-- Select how high you want the font to be, in pixels. +-- Call ScaleForPixelHeight to compute a scale factor SF that will be +-- used by all other functions. +-- +-- Current point: +-- Set the current point where the first character will appear. The +-- first character could extend left of the current point; this is font +-- dependent. You can either choose a current point that is the leftmost +-- point and hope, or add some padding, or check the bounding box or +-- left-side-bearing of the first character to be displayed and set +-- the current point based on that. +-- +-- Displaying a character: +-- Compute the bounding box of the character. It will contain signed values +-- relative to . I.e. if it returns x0,y0,x1,y1, +-- then the character should be displayed in the rectangle from +-- to = n then @@ -53470,23 +60841,25 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.fontstart = fontstart info.cff = stbtt__new_buf(nil, 0) - cmap = stbtt__find_table(data, fontstart, "cmap") - info.loca = stbtt__find_table(data, fontstart, "loca") - info.head = stbtt__find_table(data, fontstart, "head") - info.glyf = stbtt__find_table(data, fontstart, "glyf") - info.hhea = stbtt__find_table(data, fontstart, "hhea") - info.hmtx = stbtt__find_table(data, fontstart, "hmtx") - info.kern = stbtt__find_table(data, fontstart, "kern") - info.gpos = stbtt__find_table(data, fontstart, "GPOS") + cmap = stbtt__find_table(data, fontstart, "cmap") -- required + info.loca = stbtt__find_table(data, fontstart, "loca") -- required + info.head = stbtt__find_table(data, fontstart, "head") -- required + info.glyf = stbtt__find_table(data, fontstart, "glyf") -- required + info.hhea = stbtt__find_table(data, fontstart, "hhea") -- required + info.hmtx = stbtt__find_table(data, fontstart, "hmtx") -- required + info.kern = stbtt__find_table(data, fontstart, "kern") -- not required + info.gpos = stbtt__find_table(data, fontstart, "GPOS") -- not required if (cmap == 0 or info.head == 0 or info.hhea == 0 or info.hmtx == 0) then return false end if info.glyf ~= 0 then + -- required for truetype if info.loca == 0 then return false end else + -- initialization for CFF / Type2 fonts (OTF) local cff = stbtt__find_table(data, fontstart, "CFF ") if cff == 0 then return false @@ -53495,14 +60868,16 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.fontdicts = stbtt__new_buf(nil, 0) info.fdselect = stbtt__new_buf(nil, 0) - info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- TODO: this should use size from table + -- @TODO this should use size from table (not 512MB) + info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- PORT: 64MB here instead of 512MB local b = info.cff -- read the header stbtt__buf_skip(b, 2) - stbtt__buf_seek(b, stbtt__buf_get8(b)) + stbtt__buf_seek(b, stbtt__buf_get8(b)) -- hdrsize - -- TODO: the name INDEX could list multiple fonts, but we just use the first one. + -- @TODO the name INDEX could list multiple fonts, + -- but we just use the first one. stbtt__cff_get_index(b) -- name INDEX local topdictidx = stbtt__cff_get_index(b) local topdict = stbtt__cff_index_get(topdictidx, 0) @@ -53515,6 +60890,7 @@ local function stbtt_InitFont_internal(info, data, fontstart) local fdselectoff = stbtt__dict_get_ints(topdict, bit32.bor(0x100, 37), 1) info.subrs = stbtt__get_subrs(b, topdict) + -- we only support Type 2 charstrings if cstype[1] ~= 2 then return false end @@ -53523,6 +60899,7 @@ local function stbtt_InitFont_internal(info, data, fontstart) end if fdarrayoff[1] ~= 0 then + -- looks like a CID font if fdselectoff[1] == 0 then return false end @@ -53545,19 +60922,26 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.svg = -1 + -- find a cmap encoding table we understand *now* to avoid searching + -- later. (todo: could make this installable) + -- the same regardless of glyph. numTables = ttUSHORT(data, cmap + 2) info.index_map = 0 for i = 0, numTables - 1 do local encoding_record = cmap + 4 + 8 * i + -- find an encoding we understand: local platform_id = ttUSHORT(data, encoding_record) if platform_id == STBTT_PLATFORM_ID.MICROSOFT then local ms_eid = ttUSHORT(data, encoding_record + 2) if ms_eid == STBTT_MS_EID.UNICODE_BMP or ms_eid == STBTT_MS_EID.UNICODE_FULL then + -- MS/Unicode info.index_map = cmap + ttULONG(data, encoding_record + 4) end elseif platform_id == STBTT_PLATFORM_ID.UNICODE then + -- Mac/iOS has these + -- all the encodingIDs are unicode, so we don't bother to check it info.index_map = cmap + ttULONG(data, encoding_record + 4) end end @@ -53569,6 +60953,11 @@ local function stbtt_InitFont_internal(info, data, fontstart) return true end +-- If you're going to perform multiple operations on the same character +-- and you want a speed-up, call this function with the character you're +-- going to process, then use glyph-based functions instead of the +-- codepoint-based functions. +-- Returns 0 if the character codepoint is not defined in the font. --- @param info stbtt_fontinfo --- @param unicode_codepoint int function stbtt_FindGlyphIndex(info, unicode_codepoint) @@ -53576,7 +60965,7 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) local index_map = info.index_map local format = ttUSHORT(data, index_map + 0) - if format == 0 then + if format == 0 then -- apple byte encoding local bytes = ttUSHORT(data, index_map + 2) if unicode_codepoint < bytes - 6 then return ttBYTE(data, index_map + 6 + unicode_codepoint) @@ -53590,14 +60979,15 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) end return 0 elseif format == 2 then - STBTT_assert(false) -- TODO: high-byte mapping for japanese/chinese/korean + STBTT_assert(false) -- @TODO: high-byte mapping for japanese/chinese/korean return 0 - elseif format == 4 then + elseif format == 4 then -- standard mapping for windows fonts: binary search collection of ranges local segcount = bit32.rshift(ttUSHORT(data, index_map + 6), 1) local searchRange = bit32.rshift(ttUSHORT(data, index_map + 8), 1) local entrySelector = ttUSHORT(data, index_map + 10) local rangeShift = bit32.rshift(ttUSHORT(data, index_map + 12), 1) + -- do a binary search of the segments local endCount = index_map + 14 local search = endCount @@ -53605,10 +60995,13 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) return 0 end + -- they lie from endCount .. endCount + segCount + -- but searchRange is the nearest power of two, so... if unicode_codepoint >= ttUSHORT(data, search + rangeShift * 2) then search = search + rangeShift * 2 end + -- now decrement to bias correctly to find smallest search = search - 2 while entrySelector ~= 0 do searchRange = bit32.rshift(searchRange, 1) @@ -53640,8 +61033,9 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) local ngroups = ttULONG(data, index_map + 12) local low = 0 local high = ngroups + -- Binary search the right group. while low < high do - local mid = low + bit32.rshift(high - low, 1) + local mid = low + bit32.rshift(high - low, 1) -- rounds down, so low <= mid < high local start_char = ttULONG(data, index_map + 16 + mid * 12) local end_char = ttULONG(data, index_map + 16 + mid * 12 + 4) if unicode_codepoint < start_char then @@ -53657,10 +61051,10 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) end end end - return 0 + return 0 -- not found end - -- TODO: + -- @TODO STBTT_assert(false) return 0 end @@ -53682,8 +61076,8 @@ end local function stbtt__GetGlyfOffset(info, glyph_index) STBTT_assert(info.cff.size == 0) - if glyph_index >= info.numGlyphs then return -1 end - if info.indexToLocFormat >= 2 then return -1 end + if glyph_index >= info.numGlyphs then return -1 end -- glyph index out of range + if info.indexToLocFormat >= 2 then return -1 end -- unknown index->glyph map format local g1, g2 if info.indexToLocFormat == 0 then @@ -53694,9 +61088,10 @@ local function stbtt__GetGlyfOffset(info, glyph_index) g2 = info.glyf + ttULONG(info.data, info.loca + glyph_index * 4 + 4) end - if g1 == g2 then return -1 else return g1 end + if g1 == g2 then return -1 else return g1 end -- if length is 0, return -1 end +-- Gets the bounding box of the visible part of the glyph, in unscaled coordinates --- @return integer, integer?, integer?, integer?, integer? local function stbtt_GetGlyphBox(info, glyph_index) local n, x0, y0, x1, y1 @@ -53768,7 +61163,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- 1-based idx local n = 1 + ttUSHORT(data, endPtsOfContours + numberOfContours * 2 - 2) - local m = n + 2 * numberOfContours + local m = n + 2 * numberOfContours -- a loose bound on how many vertices we might need vertices = {} for i = 1, m do vertices[i] = stbtt_vertex() end @@ -53779,7 +61174,11 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) local next_move = 0 local flagcount = 0 - local off = m - n + -- in first pass, we load uninterpreted data into the allocated array + -- above, shifted to the end of the array so we won't overwrite it when + -- we create our final data starting from the front + + local off = m - n -- starting offset for uninterpreted data, regardless of how m ends up being calculated -- first load flags local flags = 0 @@ -53806,7 +61205,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) if bit32.band(flags, 2) ~= 0 then local dx = data[points] points = points + 1 - if bit32.band(flags, 16) ~= 0 then + if bit32.band(flags, 16) ~= 0 then -- ??? x = x + dx else x = x - dx @@ -53828,7 +61227,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) if bit32.band(flags, 4) ~= 0 then local dy = data[points] points = points + 1 - if bit32.band(flags, 32) ~= 0 then + if bit32.band(flags, 32) ~= 0 then -- ??? y = y + dy else y = y - dy @@ -53859,15 +61258,19 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) -- now start the new one start_off = (bit32.band(flags, 1) == 0) if start_off then + -- if we start off with an off-curve point, then when we need to find a point on the curve + -- where we can start, and we need to save some state for when we wraparound. scx = x scy = y if bit32.band(vertices[off + i + 1].type, 1) == 0 then + -- next point is also a curve point, so interpolate an on-point curve sx = bit32.rshift(x + stbtt_int32(vertices[off + i + 1].x), 1) sy = bit32.rshift(y + stbtt_int32(vertices[off + i + 1].y), 1) else + -- otherwise just use the next point as our start point sx = stbtt_int32(vertices[off + i + 1].x) sy = stbtt_int32(vertices[off + i + 1].y) - i = i + 1 + i = i + 1 -- we're using point i+1 as the starting point, so skip it end else sx = x @@ -53879,8 +61282,8 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) next_move = 1 + ttUSHORT(data, endPtsOfContours + j * 2) j = j + 1 else - if bit32.band(flags, 1) == 0 then - if was_off then + if bit32.band(flags, 1) == 0 then -- if it's a curve + if was_off then -- two off-curve control points in a row means interpolate an on-curve midpoint stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.CURVE, bit32.rshift(cx + x, 1), bit32.rshift(cy + y, 1), cx, cy) num_vertices = num_vertices + 1 end @@ -53904,6 +61307,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy) elseif numberOfContours < 0 then + -- Compound shapes. local more = 1 local comp = g + 10 num_vertices = 0 @@ -53919,8 +61323,8 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) flags = ttSHORT(data, comp) comp = comp + 2 gidx = ttSHORT(data, comp) comp = comp + 2 - if bit32.band(flags, 2) ~= 0 then - if bit32.band(flags, 1) ~= 0 then + if bit32.band(flags, 2) ~= 0 then -- XY values + if bit32.band(flags, 1) ~= 0 then -- shorts mtx[5] = ttSHORT(data, comp) comp = comp + 2 mtx[6] = ttSHORT(data, comp) comp = comp + 2 else @@ -53928,7 +61332,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) mtx[6] = ttCHAR(data, comp) comp = comp + 1 end else - -- TODO: handle matching point + -- @TODO handle matching point STBTT_assert(false) end @@ -53955,11 +61359,14 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) mtx[4] = ttSHORT(data, comp) / 16384.0 comp = comp + 2 end + -- Find transformation scales. m = STBTT_sqrt(mtx[1] * mtx[1] + mtx[2] * mtx[2]) n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4]) + -- Get indexed glyph. comp_num_vertices, comp_verts = stbtt_GetGlyphShape(info, gidx) if comp_num_vertices > 0 then + -- Transform vertices. for i = 1, comp_num_vertices do local v = comp_verts[i] local x = v.x @@ -53972,6 +61379,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) v.cy = stbtt_int16(n * (mtx[2] * x + mtx[4] * y + mtx[6])) end + -- Append vertices. if num_vertices == 0 then -- LUA: No malloc vertices = comp_verts else @@ -53983,6 +61391,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) num_vertices = num_vertices + comp_num_vertices end + -- More components ? more = bit32.band(flags, bit32.lshift(1, 5)) end end @@ -54138,7 +61547,7 @@ local function stbtt__run_charstring(info, glyph_index, c) clear_stack = 1 b0 = stbtt__buf_get8(b) - -- TODO: implement hinting + -- @TODO implement hinting if b0 == 0x13 or b0 == 0x14 then -- hintmask or cntrmask if in_header then maskbits = maskbits + trunc(sp / 2) -- implicit "vstem" @@ -54287,6 +61696,8 @@ local function stbtt__run_charstring(info, glyph_index, c) elseif b0 == 0x0C then -- two-byte escape local b1 = stbtt__buf_get8(b) + -- @TODO These "flex" implementations ignore the flex-depth and resolution, + -- and always draw beziers. if b1 == 0x22 then -- hflex if sp < 7 then return STBTT__CSERR("hflex stack") end local dx1 = s[0] @@ -54419,6 +61830,15 @@ function stbtt__GetGlyphInfoT2(info, glyph_index) return ((r ~= 0) and c.num_vertices or 0), x0, y0, x1, y1 end +-- returns # of vertices and fills *vertices with the pointer to them +-- these are expressed in "unscaled" coordinates +-- +-- The shape is a series of contours. Each one starts with +-- a STBTT_moveto, then consists of a series of mixed +-- STBTT_lineto and STBTT_curveto segments. A lineto +-- draws a line from previous endpoint to its x,y; a curveto +-- draws a quadratic bezier from previous endpoint to +-- its x,y, using cx,cy as the bezier control point. --- @param info stbtt_fontinfo --- @param glyph_index int function stbtt_GetGlyphShape(info, glyph_index) @@ -54429,6 +61849,9 @@ function stbtt_GetGlyphShape(info, glyph_index) end end +-- leftSideBearing is the offset from the current horizontal position to the left edge of the character +-- advanceWidth is the offset from the current horizontal position to the next horizontal position +-- these are expressed in unscaled coordinates --- @param info stbtt_fontinfo --- @param glyph_index int function stbtt_GetGlyphHMetrics(info, glyph_index) @@ -54446,6 +61869,12 @@ function stbtt_GetGlyphHMetrics(info, glyph_index) return advanceWidth, leftSideBearing end +-- ascent is the coordinate above the baseline the font extends; descent +-- is the coordinate below the baseline the font extends (i.e. it is typically negative) +-- lineGap is the spacing between one row's descent and the next row's ascent... +-- so you should advance the vertical position by "ascent - descent + lineGap" +-- these are expressed in unscaled coordinates, so you must multiply by +-- the scale factor for a given size --- @param info stbtt_fontinfo function stbtt_GetFontVMetrics(info) local ascent = ttSHORT(info.data, info.hhea + 4) @@ -54455,6 +61884,12 @@ function stbtt_GetFontVMetrics(info) return ascent, descent, lineGap end +-- computes a scale factor to produce a font whose "height" is 'pixels' tall. +-- Height is measured as the distance from the highest ascender to the lowest +-- descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics +-- and computing: +-- scale = pixels / (ascent - descent) +-- so if you prefer to measure height by the ascent only, use a similar calculation. --- @param info stbtt_fontinfo --- @param height float function stbtt_ScaleForPixelHeight(info, height) @@ -54465,10 +61900,12 @@ end ------------------------------------ ------------------------------------ --- ---- Antialiasing software rasterizer +--- antialiasing software rasterizer --- --- +-- same as stbtt_GetGlyphBitmapBox, but you can specify a subpixel +-- shift for the character --- @param font stbtt_fontinfo --- @param glyph int --- @param scale_x float @@ -54496,6 +61933,11 @@ function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, return ix0, iy0, ix1, iy1 end +-- get the bbox of the bitmap centered around the glyph origin; so the +-- bitmap width is ix1-ix0, height is iy1-iy0, and location to place +-- the bitmap top left is (leftSideBearing*scale,iy0). +-- (Note that the bitmap uses y-increases-down, but the shape uses +-- y-increases-up, so GlyphBitmapBox and GlyphBox are inverted.) --- @param font stbtt_fontinfo --- @param glyph int --- @param scale_x float @@ -54518,6 +61960,8 @@ end --- stbtt_MakeGlyphBitmap --- stbtt_GetGlyphBitmapSubpixel +-- the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +-- (i.e. it has already been clipped to those) --- @param scanline float[] --- @param x int --- @param e stbtt__active_edge @@ -54559,7 +62003,7 @@ local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1) -- do nothing else STBTT_assert(x0 >= x and x0 <= x + 1 and x1 >= x and x1 <= x + 1) - scanline[x] = scanline[x] + e.direction * (y1 - y0) * (1 - ((x0 - x) + (x1 - x)) / 2) + scanline[x] = scanline[x] + e.direction * (y1 - y0) * (1 - ((x0 - x) + (x1 - x)) / 2) -- coverage = 1 - average x position end end @@ -54597,6 +62041,7 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t while e do -- brute force every pixel + -- compute intersection points with top & bottom STBTT_assert(e.ey >= y_top) @@ -54640,8 +62085,8 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t if x_top >= 0 and x_bottom >= 0 and x_top < len and x_bottom < len then -- from here on, we don't have to range check x values if trunc(x_top) == trunc(x_bottom) then - -- simple case, only spans one pixel local height + -- simple case, only spans one pixel local x = trunc(x_top) height = (sy1 - sy0) * e.direction STBTT_assert(x >= 0 and x < len) @@ -54673,8 +62118,25 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t -- compute intersection with y axis at x2 y_final = y_top + dy * (x2 - x0) + -- x1 x_top x2 x_bottom + -- y_top +------|-----+------------+------------+--------|---+------------+ + -- | | | | | | + -- | | | | | | + -- sy0 | Txxxxx|............|............|............|............| + -- y_crossing | *xxxxx.......|............|............|............| + -- | | xxxxx..|............|............|............| + -- | | /- xx*xxxx........|............|............| + -- | | dy < | xxxxxx..|............|............| + -- y_final | | \- | xx*xxx.........|............| + -- sy1 | | | | xxxxxB...|............| + -- | | | | | | + -- | | | | | | + -- y_bottom +------------+------------+------------+------------+------------+ + -- + -- goal is to measure the area covered by '.' in each pixel + -- if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 - -- TODO: maybe test against sy1 rather than y_bottom? + -- @TODO: maybe test against sy1 rather than y_bottom? if y_crossing > y_bottom then y_crossing = y_bottom end @@ -54696,6 +62158,16 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t end end + -- in second pixel, area covered by line segment found in first pixel + -- is always a rectangle 1 wide * the height of that line segment; this + -- is exactly what the variable 'area' stores. it also gets a contribution + -- from the line segment within it. the THIRD pixel will get the first + -- pixel's rectangle contribution, the second pixel's rectangle contribution, + -- and its own contribution. the 'own contribution' is the same in every pixel except + -- the leftmost and rightmost, a trapezoid that slides down in each pixel. + -- the second pixel's contribution to the third pixel will be the + -- rectangle 1 wide times the height change in the second pixel, which is dy. + step = sign * dy * 1 -- dy is dy/dx, change in y for every 1 change in x, -- which multiplied by 1-pixel-width is how much pixel area changes for each step in x -- so the area advances by 'step' every time @@ -54715,7 +62187,27 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t scanline_fill[x2 + 1] = scanline_fill[x2 + 1] + sign * (sy1 - sy0) end else + -- if edge goes outside of box we're drawing, we require + -- clipping logic. since this does not match the intended use + -- of this library, we use a different, very slow brute + -- force implementation + -- note though that this does happen some of the time because + -- x_top and x_bottom can be extrapolated at the top & bottom of + -- the shape and actually lie outside the bounding box for x = 0, len - 1 do + -- cases: + -- + -- there can be up to two intersections with the pixel. any intersection + -- with left or right edges can be handled by splitting into two (or three) + -- regions. intersections with top & bottom do not necessitate case-wise logic. + -- + -- the old way of doing this found the intersections with the left & right edges, + -- then used some simple logic to produce up to three segments in sorted order + -- from top-to-bottom. however, this had a problem: if an x edge was epsilon + -- across the x border, then the corresponding y position might not be distinct + -- from the other y segment, and it might ignored as an empty segment. to avoid + -- that, we need to explicitly produce segments based on x positions. + -- rename variables to clearly-defined pairs local y0 = y_top local x1 = x @@ -54759,6 +62251,7 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t end end +-- directly AA rasterize edges w/o supersampling --- @param result stbtt__bitmap --- @param e stbtt__edge --- @param n int @@ -54786,28 +62279,33 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of for i = 0, result.w - 1 do scanline[i] = 0 end for i = 0, result.w do scanline2[i] = 0 end + -- update all active edges; + -- remove all active edges that terminate before the top of this scanline local prev = nil local curr = active while curr do local next = curr.next if curr.ey <= scan_y_top then - if prev then prev.next = next + if prev then prev.next = next -- delete from list else active = next end curr.direction = 0 else - prev = curr + prev = curr -- advance through list end curr = next end + -- insert all edges that start before the bottom of this scanline local edge = e[p] while edge.y0 <= scan_y_bottom do if edge.y0 ~= edge.y1 then local z = stbtt__new_active(edge, off_x, scan_y_top) if j == 0 and off_y ~= 0 and z.ey < scan_y_top then + -- this can happen due to subpixel positioning and some kind of fp rounding error i think z.ey = scan_y_top end - STBTT_assert(z.ey >= scan_y_top) + STBTT_assert(z.ey >= scan_y_top) -- if we get really unlucky a tiny bit of an edge can be out of bounds + -- insert at front z.next = active active = z end @@ -54815,6 +62313,7 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of edge = e[p] end + -- now process all active edges if active then stbtt__fill_active_edges_new(scanline, scanline2, result.w, active, scan_y_top) end @@ -54833,10 +62332,11 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of end end + -- advance all the edges step = active while step do - step.fx = step.fx + step.fdx - step = step.next + step.fx = step.fx + step.fdx -- advance to position for current scanline + step = step.next -- advance through list end y = y + 1 @@ -54871,6 +62371,7 @@ end local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, shift_x, shift_y, off_x, off_y, invert) local y_scale_inv = (invert) and -scale_y or scale_y local vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2 + -- vsubsample should divide 255 evenly; otherwise we won't reach full opacity -- now we have to blow out the windings into explicit edge lists local n = 0 @@ -54938,8 +62439,7 @@ local function stbtt__add_point(points, n, x, y) points[n + 1].y = y end --- tessellate until threshold p is happy... --- TODO: warped to compensate for non-linear stretching +-- tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching --- @param points? stbtt__point[] --- @param num_points int --- @param x0 float @@ -54988,7 +62488,7 @@ end --- @param n int --- @return int num_points # updated num_points passed in local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2, x3, y3, objspace_flatness_squared, n) - -- TODO: this "flatness" calculation is just made-up nonsense that seems to work well enough + -- @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough local dx0 = x1 - x0 local dy0 = y1 - y0 local dx1 = x2 - x1 @@ -55031,6 +62531,7 @@ local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2 return num_points end +-- returns number of contours --- @param vertices stbtt_vertex[] --- @param num_verts int --- @param objspace_flatness float @@ -55107,6 +62608,7 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) return points, num_contours, contour_lengths end +-- rasterize a shape with quadratic beziers into a bitmap --- @param result stbtt__bitmap --- @param flatness_in_pixels float --- @param vertices stbtt_vertex[] @@ -55130,6 +62632,11 @@ local function stbtt_Rasterize(result, flatness_in_pixels, vertices, num_verts, end end +-- renders the glyph into storage you pass in for the bitmap, +-- in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap +-- is clipped to out_w/out_h bytes. Call stbtt_GetGlyphBitmapBox to get the +-- width and height and positioning info for it first. You can also specify +-- a subpixel shift for the character. --- @param info stbtt_fontinfo --- @param output unsigned_char[] --- @param out_w int @@ -55158,7 +62665,7 @@ end ----------------- ----------------- --- ---- Bitmap baking +--- bitmap baking --- --- @@ -55170,7 +62677,7 @@ end --------------------------- --------------------------- --- ---- Bitmap baking / packing +--- bitmap baking / packing --- --- @@ -55252,9 +62759,16 @@ local function stbtt__oversample_shift(oversample) if oversample == 0 then return 0.0 end + + -- The prefilter is a box filter of width "oversample", + -- which shifts phase by (oversample - 1)/2 pixels in + -- oversampled space. We want to shift in the opposite + -- direction to counter this. return -(oversample - 1) / (2.0 * oversample) end +-- same as stbtt_MakeGlyphBitmapSubpixel, but prefiltering +-- is performed. Returns (sub_x, sub_y). --- @param info stbtt_fontinfo --- @param output unsigned_char[] --- @param out_w int @@ -55287,7 +62801,7 @@ end ------------------- ------------------- --- ---- SDF computation +--- sdf computation --- --- @@ -55313,10 +62827,20 @@ end --- stbtt__matchpair --- stbtt__matches +-- Each .ttf/.ttc file may have more than one font. Each font has a sequential +-- index number starting from 0. Call this function to get the font offset for +-- a given index; it returns -1 if the index is out of range. A regular .ttf +-- file will only define one font and it always be at offset 0, so it will +-- return '0' for index 0, and -1 for all other indices. --- @param data table --- @param index int function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end +-- Given an offset into the file that defines a font, this function builds +-- the necessary cached info for the rest of the system. You must allocate +-- the stbtt_fontinfo yourself (see stbtt_fontinfo()), and stbtt_InitFont will fill it out. You don't +-- need to do anything special to free it, because the contents are pure +-- value data with no additional data structures. Returns false on failure. --- @param info stbtt_fontinfo --- @param data table --- @param offset int diff --git a/imgui.lua b/imgui.lua index c059795..32b0482 100644 --- a/imgui.lua +++ b/imgui.lua @@ -1,3 +1,419 @@ +-- dear imgui, v1.93 WIP (Luau port) +-- (main code and documentation) + +-- This file is a Lua/Luau port of Dear ImGui's imgui.cpp (docking branch, 1.93 WIP), following imgui.cpp function by function. +-- It runs on Roblox (Luau, primary target) and LÖVE (LuaJIT). Upstream documentation, examples and the demo apply almost directly. + +-- Help: +-- - Call and read ImGui.ShowDemoWindow() in imgui_demo.lua. All applications in examples/ are doing that. +-- - Read top of imgui.lua for more details, links and comments. +-- - ImVec2 and ImVec4 have arithmetic metamethods (a + b, a * 2.0, etc.); fields are .x, .y (.z, .w). +-- - See README.md "Differences from C++ Dear ImGui" for the Luau conventions (out-params become return values, flags enums, text buffers). + +-- Resources: +-- - FAQ ........................ https://dearimgui.com/faq (in upstream repository as docs/FAQ.md) +-- - Homepage ................... https://github.com/ocornut/imgui +-- - Releases & Changelog ....... https://github.com/ocornut/imgui/releases +-- - Gallery .................... https://github.com/ocornut/imgui/issues?q=label%3Agallery (please post your screenshots/video there!) +-- - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) +-- - Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started (how to integrate in an existing app by adding ~25 lines of code) +-- - Third-party Extensions https://github.com/ocornut/imgui/wiki/Useful-Extensions (ImPlot & many more) +-- - Bindings/Backends https://github.com/ocornut/imgui/wiki/Bindings (language bindings + backends for various tech/engines) +-- - Debug Tools https://github.com/ocornut/imgui/wiki/Debug-Tools +-- - Glossary https://github.com/ocornut/imgui/wiki/Glossary +-- - Software using Dear ImGui https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui +-- - Issues & support ........... https://github.com/ocornut/imgui/issues (upstream; for issues specific to this port, use this port's repository) +-- - Test Engine & Automation ... https://github.com/ocornut/imgui_test_engine (test suite, test engine to automate your apps) +-- - Web version of the Demo .... https://pthom.github.io/imgui_explorer (w/ source code browser) + +-- Copyright (c) 2014-2026 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. +-- Businesses: you can support continued development via B2B invoiced technical support, maintenance and sponsoring contracts. +-- PLEASE reach out at omar AT discohello DOT com. See https://github.com/ocornut/imgui/wiki/Funding +-- Businesses: you can also purchase licenses for the Dear ImGui Automation/Test Engine. +-- This port is unofficial and not affiliated with the Dear ImGui project; it is distributed under the same license. + +-- It is recommended that you don't modify imgui.lua! It will become difficult for you to update the library. +-- Note that 'ImGui' being a plain table, you can add functions into it from your own source files, without +-- modifying imgui.lua. You may use the internal functions and data structures (imgui_internal.lua), but they don't +-- come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you +-- to a better solution or official support for them. + +-- +-- Index of this file: +-- +-- DOCUMENTATION +-- +-- - MISSION STATEMENT +-- - CONTROLS GUIDE +-- - PROGRAMMER GUIDE +-- - READ FIRST +-- - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI +-- - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE +-- - HOW A SIMPLE APPLICATION 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) +-- +-- CODE +-- (search for "[SECTION]" in the code to find them) +-- +-- [SECTION] INCLUDES +-- [SECTION] FORWARD DECLARATIONS +-- [SECTION] CONTEXT AND MEMORY ALLOCATORS +-- [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO, ImGuiPlatformIO) +-- [SECTION] MISC HELPERS/UTILITIES (Geometry functions) +-- [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions) +-- [SECTION] MISC HELPERS/UTILITIES (File functions) +-- [SECTION] MISC HELPERS/UTILITIES (ImText* functions) +-- [SECTION] MISC HELPERS/UTILITIES (Color functions) +-- [SECTION] ImGuiStorage +-- [SECTION] ImGuiTextFilter +-- [SECTION] ImGuiTextBuffer, ImGuiTextIndex +-- [SECTION] ImGuiListClipper +-- [SECTION] STYLING +-- [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 +-- [SECTION] ITEM SUBMISSION +-- [SECTION] LAYOUT +-- [SECTION] SCROLLING +-- [SECTION] TOOLTIPS +-- [SECTION] POPUPS +-- [SECTION] WINDOW FOCUS +-- [SECTION] KEYBOARD/GAMEPAD NAVIGATION +-- [SECTION] DRAG AND DROP +-- [SECTION] LOGGING/CAPTURING +-- [SECTION] SETTINGS +-- [SECTION] LOCALIZATION +-- [SECTION] VIEWPORTS, PLATFORM WINDOWS +-- [SECTION] DOCKING +-- [SECTION] PLATFORM DEPENDENT HELPERS +-- [SECTION] METRICS/DEBUGGER WINDOW +-- [SECTION] DEBUG LOG WINDOW +-- [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL) +-- +-- (In this port, the sections keep upstream's names but may appear in a different order: +-- e.g. DRAG AND DROP and DOCKING are near the top of imgui.lua. Some are partial or empty, see docs/TODO.txt.) +-- + +------------------------------------------------------------------------------- +-- DOCUMENTATION +------------------------------------------------------------------------------- + +-- +-- MISSION STATEMENT +-- ================= +-- +-- - Easy to use to create code-driven and data-driven tools. +-- - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools. +-- - Easy to hack and improve. +-- - Minimize setup and maintenance. +-- - Minimize state storage on user side. +-- - Minimize state synchronization. +-- - Portable, minimize dependencies, run on target (consoles, phones, etc.). +-- - Efficient runtime and memory consumption. +-- +-- Designed primarily for developers and content-creators, not the typical end-user! +-- Some of the current weaknesses (which we aim to address in the future) includes: +-- +-- - Doesn't look fancy by default. +-- - Limited layout features, intricate layouts are typically crafted in code. +-- +-- +-- CONTROLS GUIDE +-- ============== +-- +-- - MOUSE CONTROLS +-- - Mouse wheel: Scroll vertically. +-- - Shift+Mouse wheel: Scroll horizontally. +-- - Click [X]: Close a window, available when an 'open' value is passed to ImGui.Begin() (open = ImGui.Begin(name, open)). +-- - Click ^, Double-Click title: Collapse window. +-- - Drag on corner/border: Resize window (double-click to auto fit window to its contents). +-- - Drag on any empty space: Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true). +-- - Left-click outside popup: Close popup stack (right-click over underlying popup: Partially close popup stack). +-- +-- - TEXT EDITOR +-- - Hold Shift or Drag Mouse: Select text. +-- - Ctrl+Left/Right: Word jump. +-- - Ctrl+Shift+Left/Right: Select words. +-- - Ctrl+A or Double-Click: Select All. +-- - Ctrl+X, Ctrl+C, Ctrl+V: Use OS clipboard (on Roblox, requires ImGui_ImplRoblox.SetTextProxy(true)). +-- - Ctrl+Z Undo. +-- - Ctrl+Y or Ctrl+Shift+Z: Redo. +-- - ESCAPE: Revert text to its original value. +-- - On macOS, controls are automatically adjusted to match standard macOS text editing and behaviors. +-- (for 99% of shortcuts, Ctrl is replaced by Cmd on macOS). +-- +-- - KEYBOARD CONTROLS +-- - Basic: +-- - Tab, Shift+Tab Cycle through text editable fields. +-- - Ctrl+Tab, Ctrl+Shift+Tab Cycle through windows. +-- - Ctrl+Click Input text into a Slider or Drag widget. +-- - Extended features with `io.ConfigFlags = bit32.bor(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard)`: +-- - Tab, Shift+Tab: Cycle through every items. +-- - Arrow keys Move through items using directional navigation. Tweak value. +-- - Arrow keys + Alt, Shift Tweak slower, tweak faster (when using arrow keys). +-- - Enter Activate item (prefer text input when possible). +-- - Space Activate item (prefer tweaking with arrows when possible). +-- - Escape Deactivate item, leave child window, close popup. +-- - Page Up, Page Down Previous page, next page. +-- - Home, End Scroll to top, scroll to bottom. +-- - Alt Toggle between scrolling layer and menu layer. +-- - Ctrl+Tab then Ctrl+Arrows Move window. Hold Shift to resize instead of moving. +-- - Menu or Shift+F10 Open context menu. +-- - Output when ImGuiConfigFlags.NavEnableKeyboard set, +-- - io.WantCaptureKeyboard flag is set when keyboard is claimed. +-- - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags.NoNavInputs flag set. +-- - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used). +-- +-- - GAMEPAD CONTROLS +-- - Enable with 'io.ConfigFlags = bit32.bor(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad)'. +-- - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse! +-- - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets +-- - Backend support: backend needs to: +-- - Set 'io.BackendFlags = bit32.bor(io.BackendFlags, ImGuiBackendFlags.HasGamepad)' + call io:AddKeyEvent()/io:AddKeyAnalogEvent() with ImGuiKey.GamepadXXX keys. +-- - For analog values (0.0 to 1.0), 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.). +-- - (The Roblox and LÖVE backends of this port currently handle mouse and keyboard only: gamepad and touch are not wired up yet.) +-- - 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. +-- +-- - REMOTE INPUTS SHARING & MOUSE EMULATION +-- - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions. +-- - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the io.ConfigNavMoveSetMousePos flag. +-- Enabling io.ConfigNavMoveSetMousePos + ImGuiBackendFlags.HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements. +-- When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved. +-- When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. +-- (If you set the io.ConfigNavMoveSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!) +-- +-- +-- PROGRAMMER GUIDE +-- ================ +-- +-- READ FIRST +-- ---------- +-- - Remember to check the wonderful Wiki: https://github.com/ocornut/imgui/wiki +-- - Your code creates the UI every frame of your application loop, if your code doesn't run the UI is gone! +-- The UI can be highly dynamic, there are no construction or destruction steps, less superfluous +-- data retention on your side, less state duplication, less state synchronization, fewer bugs. +-- - Call and read ImGui.ShowDemoWindow() for demo code demonstrating most features (imgui_demo.lua, a port of imgui_demo.cpp). +-- Or browse pthom's online imgui_explorer: https://pthom.github.io/imgui_explorer for a web version w/ source code browser. +-- - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori). +-- You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki. +-- - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances. +-- For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI, +-- where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches. +-- - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right. +-- - IM_ASSERT() is used throughout the code, like upstream. +-- If you get an assert, read the messages and comments around the assert. +-- - This codebase aims to be highly optimized: +-- - A typical idle frame should allocate as little as possible (in Luau: avoid creating tables/closures per frame). +-- - We rely on a maximum of constant-time or O(N) algorithms. Limiting searches/scans as much as possible. +-- - This codebase aims to be both highly opinionated and highly flexible: +-- - This code works because of the things it choose to solve or not solve. +-- - The port keeps upstream's structure (ImGui is a table of free functions, structures are plain tables) +-- so that upstream code, comments and documentation map almost 1:1. See docs/PORTING.md for the porting rules. +-- +-- +-- HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI +-- ---------------------------------------------- +-- - Update by re-pulling this repository (or updating the Wally package / downloading a newer release), +-- then rebuild the bundle (python3 tools/bundle.py, or --target love) and overwrite every file. +-- - This port tracks upstream; read upstream's "API BREAKING CHANGES" (see below) when the tracked upstream version changes. +-- If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed +-- from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will +-- likely be a comment about it. Please report any issue to the GitHub page! +-- - Try to keep your copy of Dear ImGui reasonably up to date! +-- +-- +-- GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE +-- --------------------------------------------------------------- +-- - See https://github.com/ocornut/imgui/wiki/Getting-Started, and README.md of this repository. +-- - Run and study the examples and demo in imgui_demo.lua to get acquainted with the library. +-- - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder +-- (backends/imgui_impl_roblox.lua for Roblox, backends/imgui_impl_love.lua for LÖVE). +-- - Build a single file with tools/bundle.py: build/ImGui.luau (Roblox ModuleScript) or build/imgui_love.lua (LÖVE), +-- then require() / load it. All exported names (ImGui, ImVec2, ImVec4, IM_COL32, every ImGui*Flags enum...) are fields of the returned table. +-- - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. +-- - Dear ImGui never touches or knows about your GPU state. The only function that knows about rendering is the draw function that you provide (the backend's RenderDrawData). +-- Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" +-- phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui.Render(). +-- - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code. +-- +-- +-- HOW A SIMPLE APPLICATION MAY LOOK LIKE +-- -------------------------------------- +-- +-- USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.lua files from the backends/ folder). +-- The sub-folders in examples/ contain examples applications following this structure. +-- +-- Roblox (LocalScript, see examples/example_roblox/main.client.luau): +-- +-- local G = require(ReplicatedStorage:WaitForChild("ImGui")) +-- local ImGui, ImGui_ImplRoblox = G.ImGui, G.ImGui_ImplRoblox +-- +-- -- Application init: create a dear imgui context, setup some options, load fonts +-- ImGui.CreateContext() +-- local io = ImGui.GetIO() +-- -- TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags = bit32.bor(io.ConfigFlags, G.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. +-- +-- -- Initialize helper Platform and Renderer backend (here we are using imgui_impl_roblox.lua) +-- ImGui_ImplRoblox.Init() +-- +-- -- Application main loop +-- RunService.Stepped:Connect(function() +-- -- Feed inputs to dear imgui, start new frame +-- ImGui_ImplRoblox.NewFrame() +-- ImGui.NewFrame() +-- +-- -- Any application code here +-- ImGui.Text("Hello, world!") +-- +-- -- Render dear imgui +-- ImGui.Render() +-- ImGui_ImplRoblox.RenderDrawData(ImGui.GetDrawData()) +-- end) +-- +-- -- Shutdown +-- ImGui_ImplRoblox.Shutdown() +-- ImGui.DestroyContext() +-- +-- LÖVE (see examples/example_love/main.lua): +-- +-- function love.load() +-- ImGui.CreateContext() +-- G.ImGui_ImplLove.Init({ root = ROOT }) +-- end +-- function love.update(dt) +-- G.ImGui_ImplLove.NewFrame() +-- ImGui.NewFrame() +-- ImGui.Text("Hello, world!") +-- ImGui.Render() +-- end +-- function love.draw() +-- G.ImGui_ImplLove.RenderDrawData(ImGui.GetDrawData()) +-- end +-- -- + forward love.mousemoved/mousepressed/mousereleased/wheelmoved/keypressed/keyreleased/textinput/focus +-- -- to G.ImGui_ImplLove.MouseMoved/MousePressed/MouseReleased/WheelMoved/KeyPressed/KeyReleased/TextInput/Focus. +-- +-- 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. +-- +-- +-- USAGE +-- ----- +-- +-- Widget functions are called every frame; their return values tell you what the user did. +-- Out-parameters of the C++ API (bool* p_open, float* v, int* v...) are passed by value and the new value is returned: +-- +-- ImGui.Text("Hello, world %d", 123) +-- if ImGui.Button("Save") then +-- MySaveFunction() +-- end +-- ImGui.InputText("string", buf, 256) -- buf = ImGui.NewTextBuffer("...", 256), edited in place +-- f = ImGui.SliderFloat("float", f, 0.0, 1.0) -- returns (value, changed) +-- pressed, v = ImGui.Checkbox("checkbox", v) +-- +-- -- Create a window called "My First Tool", with a menu bar. +-- my_tool_active = ImGui.Begin("My First Tool", my_tool_active, ImGuiWindowFlags.MenuBar) -- returns (open, visible) +-- if ImGui.BeginMenuBar() then +-- if ImGui.BeginMenu("File") then +-- if ImGui.MenuItem("Close", "Ctrl+W") then my_tool_active = false end +-- ImGui.EndMenu() +-- end +-- ImGui.EndMenuBar() +-- end +-- ImGui.ColorEdit4("Color", my_color) -- ImVec4 / arrays are edited in place +-- ImGui.End() +-- +-- +-- USING CUSTOM BACKEND / CUSTOM ENGINE +-- ------------------------------------ +-- +-- A backend implements the usual Dear ImGui contract: Init, NewFrame, RenderDrawData, inputs -> io:AddXXXEvent(), +-- texture updates via ImTextureData. Adding another Lua host means a new backends/imgui_impl_.lua. +-- -> see https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md for basic instructions. +-- -> the backends in backends/imgui_impl_roblox.lua and backends/imgui_impl_love.lua are complete implementations. +-- +-- Basic application/backend skeleton: +-- +-- -- Application init: create a Dear ImGui context, setup some options, load fonts +-- ImGui.CreateContext() +-- local io = ImGui.GetIO() +-- -- TODO: set io.ConfigXXX values, e.g. +-- io.ConfigFlags = bit32.bor(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) -- Enable keyboard controls +-- +-- -- TODO: Load TTF/OTF fonts if you don't want to use the default font. +-- io.Fonts:AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0) +-- +-- -- Application main loop (called once per frame) +-- local function OnFrame(dt) +-- -- Setup low-level inputs, or write to those fields from your input event handlers, etc. +-- -- (In the examples/ app this is usually done within the ImGui_ImplXXX.NewFrame() function from one of the Backends) +-- io.DeltaTime = dt -- set the time elapsed since the previous frame (in seconds) +-- io.DisplaySize.x = 1920.0 -- set the current display width +-- io.DisplaySize.y = 1280.0 -- set the current display height here +-- io:AddMousePosEvent(mouse_x, mouse_y) -- update mouse position +-- io:AddMouseButtonEvent(0, mouse_b0) -- update mouse button states +-- io:AddMouseButtonEvent(1, mouse_b1) -- update mouse button states +-- +-- -- Call NewFrame(), after this point you can use ImGui.* functions anytime +-- -- (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere) +-- ImGui.NewFrame() +-- +-- -- Most of your application code here +-- ImGui.Text("Hello, world!") +-- 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! +-- +-- -- 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() -- this is automatically called by Render(), but available +-- ImGui.Render() +-- +-- -- Update textures +-- local draw_data = ImGui.GetDrawData() +-- for _, tex in draw_data.Textures:iter() do +-- if tex.Status ~= ImTextureStatus.OK then +-- MyImGuiBackend_UpdateTexture(tex) +-- end +-- end +-- +-- -- Render dear imgui contents +-- MyImGuiBackend_RenderDrawData(draw_data) +-- end +-- +-- -- Shutdown +-- ImGui.DestroyContext() +-- +-- +-- +-- API BREAKING CHANGES +-- ==================== +-- +-- This port tracks upstream Dear ImGui 1.93 WIP (docking branch). +-- For the change-log of API breaking changes, see the top of upstream imgui.cpp, or https://github.com/ocornut/imgui/releases +-- +-- +-- FREQUENTLY ASKED QUESTIONS (FAQ) +-- ================================ +-- +-- Read all answers online: +-- https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url) +-- For questions specific to this port (Roblox, LÖVE, performance, differences from C++), see the FAQ in README.md of this repository. +-- + --- Dear ImGui WIP -- (Core Code) @@ -9,6 +425,9 @@ IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS = true -- Don't implement ImStd.ImFileOpen/ IMGUI_DISABLE_DEBUG_TOOLS = false -- Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowIDStackToolWindow() will be empty +-- Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be ~= nil. +-- - ImGui.CreateContext() will automatically set this pointer if it is nil. +-- Change to a different context by calling ImGui.SetCurrentContext(). --- @type ImGuiContext? local GImGui = nil @@ -26,10 +445,13 @@ local function LUA_TableConstructorWrapper(T, size, userdata) return p end +-- Memory Allocator functions. Use SetAllocatorFunctions() to change them. +-- - You probably don't want to modify that mid-program. local GImAllocatorAllocFunc = LUA_TableConstructorWrapper local GImAllocatorFreeFunc = function(p0, p1, p2) end local GImAllocatorUserData = nil +-- IM_ALLOC() == ImGui.MemAlloc() --- @param constructor function --- @param size int function ImGui.MemAlloc(constructor, size) @@ -41,6 +463,7 @@ function ImGui.MemAlloc(constructor, size) return p end +-- IM_FREE() == ImGui.MemFree() -- This does not set `owner[field]` to nil! --- @param owner table --- @param field string|int @@ -54,6 +477,7 @@ function ImGui.MemFree(owner, field) return GImAllocatorFreeFunc(owner, field, GImAllocatorUserData) end +-- We record the number of allocation in recent frames, as a way to audit/sanitize our guiding principles of "no allocations on idle/repeating frames" --- @param info ImGuiDebugAllocInfo --- @param frame_count int --- @param ptr table @@ -94,6 +518,10 @@ do --[[ [SECTION] imgui_dragdrop (was imgui_dragdrop.lua) ]] -- Drag and drop: 1:1 port of imgui.cpp [SECTION] DRAG AND DROP (docking branch) -- Payload `Data` is any Lua value (no copy is made). `data_size` is optional and only kept for API parity. +------------------------------------------------------------------------------- +-- [SECTION] DRAG AND DROP +------------------------------------------------------------------------------- + function ImGui.IsDragDropActive() return ImGui.GetCurrentContext().DragDropActive end @@ -109,11 +537,20 @@ function ImGui.ClearDragDrop() g.DragDropAcceptFrameCount = -1 end +-- When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource() +-- If the item has an identifier: +-- - This assume/require the item to be activated (typically via ButtonBehavior). +-- - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button. +-- - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag. +-- If the item has no identifier: +-- - Currently always assume left mouse button. function ImGui.BeginDragDropSource(flags) if flags == nil then flags = 0 end local g = ImGui.GetCurrentContext() local window = g.CurrentWindow + -- FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button, + -- in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic). local mouse_button = ImGuiMouseButton.Left local source_drag_active = false @@ -122,19 +559,30 @@ function ImGui.BeginDragDropSource(flags) if bit32.band(flags, ImGuiDragDropFlags.SourceExtern) == 0 then source_id = g.LastItemData.ID if source_id ~= 0 then + -- Common path: items with ID if g.ActiveId ~= source_id then return false end if g.ActiveIdMouseButton ~= -1 then mouse_button = g.ActiveIdMouseButton end if g.IO.MouseDown[mouse_button] == false or window.SkipItems then return false end g.ActiveIdAllowOverlap = false else + -- Uncommon path: items without ID if g.IO.MouseDown[mouse_button] == false or window.SkipItems then return false end if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) == 0 and (g.ActiveId == 0 or g.ActiveIdWindow ~= window) then return false end + + -- If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to: + -- A) Read the explanation below, B) Use the ImGuiDragDropFlags.SourceAllowNullID flag. if bit32.band(flags, ImGuiDragDropFlags.SourceAllowNullID) == 0 then IM_ASSERT(false, "Use ImGuiDragDropFlags.SourceAllowNullID for items without an ID") return false end + + -- Magic fallback to handle items with no assigned ID, e.g. Text(), Image() + -- We build a throwaway ID based on current ID stack + relative AABB of items in window. + -- THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZING OF THE WIDGET, so if your widget moves your dragging operation will be canceled. + -- We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive. + -- Rely on keeping other window.LastItemXXX fields intact. source_id = window:GetIDFromRectangle(g.LastItemData.Rect) g.LastItemData.ID = source_id ImGui.KeepAliveID(source_id) @@ -143,14 +591,16 @@ function ImGui.BeginDragDropSource(flags) ImGui.SetActiveID(source_id, window) ImGui.FocusWindow(window) end - if g.ActiveId == source_id then g.ActiveIdAllowOverlap = is_hovered end + if g.ActiveId == source_id then g.ActiveIdAllowOverlap = is_hovered end -- Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker. end if g.ActiveId ~= source_id then return false end source_parent_id = window.IDStack.Data[window.IDStack.Size] source_drag_active = ImGui.IsMouseDragging(mouse_button) + -- Disable navigation and key inputs while dragging + cancel existing request if any ImGui.SetActiveIdUsingAllKeyboardKeys() else + -- When ImGuiDragDropFlags.SourceExtern is set: window = nil source_id = ImHashStr("#SourceExtern") source_drag_active = true @@ -159,9 +609,10 @@ function ImGui.BeginDragDropSource(flags) ImGui.SetActiveID(source_id, nil) end - IM_ASSERT(g.DragDropWithinTarget == false) + IM_ASSERT(g.DragDropWithinTarget == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() if not source_drag_active then return false end + -- Activate drag and drop if not g.DragDropActive then IM_ASSERT(source_id ~= 0) ImGui.ClearDragDrop() @@ -177,13 +628,15 @@ function ImGui.BeginDragDropSource(flags) g.DragDropWithinSource = true if bit32.band(flags, ImGuiDragDropFlags.SourceNoPreviewTooltip) == 0 then + -- Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit) + -- We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents. local ret if g.DragDropAcceptIdPrev ~= 0 and bit32.band(g.DragDropAcceptFlagsPrev, ImGuiDragDropFlags.AcceptNoPreviewTooltip) ~= 0 then ret = ImGui.BeginTooltipHidden() else ret = ImGui.BeginTooltip() end - IM_ASSERT(ret) + IM_ASSERT(ret) -- FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", nil, ImGuiWindowFlags.NoSavedSettings) + SetWindowHiddenAndSkipItemsForCurrentFrame(). end if bit32.band(flags, ImGuiDragDropFlags.SourceNoDisableHover) == 0 and bit32.band(flags, ImGuiDragDropFlags.SourceExtern) == 0 then @@ -201,10 +654,12 @@ function ImGui.EndDragDropSource() ImGui.EndTooltip() end + -- Discard the drag if have not called SetDragDropPayload() if g.DragDropPayload.DataFrameCount == -1 then ImGui.ClearDragDrop() end g.DragDropWithinSource = false end +-- Use 'cond' to choose to submit payload on drag start or every frame --- @param data any # any Lua value --- @return bool accepted function ImGui.SetDragDropPayload(type, data, data_size, cond) @@ -215,15 +670,17 @@ function ImGui.SetDragDropPayload(type, data, data_size, cond) IM_ASSERT(type ~= nil) IM_ASSERT(#type < 32, "Payload type can be at most 32 characters long") IM_ASSERT(cond == ImGuiCond.Always or cond == ImGuiCond.Once) - IM_ASSERT(payload.SourceId ~= 0) + IM_ASSERT(payload.SourceId ~= 0) -- Not called between BeginDragDropSource() and EndDragDropSource() if cond == ImGuiCond.Always or payload.DataFrameCount == -1 then + -- Copy payload payload.DataType = type payload.Data = data payload.DataSize = data_size or ((data ~= nil) and 1 or 0) end payload.DataFrameCount = g.FrameCount + -- Return whether the payload has been accepted return (g.DragDropAcceptFrameCount == g.FrameCount) or (g.DragDropAcceptFrameCount == g.FrameCount - 1) end @@ -238,15 +695,19 @@ function ImGui.BeginDragDropTargetCustom(bb, id) if not ImGui.IsMouseHoveringRect(bb.Min, bb.Max) or (id == g.DragDropPayload.SourceId) then return false end if window.SkipItems then return false end - IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) + IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() g.DragDropTargetRect = ImRect(bb.Min, bb.Max) - g.DragDropTargetClipRect = ImRect(window.ClipRect.Min, window.ClipRect.Max) + g.DragDropTargetClipRect = ImRect(window.ClipRect.Min, window.ClipRect.Max) -- May want to be overridden by user depending on use case? g.DragDropTargetId = id g.DragDropTargetFullViewport = 0 g.DragDropWithinTarget = true return true end +-- Typical usage would be: +-- if not ImGui.IsWindowHovered(bit32.bor(ImGuiHoveredFlags.AnyWindow, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem)) then +-- if ImGui.BeginDragDropTargetViewport(ImGui.GetMainViewport(), nil) then +-- But we are leaving the hover test to the caller for maximum flexibility. function ImGui.BeginDragDropTargetViewport(viewport, p_bb) local g = ImGui.GetCurrentContext() if not g.DragDropActive then return false end @@ -257,7 +718,7 @@ function ImGui.BeginDragDropTargetViewport(viewport, p_bb) return false end - IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) + IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() g.DragDropTargetRect = ImRect(bb.Min, bb.Max) g.DragDropTargetClipRect = ImRect(bb.Min, bb.Max) g.DragDropTargetId = id @@ -266,6 +727,10 @@ function ImGui.BeginDragDropTargetViewport(viewport, p_bb) return true end +-- We don't use BeginDragDropTargetCustom() and duplicate its code because: +-- 1) we use LastItemData's ImGuiItemStatusFlags.HoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them. +-- 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can. +-- Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case) function ImGui.BeginDragDropTarget() local g = ImGui.GetCurrentContext() if not g.DragDropActive then return false end @@ -283,7 +748,7 @@ function ImGui.BeginDragDropTarget() end if g.DragDropPayload.SourceId == id then return false end - IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) + IM_ASSERT(g.DragDropWithinTarget == false and g.DragDropWithinSource == false) -- Can't nest BeginDragDropSource() and BeginDragDropTarget() g.DragDropTargetRect = ImRect(display_rect.Min, display_rect.Max) local clip = (bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasClipRect) ~= 0) and g.LastItemData.ClipRect or window.ClipRect g.DragDropTargetClipRect = ImRect(clip.Min, clip.Max) @@ -302,10 +767,12 @@ function ImGui.AcceptDragDropPayload(type, flags) if flags == nil then flags = 0 end local g = ImGui.GetCurrentContext() local payload = g.DragDropPayload - IM_ASSERT(g.DragDropActive) - IM_ASSERT(payload.DataFrameCount ~= -1) + IM_ASSERT(g.DragDropActive) -- Not called between BeginDragDropTarget() and EndDragDropTarget() ? + IM_ASSERT(payload.DataFrameCount ~= -1) -- Forgot to call EndDragDropTarget() ? if type ~= nil and not ImGuiPayload_IsDataType(payload, type) then return nil end + -- Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints. + -- NB: We currently accept nil id as target. However, overlapping targets requires a unique ID to function! local was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId) local r = g.DragDropTargetRect local r_surface = r:GetWidth() * r:GetHeight() @@ -314,9 +781,11 @@ function ImGui.AcceptDragDropPayload(type, flags) g.DragDropAcceptFlagsCurr = flags g.DragDropAcceptIdCurr = g.DragDropTargetId g.DragDropAcceptIdCurrRectSurface = r_surface + -- IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId) + -- Render default drop visuals payload.Preview = was_accepted_previously - flags = bit32.bor(flags, bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.AcceptNoDrawDefaultRect)) + flags = bit32.bor(flags, bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.AcceptNoDrawDefaultRect)) -- Source can also inhibit the preview (useful for external sources that live for 1 frame) local draw_target_rect = payload.Preview and bit32.band(flags, ImGuiDragDropFlags.AcceptNoDrawDefaultRect) == 0 if draw_target_rect and g.DragDropTargetFullViewport ~= 0 then ImGui.RenderDragDropTargetRectForViewport(g.DragDropTargetFullViewport, g.DragDropTargetRect) @@ -328,17 +797,18 @@ function ImGui.AcceptDragDropPayload(type, flags) if bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceExtern) ~= 0 and g.DragDropMouseButton == -1 then payload.Delivery = was_accepted_previously and (g.DragDropSourceFrameCount < g.FrameCount) else - payload.Delivery = was_accepted_previously and not ImGui.IsMouseDown(g.DragDropMouseButton) + payload.Delivery = was_accepted_previously and not ImGui.IsMouseDown(g.DragDropMouseButton) -- For extern drag sources affecting OS window focus, it's easier to just test not IsMouseDown() instead of IsMouseReleased() end if not payload.Delivery and bit32.band(flags, ImGuiDragDropFlags.AcceptBeforeDelivery) == 0 then return nil end return payload end +-- FIXME-STYLE FIXME-DRAGDROP: Settle on a proper default visuals for drop target. function ImGui.RenderDragDropTargetRectForItem(bb) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow local bb_display = ImRect(bb.Min, bb.Max) - bb_display:ClipWith(g.DragDropTargetClipRect) + bb_display:ClipWith(g.DragDropTargetClipRect) -- Clip THEN expand so we have a way to visualize that target is not entirely visible. bb_display:Expand(g.Style.DragDropTargetPadding) local push_clip_rect = not window.ClipRect:Contains(bb_display) if push_clip_rect then window.DrawList:PushClipRectFullScreen() end @@ -372,6 +842,8 @@ function ImGui.EndDragDropTarget() IM_ASSERT(g.DragDropActive) IM_ASSERT(g.DragDropWithinTarget) g.DragDropWithinTarget = false + + -- Clear drag and drop state payload right after delivery if g.DragDropPayload.Delivery then ImGui.ClearDragDrop() end end @@ -391,54 +863,129 @@ do --[[ [SECTION] imgui_docking (was imgui_docking.lua) ]] -- - node.ChildNodes is a table indexed [0] and [1] like upstream. -- - ImGuiDockPreviewData.DropRectsDraw is indexed [dir + 1] with dir in -1..3 (so keys 0..4), like upstream. +------------------------------------------------------------------------------- +-- [SECTION] DOCKING +------------------------------------------------------------------------------- +-- Docking: Internal Types +-- Docking: Forward Declarations +-- Docking: ImGuiDockContext +-- Docking: ImGuiDockContext Docking/Undocking functions +-- Docking: ImGuiDockNode +-- Docking: ImGuiDockNode Tree manipulation functions +-- Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) +-- Docking: Builder Functions +-- Docking: Begin/End Support Functions (called from Begin/End) +-- Docking: Settings +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- Typical Docking call flow: (root level is generally public API): +------------------------------------------------------------------------------- +-- - NewFrame() new dear imgui frame +-- | DockContextNewFrameUpdateUndocking() - process queued undocking requests +-- | - DockContextProcessUndockWindow() - process one window undocking request +-- | - DockContextProcessUndockNode() - process one whole node undocking request +-- | DockContextNewFrameUpdateUndocking() - process queue docking requests, create floating dock nodes +-- | - update g.HoveredDockNode - [debug] update node hovered by mouse +-- | - DockContextProcessDock() - process one docking request +-- | - DockNodeUpdate() +-- | - DockNodeUpdateForRootNode() +-- | - DockNodeUpdateFlagsAndCollapse() +-- | - DockNodeFindInfo() +-- | - destroy unused node or tab bar +-- | - create dock node host window +-- | - Begin() etc. +-- | - DockNodeStartMouseMovingWindow() +-- | - DockNodeTreeUpdatePosSize() +-- | - DockNodeTreeUpdateSplitter() +-- | - draw node background +-- | - DockNodeUpdateTabBar() - create/update tab bar for a docking node +-- | - DockNodeAddTabBar() +-- | - DockNodeWindowMenuUpdate() +-- | - DockNodeCalcTabBarLayout() +-- | - BeginTabBarEx() +-- | - TabItemEx() calls +-- | - EndTabBar() +-- | - BeginDockableDragDropTarget() +-- | - DockNodeUpdate() - recurse into child nodes... +------------------------------------------------------------------------------- +-- - DockSpace() user submit a dockspace into a window +-- | Begin(Child) - create a child window +-- | DockNodeUpdate() - call main dock node update function +-- | End(Child) +-- | ItemSize() +------------------------------------------------------------------------------- +-- - Begin() +-- | BeginDocked() +-- | BeginDockableDragDropSource() +-- | BeginDockableDragDropTarget() +-- | - DockNodePreviewDockRender() +------------------------------------------------------------------------------- +-- - EndFrame() +-- | DockContextEndFrame() +------------------------------------------------------------------------------- + local MT = ImGui.GetMetatables() -IMGUI_PAYLOAD_TYPE_WINDOW = "_IMWINDOW" +IMGUI_PAYLOAD_TYPE_WINDOW = "_IMWINDOW" -- Payload == ImGuiWindow local DOCKING_HOST_DRAW_CHANNEL_BG = 0 -- Dock host: background fill local DOCKING_HOST_DRAW_CHANNEL_FG = 1 -- Dock host: decorations and contents local DOCKING_SPLITTER_SIZE = 2.0 ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: flags & enums ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Flags for ImGui.DockSpace(), shared/inherited by child nodes. +-- (Some flags can be applied to individual nodes directly) +-- FIXME-DOCK: Also see ImGuiDockNodeFlagsPrivate_ which may involve using the WIP and internal DockBuilder api. ImGuiDockNodeFlags = { None = 0, - KeepAliveOnly = bit32.lshift(1, 0), - NoDockingOverCentralNode = bit32.lshift(1, 2), - PassthruCentralNode = bit32.lshift(1, 3), - NoDockingSplit = bit32.lshift(1, 4), - NoResize = bit32.lshift(1, 5), - AutoHideTabBar = bit32.lshift(1, 6), - NoUndocking = bit32.lshift(1, 7), + KeepAliveOnly = bit32.lshift(1, 0), -- -- Don't display the dockspace node but keep it alive. Windows docked into this dockspace node won't be undocked. + -- NoCentralNode = bit32.lshift(1, 1), -- -- Disable Central Node (the node which can stay empty) + NoDockingOverCentralNode = bit32.lshift(1, 2), -- -- Disable docking over the Central Node, which will be always kept empty. + PassthruCentralNode = bit32.lshift(1, 3), -- -- Enable passthru dockspace: 1) DockSpace() will render a ImGuiCol.WindowBg background covering everything excepted the Central Node when empty. Meaning the host window should probably use SetNextWindowBgAlpha(0.0) prior to Begin() when using this. 2) When Central Node is empty: let inputs pass-through + won't display a DockingEmptyBg background. See demo for details. + NoDockingSplit = bit32.lshift(1, 4), -- -- Disable other windows/nodes from splitting this node. + NoResize = bit32.lshift(1, 5), -- Saved -- Disable resizing node using the splitter/separators. Useful with programmatically setup dockspaces. + AutoHideTabBar = bit32.lshift(1, 6), -- -- Tab bar will automatically hide when there is a single window in the dock node. + NoUndocking = bit32.lshift(1, 7), -- -- Disable undocking this node. + + -- Extend ImGuiDockNodeFlags_ (ImGuiDockNodeFlagsPrivate_) -- [Internal] - DockSpace = bit32.lshift(1, 10), - CentralNode = bit32.lshift(1, 11), - NoTabBar = bit32.lshift(1, 12), - HiddenTabBar = bit32.lshift(1, 13), - NoWindowMenuButton = bit32.lshift(1, 14), - NoCloseButton = bit32.lshift(1, 15), - NoResizeX = bit32.lshift(1, 16), - NoResizeY = bit32.lshift(1, 17), - DockedWindowsInFocusRoute = bit32.lshift(1, 18), - NoDockingSplitOther = bit32.lshift(1, 19), - NoDockingOverMe = bit32.lshift(1, 20), - NoDockingOverOther = bit32.lshift(1, 21), - NoDockingOverEmpty = bit32.lshift(1, 22), + DockSpace = bit32.lshift(1, 10), -- Saved -- A dockspace is a node that occupy space within an existing user window. Otherwise the node is floating and create its own window. + CentralNode = bit32.lshift(1, 11), -- Saved -- The central node has 2 main properties: stay visible when empty, only use "remaining" spaces from its neighbor. + NoTabBar = bit32.lshift(1, 12), -- Saved -- Tab bar is completely unavailable. No triangle in the corner to enable it back. + HiddenTabBar = bit32.lshift(1, 13), -- Saved -- Tab bar is hidden, with a triangle in the corner to show it again (NB: actual tab-bar instance may be destroyed as this is only used for single-window tab bar) + NoWindowMenuButton = bit32.lshift(1, 14), -- Saved -- Disable window/docking menu (that one that appears instead of the collapse button) + NoCloseButton = bit32.lshift(1, 15), -- Saved -- Disable close button + NoResizeX = bit32.lshift(1, 16), -- -- + NoResizeY = bit32.lshift(1, 17), -- -- + DockedWindowsInFocusRoute = bit32.lshift(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. + NoDockingSplitOther = bit32.lshift(1, 19), -- -- Disable this node from splitting other windows/nodes. + NoDockingOverMe = bit32.lshift(1, 20), -- -- Disable other windows/nodes from being docked over this node. + NoDockingOverOther = bit32.lshift(1, 21), -- -- Disable this node from being docked over another window or non-empty node. + NoDockingOverEmpty = bit32.lshift(1, 22), -- -- Disable this node from being docked over an empty node (e.g. DockSpace with no other windows) } do local F = ImGuiDockNodeFlags - F.NoSplit = F.NoDockingSplit - F.NoDockingInCentralNode = F.NoDockingOverCentralNode + F.NoSplit = F.NoDockingSplit -- Renamed in 1.90 + F.NoDockingInCentralNode = F.NoDockingOverCentralNode -- Renamed in 1.90 F.NoDocking = bit32.bor(F.NoDockingOverMe, F.NoDockingOverOther, F.NoDockingOverEmpty, F.NoDockingSplit, F.NoDockingSplitOther) + -- Masks F.SharedFlagsInheritMask_ = 0xFFFFFFFF F.NoResizeFlagsMask_ = bit32.bor(F.NoResize, F.NoResizeX, F.NoResizeY) + -- When splitting, those local flags are moved to the inheriting child, never duplicated F.LocalFlagsTransferMask_ = bit32.bor(F.NoDockingSplit, F.NoResizeFlagsMask_, F.AutoHideTabBar, F.CentralNode, F.NoTabBar, F.HiddenTabBar, F.NoWindowMenuButton, F.NoCloseButton) F.SavedFlagsMask_ = bit32.bor(F.NoResizeFlagsMask_, F.DockSpace, F.CentralNode, F.NoTabBar, F.HiddenTabBar, F.NoWindowMenuButton, F.NoCloseButton) end +-- Store the source authority (dock node vs window) of a field ImGuiDataAuthority = { Auto = 0, DockNode = 1, Window = 2 } ImGuiDockNodeState = { @@ -448,35 +995,50 @@ ImGuiDockNodeState = { HostWindowVisible = 3, } +-- List of colors that are stored at the time of Begin() into Docked Windows. +-- We currently store the packed colors in a simple array window.DockStyle.Colors[]. +-- A better solution may involve appending into a log of colors in ImGuiContext + store offsets into those arrays in ImGuiWindow, +-- but it would be more complex as we'd need to double-buffer both as e.g. drop target may refer to window from last frame. ImGuiWindowDockStyleCol = { Text = 0, TabHovered = 1, TabFocused = 2, TabSelected = 3, TabSelectedOverline = 4, TabDimmed = 5, TabDimmedSelected = 6, TabDimmedSelectedOverline = 7, UnsavedMarker = 8, COUNT = 9, } -local ImGuiDockRequestType = { None = 0, Dock = 1, Undock = 2, Split = 3 } - ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Internal Types ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - ImGuiDockRequestType +-- - ImGuiDockRequest +-- - ImGuiDockPreviewData +-- - ImGuiDockNodeSettings +-- - ImGuiDockContext +------------------------------------------------------------------------------- + +local ImGuiDockRequestType = { None = 0, Dock = 1, Undock = 2, Split = 3 } -- Split is the same as Dock but without a DockPayload local function ImGuiDockRequest() return { Type = ImGuiDockRequestType.None, + -- DockTargetWindow: Destination/Target Window to dock into (may be a loose window or a DockNode, might be nil in which case DockTargetNode cannot be nil) + -- DockTargetNode: Destination/Target Node to dock into + -- DockPayload: Source/Payload window to dock (may be a loose window or a DockNode), [Optional] DockTargetWindow = nil, DockTargetNode = nil, DockPayload = nil, DockSplitDir = ImGuiDir.None, DockSplitRatio = 0.5, DockSplitOuter = false, UndockTargetWindow = nil, UndockTargetNode = nil, } end +-- Persistent Settings data, stored contiguously in SettingsNodes local function ImGuiDockNodeSettings() return { ID = 0, ParentNodeId = 0, ParentWindowId = 0, SelectedTabId = 0, - SplitAxis = ImGuiAxis.None, Depth = 0, Flags = 0, + SplitAxis = ImGuiAxis.None, Depth = 0, Flags = 0, -- Flags: NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags.SavedFlagsMask_) Pos = ImVec2(0, 0), Size = ImVec2(0, 0), SizeRef = ImVec2(0, 0), } end function ImGuiDockContext() + -- Nodes: Map ID -> ImGuiDockNode: Active nodes return { Nodes = {}, Requests = ImVector(), NodesSettings = ImVector(), WantFullRebuild = false } end @@ -487,25 +1049,44 @@ local DN = MT.ImGuiDockNode function ImGuiDockNode(id) return setmetatable({ ID = id, + -- SharedFlags: (Write) Flags shared by all nodes of a same dockspace hierarchy (inherited from the root node) + -- LocalFlags: (Write) Flags specific to this node + -- LocalFlagsInWindows: (Write) Flags specific to this node, applied from windows + -- MergedFlags: (Read) Effective flags (== SharedFlags | LocalFlagsInNode | LocalFlagsInWindows) SharedFlags = 0, LocalFlags = 0, LocalFlagsInWindows = 0, MergedFlags = 0, State = ImGuiDockNodeState.Unknown, ParentNode = nil, - ChildNodes = { [0] = nil, [1] = nil }, - Windows = ImVector(), + ChildNodes = { [0] = nil, [1] = nil }, -- [Split node only] Child nodes (left/right or top/bottom). Consider switching to an array. + Windows = ImVector(), -- Note: unordered list! Iterate TabBar.Tabs for user-order. TabBar = nil, + -- Pos: Current position + -- Size: Current size + -- SizeRef: [Split node only] Last explicitly written-to size (overridden when using a splitter affecting the node), used to calculate Size. Pos = ImVec2(0, 0), Size = ImVec2(0, 0), SizeRef = ImVec2(0, 0), - SplitAxis = ImGuiAxis.None, + SplitAxis = ImGuiAxis.None, -- [Split node only] Split axis (X or Y) LastBgColor = IM_COL32_WHITE, - WindowClass = ImGuiWindowClass(), + WindowClass = ImGuiWindowClass(), -- [Root node only] + -- VisibleWindow: Generally point to window which is ID is == SelectedTabID, but when CTRL+Tabbing this can be a different window. HostWindow = nil, VisibleWindow = nil, + -- CentralNode: [Root node only] Pointer to central node. + -- OnlyNodeWithWindows: [Root node only] Set when there is a single visible node within the hierarchy. CentralNode = nil, OnlyNodeWithWindows = nil, - CountNodeWithWindows = 0, + CountNodeWithWindows = 0, -- [Root node only] + -- LastFrameAlive: Last frame number the node was updated or kept alive explicitly with DockSpace() + ImGuiDockNodeFlags.KeepAliveOnly + -- LastFrameActive: Last frame number the node was updated. + -- LastFrameFocused: Last frame number the node was focused. LastFrameAlive = -1, LastFrameActive = -1, LastFrameFocused = -1, + -- LastFocusedNodeId: [Root node only] Which of our child docking node (any ancestor in the hierarchy) was last focused. + -- SelectedTabId: [Leaf node only] Which of our tab/window is selected. + -- WantCloseTabId: [Leaf node only] Set when closing a specific tab/window. + -- RefViewportId: Reference viewport ID from visible window when HostWindow == nil. LastFocusedNodeId = 0, SelectedTabId = 0, WantCloseTabId = 0, RefViewportId = 0, - AuthorityForPos = ImGuiDataAuthority.DockNode, AuthorityForSize = ImGuiDataAuthority.DockNode, + AuthorityForPos = ImGuiDataAuthority.DockNode, AuthorityForSize = ImGuiDataAuthority.DockNode, -- ImGuiDataAuthority AuthorityForViewport = ImGuiDataAuthority.Auto, - IsVisible = true, IsFocused = false, IsBgDrawnThisFrame = false, - HasCloseButton = false, HasWindowMenuButton = false, HasCentralNodeChild = false, + IsVisible = true, IsFocused = false, IsBgDrawnThisFrame = false, -- IsVisible: Set to false when the node is hidden (usually disabled as it has no active window) + HasCloseButton = false, HasWindowMenuButton = false, HasCentralNodeChild = false, -- HasCloseButton: Provide space for a close button (if any of the docked window has one). Note that button may be hidden on window without one. + -- WantCloseAll: Set when closing all tabs at once. + -- WantMouseMove: After a node extraction we need to transition toward moving the newly created host window WantCloseAll = false, WantLockSizeOnce = false, WantMouseMove = false, WantHiddenTabBarUpdate = false, WantHiddenTabBarToggle = false, }, DN) @@ -515,8 +1096,8 @@ function DN:IsRootNode() return self.ParentNode == nil end function DN:IsDockSpace() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.DockSpace) ~= 0 end function DN:IsFloatingNode() return self.ParentNode == nil and bit32.band(self.MergedFlags, ImGuiDockNodeFlags.DockSpace) == 0 end function DN:IsCentralNode() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.CentralNode) ~= 0 end -function DN:IsHiddenTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.HiddenTabBar) ~= 0 end -function DN:IsNoTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.NoTabBar) ~= 0 end +function DN:IsHiddenTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.HiddenTabBar) ~= 0 end -- Hidden tab bar can be shown back by clicking the small triangle +function DN:IsNoTabBar() return bit32.band(self.MergedFlags, ImGuiDockNodeFlags.NoTabBar) ~= 0 end -- Never show a tab bar function DN:IsSplitNode() return self.ChildNodes[0] ~= nil end function DN:IsLeafNode() return self.ChildNodes[0] == nil end function DN:IsEmpty() return self.ChildNodes[0] == nil and self.Windows.Size == 0 end @@ -527,9 +1108,11 @@ function DN:UpdateMergedFlags() self.MergedFlags = bit32.bor(self.SharedFlags, s local function ImGuiDockPreviewData() local d = { FutureNode = ImGuiDockNode(0), + -- IsSidesAvailable: Hold your breath, grammar freaks.. + -- IsSplitDirExplicit: Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window) IsDropAllowed = false, IsCenterAvailable = false, IsSidesAvailable = false, IsSplitDirExplicit = false, SplitNode = nil, SplitDir = ImGuiDir.None, SplitRatio = 0.0, - DropRectsDraw = {}, + DropRectsDraw = {}, -- May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects() } for n = 0, 4 do d.DropRectsDraw[n] = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX) end return d @@ -550,20 +1133,51 @@ local function DockContextNodesSorted(ctx) end ImGui.DockContextNodesSorted = DockContextNodesSorted ---------------------------------------------------------------------------------------- --- Docking: ImGuiDockContext ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Docking: Forward Declarations +------------------------------------------------------------------------------- +-- Settings local DockSettingsHandler_ClearAll, DockSettingsHandler_ApplyAll, DockSettingsHandler_ReadOpen, DockSettingsHandler_ReadLine, DockSettingsHandler_WriteAll local DockSettingsRenameNodeReferences, DockSettingsRemoveNodeReferences, DockSettingsFindNodeSettings +------------------------------------------------------------------------------- +-- Docking: ImGuiDockContext +------------------------------------------------------------------------------- +-- The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings, +-- or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active. +-- At boot time only, we run a simple GC to remove nodes that have no references. +-- Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures), +-- we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does). +-- This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data. +------------------------------------------------------------------------------- +-- - DockContextInitialize() +-- - DockContextShutdown() +-- - DockContextClearNodes() +-- - DockContextRebuildNodes() +-- - DockContextNewFrameUpdateUndocking() +-- - DockContextNewFrameUpdateDocking() +-- - DockContextEndFrame() +-- - DockContextFindNodeByID() +-- - DockContextBindNodeToWindow() +-- - DockContextGenNodeID() +-- - DockContextAddNode() +-- - DockContextRemoveNode() +-- - ImGuiDockContextPruneNodeData +-- - DockContextPruneUnusedSettingsNodes() +-- - DockContextBuildNodesFromSettings() +-- - DockContextBuildAddWindowsToNodes() +------------------------------------------------------------------------------- + function ImGui.DockContextInitialize(ctx) local g = ctx + + -- Add .ini handle for persistent docking data local ini_handler = ImGuiSettingsHandler() ini_handler.TypeName = "Docking" ini_handler.TypeHash = ImHashStr("Docking") ini_handler.ClearAllFn = DockSettingsHandler_ClearAll - ini_handler.ReadInitFn = DockSettingsHandler_ClearAll + ini_handler.ReadInitFn = DockSettingsHandler_ClearAll -- Also clear on read ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen ini_handler.ReadLineFn = DockSettingsHandler_ReadLine ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll @@ -585,15 +1199,18 @@ function ImGui.DockContextClearNodes(ctx, root_id, clear_settings_refs) ImGui.DockBuilderRemoveNodeChildNodes(root_id) end +-- [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch +-- (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!) function ImGui.DockContextRebuildNodes(ctx) local dc = ctx.DockContext ImGui.SaveIniSettingsToMemory() - local root_id = 0 + local root_id = 0 -- Rebuild all ImGui.DockContextClearNodes(ctx, root_id, false) ImGui.DockContextBuildNodesFromSettings(ctx, dc.NodesSettings.Data, dc.NodesSettings.Size) ImGui.DockContextBuildAddWindowsToNodes(ctx, root_id) end +-- Docking context update function, called by NewFrame() function ImGui.DockContextNewFrameUpdateUndocking(ctx) local g = ctx local dc = ctx.DockContext @@ -604,20 +1221,24 @@ function ImGui.DockContextNewFrameUpdateUndocking(ctx) return end + -- Setting NoSplit at runtime merges all nodes if g.IO.ConfigDockingNoSplit then for _, id in ipairs(DockContextNodesSorted(ctx)) do local node = dc.Nodes[id] if node and node:IsRootNode() and node:IsSplitNode() then ImGui.DockBuilderRemoveNodeChildNodes(node.ID) + -- dc.WantFullRebuild = true end end end + -- Process full rebuild if dc.WantFullRebuild then ImGui.DockContextRebuildNodes(ctx) dc.WantFullRebuild = false end + -- Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame) for _, req in dc.Requests:iter() do if req.Type == ImGuiDockRequestType.Undock and req.UndockTargetWindow then ImGui.DockContextProcessUndockWindow(ctx, req.UndockTargetWindow) @@ -627,11 +1248,15 @@ function ImGui.DockContextNewFrameUpdateUndocking(ctx) end end +-- Docking context update function, called by NewFrame() function ImGui.DockContextNewFrameUpdateDocking(ctx) local g = ctx local dc = ctx.DockContext if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then return end + -- [DEBUG] Store hovered dock node. + -- We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using .DockNode is a good shortcut. + -- Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering. g.DebugHoveredDockNode = nil local hovered_window = g.HoveredWindowUnderMovingWindow if hovered_window then @@ -642,6 +1267,7 @@ function ImGui.DockContextNewFrameUpdateDocking(ctx) end end + -- Process Docking requests for _, req in dc.Requests:iter() do if req.Type == ImGuiDockRequestType.Dock then ImGui.DockContextProcessDock(ctx, req) @@ -649,6 +1275,7 @@ function ImGui.DockContextNewFrameUpdateDocking(ctx) end dc.Requests:resize(0) + -- Create windows for each automatic docking nodes for _, id in ipairs(DockContextNodesSorted(ctx)) do local node = dc.Nodes[id] if node and node:IsFloatingNode() then @@ -658,6 +1285,7 @@ function ImGui.DockContextNewFrameUpdateDocking(ctx) end function ImGui.DockContextEndFrame(ctx) + -- Draw backgrounds of node missing their window local g = ctx local dc = g.DockContext for _, id in ipairs(DockContextNodesSorted(ctx)) do @@ -676,17 +1304,23 @@ function ImGui.DockContextFindNodeByID(ctx, id) end function ImGui.DockContextGenNodeID(ctx) + -- Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used) + -- FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0 + -- We should poke in ctx.Nodes to find a suitable ID faster. Even more so trivial that ctx.Nodes lookup is already sorted. local id = 0x0001 while ImGui.DockContextFindNodeByID(ctx, id) ~= nil do id = id + 1 end return id end function ImGui.DockContextAddNode(ctx, id) + -- Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window. if id == 0 then id = ImGui.DockContextGenNodeID(ctx) else IM_ASSERT(ImGui.DockContextFindNodeByID(ctx, id) == nil) end + + -- We don't set node.LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings! local node = ImGuiDockNode(id) ctx.DockContext.Nodes[node.ID] = node return node @@ -715,12 +1349,14 @@ function ImGui.DockContextRemoveNode(ctx, node, merge_sibling_into_parent_node) end end +-- Raw-ish delete function ImGui.DockContextDeleteNode(ctx, node) local dc = ctx.DockContext node.TabBar = nil dc.Nodes[node.ID] = nil end +-- Garbage collect unused nodes (run once at init time) function ImGui.DockContextPruneUnusedSettingsNodes(ctx) local g = ctx local dc = ctx.DockContext @@ -733,9 +1369,10 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) return d end + -- Count child nodes and compute RootID for _, settings in dc.NodesSettings:iter() do if pool[settings.ID] ~= nil then - settings.ID = 0 + settings.ID = 0 -- Duplicate else local parent_data = (settings.ParentNodeId ~= 0) and pool[settings.ParentNodeId] or nil GetOrAdd(settings.ID).RootId = parent_data and parent_data.RootId or settings.ID @@ -746,6 +1383,8 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) end end + -- Count reference to dock ids from dockspaces + -- We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes() for _, settings in dc.NodesSettings:iter() do if settings.ParentWindowId ~= 0 then local window_settings = ImGui.FindWindowSettingsByID(settings.ParentWindowId) @@ -756,6 +1395,8 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) end end + -- Count reference to dock ids from window settings + -- We guard against the possibility of an invalid .ini file (RootID may point to a missing node) for _, settings in g.SettingsWindows:iter() do local dock_id = settings.DockId if dock_id and dock_id ~= 0 then @@ -768,6 +1409,7 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) end end + -- Prune for _, settings in dc.NodesSettings:iter() do local data = pool[settings.ID] if data ~= nil and data.CountWindows <= 1 then @@ -775,8 +1417,8 @@ function ImGui.DockContextPruneUnusedSettingsNodes(ctx) local data_parent = (settings.ParentNodeId ~= 0) and pool[settings.ParentNodeId] or nil local remove = false - remove = remove or (data.CountWindows == 1 and settings.ParentNodeId == 0 and data.CountChildNodes == 0 and bit32.band(settings.Flags, ImGuiDockNodeFlags.CentralNode) == 0) - remove = remove or (data.CountWindows == 0 and settings.ParentNodeId == 0 and data.CountChildNodes == 0) + remove = remove or (data.CountWindows == 1 and settings.ParentNodeId == 0 and data.CountChildNodes == 0 and bit32.band(settings.Flags, ImGuiDockNodeFlags.CentralNode) == 0) -- Floating root node with only 1 window + remove = remove or (data.CountWindows == 0 and settings.ParentNodeId == 0 and data.CountChildNodes == 0) -- Leaf nodes with 0 window remove = remove or (data_root == nil or data_root.CountChildWindows == 0) if remove then DockSettingsRemoveNodeReferences({ settings.ID }, 1) @@ -791,6 +1433,7 @@ end --- @param node_settings_array table # 1-based array function ImGui.DockContextBuildNodesFromSettings(ctx, node_settings_array, node_settings_count) + -- Build nodes for node_n = 1, node_settings_count do local settings = node_settings_array[node_n] if settings.ID ~= 0 and ImGui.DockContextFindNodeByID(ctx, settings.ID) == nil then @@ -811,6 +1454,8 @@ function ImGui.DockContextBuildNodesFromSettings(ctx, node_settings_array, node_ node.SplitAxis = settings.SplitAxis node:SetLocalFlags(bit32.band(settings.Flags, ImGuiDockNodeFlags.SavedFlagsMask_)) + -- Bind host window immediately if it already exist (in case of a rebuild) + -- This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node.HostWindow to be set. local root_node = ImGui.DockNodeGetRootNode(node) node.HostWindow = ImGui.FindWindowByName(DockNodeGetHostWindowTitle(root_node)) end @@ -818,11 +1463,12 @@ function ImGui.DockContextBuildNodesFromSettings(ctx, node_settings_array, node_ end function ImGui.DockContextBuildAddWindowsToNodes(ctx, root_id) + -- Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame) local g = ctx for _, window in g.Windows:iter() do if window.DockId ~= 0 and window.LastFrameActive >= g.FrameCount - 1 and window.DockNode == nil then local node = ImGui.DockContextFindNodeByID(ctx, window.DockId) - IM_ASSERT(node ~= nil) + IM_ASSERT(node ~= nil) -- This should have been called after DockContextBuildNodesFromSettings() if root_id == 0 or ImGui.DockNodeGetRootNode(node).ID == root_id then ImGui.DockNodeAddWindow(node, window, true) end @@ -830,9 +1476,18 @@ function ImGui.DockContextBuildAddWindowsToNodes(ctx, root_id) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: ImGuiDockContext Docking/Undocking functions ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockContextQueueDock() +-- - DockContextQueueUndockWindow() +-- - DockContextQueueUndockNode() +-- - DockContextQueueNotifyRemovedNode() +-- - DockContextProcessDock() +-- - DockContextProcessUndockWindow() +-- - DockContextProcessUndockNode() +-- - DockContextCalcDropPosForDocking() +------------------------------------------------------------------------------- function ImGui.DockContextQueueDock(ctx, target, target_node, payload, split_dir, split_ratio, split_outer) IM_ASSERT(target ~= payload) @@ -872,26 +1527,30 @@ function ImGui.DockContextProcessDock(ctx, req) IM_ASSERT(req.DockTargetWindow ~= nil or req.DockTargetNode ~= nil) local g = ctx - local payload_window = req.DockPayload + local payload_window = req.DockPayload -- Optional local target_window = req.DockTargetWindow local node = req.DockTargetNode + -- Decide which Tab will be selected at the end of the operation local next_selected_id = 0 local payload_node = nil if payload_window then payload_node = payload_window.DockNodeAsHost - payload_window.DockNodeAsHost = nil + payload_window.DockNodeAsHost = nil -- Important to clear this as the node will have its life as a child which might be merged/deleted later. if payload_node and payload_node:IsLeafNode() then next_selected_id = (payload_node.TabBar.NextSelectedTabId ~= 0) and payload_node.TabBar.NextSelectedTabId or payload_node.TabBar.SelectedTabId end if payload_node == nil then next_selected_id = payload_window.TabId end end + -- FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well + -- When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==. if node then IM_ASSERT(node.LastFrameAlive <= g.FrameCount) end if node and target_window and node == target_window.DockNodeAsHost then IM_ASSERT(node.Windows.Size > 0 or node:IsSplitNode() or node:IsCentralNode()) end + -- Create new node and add existing window to it if node == nil then node = ImGui.DockContextAddNode(ctx, 0) node.Pos = ImVec2(target_window.Pos.x, target_window.Pos.y) @@ -906,10 +1565,11 @@ function ImGui.DockContextProcessDock(ctx, req) local split_dir = req.DockSplitDir if split_dir ~= ImGuiDir.None then + -- Split into two, one side will be our payload node unless we are dropping a loose window local split_axis = (split_dir == ImGuiDir.Left or split_dir == ImGuiDir.Right) and ImGuiAxis.X or ImGuiAxis.Y - local split_inheritor_child_idx = (split_dir == ImGuiDir.Left or split_dir == ImGuiDir.Up) and 1 or 0 + local split_inheritor_child_idx = (split_dir == ImGuiDir.Left or split_dir == ImGuiDir.Up) and 1 or 0 -- Current contents will be moved to the opposite side local split_ratio = req.DockSplitRatio - ImGui.DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node) + ImGui.DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node) -- payload_node may be nil here! local new_node = node.ChildNodes[bit32.bxor(split_inheritor_child_idx, 1)] new_node.HostWindow = node.HostWindow node = new_node @@ -917,6 +1577,7 @@ function ImGui.DockContextProcessDock(ctx, req) node:SetLocalFlags(bit32.band(node.LocalFlags, bit32.bnot(ImGuiDockNodeFlags.HiddenTabBar))) if node ~= payload_node then + -- Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!) if node.Windows.Size > 0 and node.TabBar == nil then ImGui.DockNodeAddTabBar(node) for n = 1, node.Windows.Size do @@ -925,9 +1586,13 @@ function ImGui.DockContextProcessDock(ctx, req) end if payload_node ~= nil then + -- Transfer full payload node (with 1+ child windows or child nodes) if payload_node:IsSplitNode() then if node.Windows.Size > 0 then - IM_ASSERT(payload_node.OnlyNodeWithWindows ~= nil) + -- We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node. + -- In this situation, we move the windows of the target node into the currently visible node of the payload. + -- This allows us to preserve some of the underlying dock tree settings nicely. + IM_ASSERT(payload_node.OnlyNodeWithWindows ~= nil) -- The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted. local visible_node = payload_node.OnlyNodeWithWindows if visible_node.TabBar then IM_ASSERT(visible_node.TabBar.Tabs.Size > 0) end ImGui.DockNodeMoveWindows(node, visible_node) @@ -935,6 +1600,8 @@ function ImGui.DockContextProcessDock(ctx, req) DockSettingsRenameNodeReferences(node.ID, visible_node.ID) end if node:IsCentralNode() then + -- Central node property needs to be moved to a leaf node, pick the last focused one. + -- FIXME-DOCK: If we had to transfer other flags here, what would the policy be? local last_focused_node = ImGui.DockContextFindNodeByID(ctx, payload_node.LastFocusedNodeId) IM_ASSERT(last_focused_node ~= nil) local last_focused_root_node = ImGui.DockNodeGetRootNode(last_focused_node) @@ -953,6 +1620,7 @@ function ImGui.DockContextProcessDock(ctx, req) end ImGui.DockContextRemoveNode(ctx, payload_node, true) elseif payload_window then + -- Transfer single window local payload_dock_id = payload_window.DockId node.VisibleWindow = payload_window ImGui.DockNodeAddWindow(node, payload_window, true) @@ -961,14 +1629,24 @@ function ImGui.DockContextProcessDock(ctx, req) end end else + -- When docking a floating single window node we want to reevaluate auto-hiding of the tab bar node.WantHiddenTabBarUpdate = true end + -- Update selection immediately local tab_bar = node.TabBar if tab_bar then tab_bar.NextSelectedTabId = next_selected_id end ImGui.MarkIniSettingsDirty() end +-- Problem: +-- Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more +-- than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic +-- with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be +-- due to missing ImGuiBackendFlags.HasMouseCursors backend flag). +-- Solution: +-- When undocking a window we currently force its maximum size to 90% of the host viewport. +-- Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch). local function FixLargeWindowsWhenUndocking(size, ref_viewport) if ref_viewport == nil then return size end local max_size = ImTrunc(ref_viewport.WorkSize * 0.90) @@ -997,6 +1675,7 @@ function ImGui.DockContextProcessUndockNode(ctx, node) IM_ASSERT(node.Windows.Size >= 1) if node:IsRootNode() or node:IsCentralNode() then + -- In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload. local new_node = ImGui.DockContextAddNode(ctx, 0) new_node.Pos = ImVec2(node.Pos.x, node.Pos.y) new_node.Size = ImVec2(node.Size.x, node.Size.y) @@ -1005,11 +1684,12 @@ function ImGui.DockContextProcessUndockNode(ctx, node) DockSettingsRenameNodeReferences(node.ID, new_node.ID) node = new_node else + -- Otherwise extract our node and merge our sibling back into the parent node. IM_ASSERT(node.ParentNode.ChildNodes[0] == node or node.ParentNode.ChildNodes[1] == node) local index_in_parent = (node.ParentNode.ChildNodes[0] == node) and 0 or 1 node.ParentNode.ChildNodes[index_in_parent] = nil ImGui.DockNodeTreeMerge(ctx, node.ParentNode, node.ParentNode.ChildNodes[bit32.bxor(index_in_parent, 1)]) - node.ParentNode.AuthorityForViewport = ImGuiDataAuthority.Window + node.ParentNode.AuthorityForViewport = ImGuiDataAuthority.Window -- The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport node.ParentNode = nil end for _, window in node.Windows:iter() do @@ -1024,9 +1704,13 @@ function ImGui.DockContextProcessUndockNode(ctx, node) ImGui.MarkIniSettingsDirty() end +-- This is mostly used for automation. --- @return bool ok, ImVec2? out_pos function ImGui.DockContextCalcDropPosForDocking(target, target_node, payload_window, payload_node, split_dir, split_outer) if target ~= nil and target_node == nil then target_node = target.DockNode end + + -- In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects + -- (which would be functionally identical) we only show the outer one. Reflect this here. if target_node and target_node.ParentNode == nil and target_node:IsCentralNode() and split_dir ~= ImGuiDir.None then split_outer = true end @@ -1037,9 +1721,38 @@ function ImGui.DockContextCalcDropPosForDocking(target, target_node, payload_win return true, r:GetCenter() end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: ImGuiDockNode ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockNodeGetTabOrder() +-- - DockNodeAddWindow() +-- - DockNodeRemoveWindow() +-- - DockNodeMoveChildNodes() +-- - DockNodeMoveWindows() +-- - DockNodeApplyPosSizeToWindows() +-- - DockNodeHideHostWindow() +-- - ImGuiDockNodeFindInfoResults +-- - DockNodeFindInfo() +-- - DockNodeFindWindowByID() +-- - DockNodeUpdateFlagsAndCollapse() +-- - DockNodeUpdateHasCentralNodeFlag() +-- - DockNodeUpdateVisibleFlag() +-- - DockNodeStartMouseMovingWindow() +-- - DockNodeUpdate() +-- - DockNodeUpdateWindowMenu() +-- - DockNodeBeginAmendTabBar() +-- - DockNodeEndAmendTabBar() +-- - DockNodeUpdateTabBar() +-- - DockNodeAddTabBar() +-- - DockNodeRemoveTabBar() +-- - DockNodeIsDropAllowedOne() +-- - DockNodeIsDropAllowed() +-- - DockNodeCalcTabBarLayout() +-- - DockNodeCalcSplitRects() +-- - DockNodeCalcDropRectsAndTestMousePos() +-- - DockNodePreviewDockSetup() +-- - DockNodePreviewDockRender() +------------------------------------------------------------------------------- function ImGui.DockNodeGetTabOrder(window) local tab_bar = window.DockNode.TabBar @@ -1055,11 +1768,15 @@ end function ImGui.DockNodeAddWindow(node, window, add_to_tab_bar) if window.DockNode then + -- Can overwrite an existing window.DockNode (e.g. pointing to a disabled DockSpace node) IM_ASSERT(window.DockNode.ID ~= node.ID) ImGui.DockNodeRemoveWindow(window.DockNode, window, 0) end IM_ASSERT(window.DockNode == nil or window.DockNodeAsHost == nil) + -- If more than 2 windows appeared on the same frame leading to the creation of a new hosting window, + -- we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame). + -- We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin() if node.HostWindow == nil and node.Windows.Size == 1 and node.Windows.Data[1].WasActive == false then DockNodeHideWindowDuringHostWindowCreation(node.Windows.Data[1]) end @@ -1071,17 +1788,22 @@ function ImGui.DockNodeAddWindow(node, window, add_to_tab_bar) window.DockIsActive = (node.Windows.Size > 1) window.DockTabWantClose = false + -- When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage. + -- In particular it is important we init the viewport from the first window so we don't create two viewports and drop one. if node.HostWindow == nil and node:IsFloatingNode() then if node.AuthorityForPos == ImGuiDataAuthority.Auto then node.AuthorityForPos = ImGuiDataAuthority.Window end if node.AuthorityForSize == ImGuiDataAuthority.Auto then node.AuthorityForSize = ImGuiDataAuthority.Window end if node.AuthorityForViewport == ImGuiDataAuthority.Auto then node.AuthorityForViewport = ImGuiDataAuthority.Window end end + -- Add to tab bar if requested if add_to_tab_bar then if node.TabBar == nil then ImGui.DockNodeAddTabBar(node) node.TabBar.SelectedTabId = node.SelectedTabId node.TabBar.NextSelectedTabId = node.SelectedTabId + + -- Add existing windows for n = 1, node.Windows.Size - 1 do ImGui.TabBarAddTab(node.TabBar, ImGuiTabItemFlags.None, node.Windows.Data[n]) end @@ -1091,6 +1813,7 @@ function ImGui.DockNodeAddWindow(node, window, add_to_tab_bar) ImGui.DockNodeUpdateVisibleFlag(node) + -- Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame. if node.HostWindow then ImGui.UpdateWindowParentAndRootLinks(window, bit32.bor(window.Flags, ImGuiWindowFlags.ChildWindow), node.HostWindow) end @@ -1098,6 +1821,8 @@ end function ImGui.DockNodeRemoveWindow(node, window, save_dock_id) IM_ASSERT(window.DockNode == node) + -- IM_ASSERT(window.RootWindowDockTree == node.HostWindow) + -- IM_ASSERT(window.LastFrameActive < g.FrameCount) -- We may call this from Begin() IM_ASSERT(save_dock_id == 0 or save_dock_id == node.ID) window.DockNode = nil @@ -1106,20 +1831,24 @@ function ImGui.DockNodeRemoveWindow(node, window, save_dock_id) window.DockId = save_dock_id window.Flags = bit32.band(window.Flags, bit32.bnot(ImGuiWindowFlags.ChildWindow)) if window.ParentWindow then window.ParentWindow.DC.ChildWindows:find_erase(window) end - ImGui.UpdateWindowParentAndRootLinks(window, window.Flags, nil) + ImGui.UpdateWindowParentAndRootLinks(window, window.Flags, nil) -- Update immediately if node.HostWindow and node.HostWindow.ViewportOwned then + -- When undocking from a user interaction this will always run in NewFrame() and have not much effect. + -- But mid-frame, if we clear viewport we need to mark window as hidden as well. window.Viewport = nil window.ViewportId = 0 window.ViewportOwned = false window.Hidden = true end + -- Remove window local idx = node.Windows:find_index(window) IM_ASSERT(idx ~= nil) node.Windows:erase(idx) if node.VisibleWindow == window then node.VisibleWindow = nil end + -- Remove tab and possibly tab bar node.WantHiddenTabBarUpdate = true if node.TabBar then ImGui.TabBarRemoveTab(node.TabBar, window.TabId) @@ -1128,16 +1857,20 @@ function ImGui.DockNodeRemoveWindow(node, window, save_dock_id) ImGui.DockNodeRemoveTabBar(node) end end + if node.Windows.Size == 0 and not node:IsCentralNode() and not node:IsDockSpace() and window.DockId ~= node.ID then + -- Automatic dock node delete themselves if they are not holding at least one tab ImGui.DockContextRemoveNode(ImGui.GetCurrentContext(), node, true) return end if node.Windows.Size == 1 and not node:IsCentralNode() and node.HostWindow then local remaining_window = node.Windows.Data[1] + -- Note: we used to transport viewport ownership here. remaining_window.Collapsed = node.HostWindow.Collapsed end + -- Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree ImGui.DockNodeUpdateVisibleFlag(node) end @@ -1154,16 +1887,19 @@ function ImGui.DockNodeMoveChildNodes(dst_node, src_node) end function ImGui.DockNodeMoveWindows(dst_node, src_node) + -- Insert tabs in the same orders as currently ordered (node.Windows isn't ordered) IM_ASSERT(src_node and dst_node and dst_node ~= src_node) local src_tab_bar = src_node.TabBar if src_tab_bar ~= nil then IM_ASSERT(src_node.Windows.Size <= src_node.TabBar.Tabs.Size) end + -- If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.) local move_tab_bar = (src_tab_bar ~= nil) and (dst_node.TabBar == nil) if move_tab_bar then dst_node.TabBar = src_node.TabBar src_node.TabBar = nil end + -- Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar(). -- Snapshot: DockNodeAddWindow() won't touch src_node.Windows since window.DockNode is cleared first local windows = {} for i = 1, src_node.Windows.Size do windows[i] = src_node.Windows.Data[i] end @@ -1182,7 +1918,7 @@ end function ImGui.DockNodeApplyPosSizeToWindows(node) for _, window in node.Windows:iter() do - ImGui.SetWindowPos(window, node.Pos, ImGuiCond.Always) + ImGui.SetWindowPos(window, node.Pos, ImGuiCond.Always) -- We don't assign directly to Pos because it can break the calculation of SizeContents on next frame ImGui.SetWindowSize(window, node.Size, ImGuiCond.Always) end end @@ -1199,13 +1935,14 @@ function ImGui.DockNodeHideHostWindow(node) if node.TabBar then ImGui.DockNodeRemoveTabBar(node) end end +-- Search function called once by root node in DockNodeUpdate() local function DockNodeFindInfo(node, info) if node.Windows.Size > 0 then if info.FirstNodeWithWindows == nil then info.FirstNodeWithWindows = node end info.CountNodesWithWindows = info.CountNodesWithWindows + 1 end if node:IsCentralNode() then - IM_ASSERT(info.CentralNode == nil) + IM_ASSERT(info.CentralNode == nil) -- Should be only one IM_ASSERT(node:IsLeafNode(), "If you get this assert: please submit .ini file + repro of actions leading to this.") info.CentralNode = node end @@ -1222,18 +1959,27 @@ function ImGui.DockNodeFindWindowByID(node, id) return nil end +-- - Remove inactive windows/nodes. +-- - Update visibility flag. function ImGui.DockNodeUpdateFlagsAndCollapse(node) local g = ImGui.GetCurrentContext() IM_ASSERT(node.ParentNode == nil or node.ParentNode.ChildNodes[0] == node or node.ParentNode.ChildNodes[1] == node) + -- Inherit most flags if node.ParentNode then node.SharedFlags = bit32.band(node.ParentNode.SharedFlags, ImGuiDockNodeFlags.SharedFlagsInheritMask_) end + -- Recurse into children + -- There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'. + -- If 'node.ChildNode[0]' delete itself, then 'node.ChildNode[1].Windows' will be moved into 'node' + -- If 'node.ChildNode[1]' delete itself, then 'node.ChildNode[0].Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless) node.HasCentralNodeChild = false if node.ChildNodes[0] then ImGui.DockNodeUpdateFlagsAndCollapse(node.ChildNodes[0]) end if node.ChildNodes[1] then ImGui.DockNodeUpdateFlagsAndCollapse(node.ChildNodes[1]) end + -- Remove inactive windows, collapse nodes + -- Merge node flags overrides stored in windows node.LocalFlagsInWindows = ImGuiDockNodeFlags.None local window_n = 1 while window_n <= node.Windows.Size do @@ -1242,35 +1988,40 @@ function ImGui.DockNodeUpdateFlagsAndCollapse(node) local node_was_active = (node.LastFrameActive + 1 == g.FrameCount) local remove = false - remove = remove or (node_was_active and (window.WasActive == false)) - remove = remove or (node_was_active and (node.WantCloseAll or node.WantCloseTabId == window.TabId) and window.HasCloseButton and bit32.band(window.Flags, ImGuiWindowFlags.UnsavedDocument) == 0) + remove = remove or (node_was_active and (window.WasActive == false)) -- Can't use 'window.LastFrameActive + 1 < g.FrameCount'. (see #9151) + remove = remove or (node_was_active and (node.WantCloseAll or node.WantCloseTabId == window.TabId) and window.HasCloseButton and bit32.band(window.Flags, ImGuiWindowFlags.UnsavedDocument) == 0) -- Submit all _expected_ closure from last frame remove = remove or window.DockTabWantClose if remove then window.DockTabWantClose = false if node.Windows.Size == 1 and not node:IsCentralNode() then ImGui.DockNodeHideHostWindow(node) node.State = ImGuiDockNodeState.HostWindowHiddenBecauseSingleWindow - ImGui.DockNodeRemoveWindow(node, window, node.ID) + ImGui.DockNodeRemoveWindow(node, window, node.ID) -- Will delete the node so it'll be invalid on return return end ImGui.DockNodeRemoveWindow(node, window, node.ID) else + -- FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this. + -- node.LocalFlagsInWindow = bit32.band(node.LocalFlagsInWindow, bit32.bnot(window.WindowClass.DockNodeFlagsOverrideClear)) node.LocalFlagsInWindows = bit32.bor(node.LocalFlagsInWindows, window.WindowClass.DockNodeFlagsOverrideSet) window_n = window_n + 1 end end node:UpdateMergedFlags() + -- Auto-hide tab bar option local node_flags = node.MergedFlags if node.WantHiddenTabBarUpdate and node.Windows.Size == 1 and bit32.band(node_flags, ImGuiDockNodeFlags.AutoHideTabBar) ~= 0 and not node:IsHiddenTabBar() then node.WantHiddenTabBarToggle = true end node.WantHiddenTabBarUpdate = false + -- Cancel toggling if we know our tab bar is enforced to be hidden at all times if node.WantHiddenTabBarToggle and node.VisibleWindow and bit32.band(node.VisibleWindow.WindowClass.DockNodeFlagsOverrideSet, ImGuiDockNodeFlags.HiddenTabBar) ~= 0 then node.WantHiddenTabBarToggle = false end + -- Apply toggles at a single point of the frame (here!) local prev_local_flags = node.LocalFlags if node.Windows.Size > 1 then node:SetLocalFlags(bit32.band(node.LocalFlags, bit32.bnot(ImGuiDockNodeFlags.HiddenTabBar))) @@ -1278,13 +2029,14 @@ function ImGui.DockNodeUpdateFlagsAndCollapse(node) node:SetLocalFlags(bit32.bxor(node.LocalFlags, ImGuiDockNodeFlags.HiddenTabBar)) end if bit32.band(bit32.bxor(node.LocalFlags, prev_local_flags), ImGuiDockNodeFlags.SavedFlagsMask_) ~= 0 then - ImGui.MarkIniSettingsDirty() + ImGui.MarkIniSettingsDirty() -- Bit flaky to only do this here. Perhaps compare node flags every frame? #9380 end node.WantHiddenTabBarToggle = false ImGui.DockNodeUpdateVisibleFlag(node) end +-- This is rarely called as DockNodeUpdateForRootNode() generally does it most frames. function ImGui.DockNodeUpdateHasCentralNodeChild(node) node.HasCentralNodeChild = false if node.ChildNodes[0] then ImGui.DockNodeUpdateHasCentralNodeChild(node.ChildNodes[0]) end @@ -1299,6 +2051,7 @@ function ImGui.DockNodeUpdateHasCentralNodeChild(node) end function ImGui.DockNodeUpdateVisibleFlag(node) + -- Update visibility flag local is_visible = (node.ParentNode == nil) and node:IsDockSpace() or node:IsCentralNode() is_visible = is_visible or (node.Windows.Size > 0) is_visible = is_visible or (node.ChildNodes[0] ~= nil and node.ChildNodes[0].IsVisible) @@ -1311,13 +2064,17 @@ function ImGui.DockNodeStartMouseMovingWindow(node, window) IM_ASSERT(node.WantMouseMove == true) ImGui.StartMouseMovingWindow(window) ImVec2_Copy(g.ActiveIdClickOffset, g.IO.MouseClickedPos[0] - node.Pos) - g.MovingWindow = window + g.MovingWindow = window -- If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision. node.WantMouseMove = false end +-- Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class. function ImGui.DockNodeUpdateForRootNode(node) ImGui.DockNodeUpdateFlagsAndCollapse(node) + -- - Setup central node pointers + -- - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!) + -- Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing local info = { CentralNode = nil, FirstNodeWithWindows = nil, CountNodesWithWindows = 0 } DockNodeFindInfo(node, info) node.CentralNode = info.CentralNode @@ -1327,6 +2084,9 @@ function ImGui.DockNodeUpdateForRootNode(node) node.LastFocusedNodeId = info.FirstNodeWithWindows.ID end + -- Copy the window class from of our first window so it can be used for proper dock filtering. + -- When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy. + -- FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec. local first_node_with_windows = info.FirstNodeWithWindows if first_node_with_windows then node.WindowClass = first_node_with_windows.Windows.Data[1].WindowClass @@ -1346,6 +2106,11 @@ function ImGui.DockNodeUpdateForRootNode(node) end local function DockNodeSetupHostWindow(node, host_window) + -- Remove ourselves from any previous different host window + -- This can happen if a user mistakenly does (see #4295 for details): + -- - N+0: DockBuilderAddNode(id, 0) -- missing ImGuiDockNodeFlags.DockSpace + -- - N+1: NewFrame() -- will create floating host window for that node + -- - N+1: DockSpace(id) -- requalify node as dockspace, moving host window if node.HostWindow and node.HostWindow ~= host_window and node.HostWindow.DockNodeAsHost == node then node.HostWindow.DockNodeAsHost = nil end @@ -1363,8 +2128,10 @@ function ImGui.DockNodeUpdate(node) node.OnlyNodeWithWindows = nil if node:IsRootNode() then ImGui.DockNodeUpdateForRootNode(node) end + -- Remove tab bar if not needed if node.TabBar and node:IsNoTabBar() then ImGui.DockNodeRemoveTabBar(node) end + -- Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId) local want_to_hide_host_window = false if node:IsFloatingNode() then if node.Windows.Size <= 1 and node:IsLeafNode() then @@ -1376,6 +2143,7 @@ function ImGui.DockNodeUpdate(node) end if want_to_hide_host_window then if node.Windows.Size == 1 then + -- Floating window pos/size is authoritative local single_window = node.Windows.Data[1] node.Pos = ImVec2(single_window.Pos.x, single_window.Pos.y) node.Size = ImVec2(single_window.SizeFull.x, single_window.SizeFull.y) @@ -1383,6 +2151,7 @@ function ImGui.DockNodeUpdate(node) node.AuthorityForSize = ImGuiDataAuthority.Window node.AuthorityForViewport = ImGuiDataAuthority.Window + -- Transfer focus immediately so when we revert to a regular window it is immediately selected if node.HostWindow and g.NavWindow == node.HostWindow then ImGui.FocusWindow(single_window) end @@ -1407,9 +2176,20 @@ function ImGui.DockNodeUpdate(node) return end + -- In some circumstance we will defer creating the host window (so everything will be kept hidden), + -- while the expected visible window is resizing itself. + -- This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled, + -- otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up: + -- N+0: Begin(): window created (with no known size), node is created + -- N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible + -- N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible + -- We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code. + -- It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin(). + -- In reality it isn't very important as user quickly ends up with size data in .ini file. if node.IsVisible and node.HostWindow == nil and node:IsFloatingNode() and node:IsLeafNode() then IM_ASSERT(node.Windows.Size > 0) local ref_window = nil + -- Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them! if node.SelectedTabId ~= 0 then ref_window = ImGui.DockNodeFindWindowByID(node, node.SelectedTabId) end if ref_window == nil then ref_window = node.Windows.Data[1] end if ref_window.AutoFitFramesX > 0 or ref_window.AutoFitFramesY > 0 then @@ -1420,9 +2200,11 @@ function ImGui.DockNodeUpdate(node) local node_flags = node.MergedFlags + -- Decide if the node will have a close button and a window menu button node.HasWindowMenuButton = (node.Windows.Size > 0) and bit32.band(node_flags, ImGuiDockNodeFlags.NoWindowMenuButton) == 0 node.HasCloseButton = false for _, window in node.Windows:iter() do + -- FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call. node.HasCloseButton = node.HasCloseButton or window.HasCloseButton window.DockIsActive = (node.Windows.Size > 1) end @@ -1430,40 +2212,47 @@ function ImGui.DockNodeUpdate(node) node.HasCloseButton = false end + -- Bind or create host window local host_window = nil local beginned_into_host_window = false if node:IsDockSpace() then + -- [Explicit root dockspace node] IM_ASSERT(node.HostWindow) host_window = node.HostWindow else + -- [Automatic root or child nodes] if node:IsRootNode() and node.IsVisible then local ref_window = (node.Windows.Size > 0) and node.Windows.Data[1] or nil + -- Sync Pos if node.AuthorityForPos == ImGuiDataAuthority.Window and ref_window then ImGui.SetNextWindowPos(ref_window.Pos) elseif node.AuthorityForPos == ImGuiDataAuthority.DockNode then ImGui.SetNextWindowPos(node.Pos) end + -- Sync Size if node.AuthorityForSize == ImGuiDataAuthority.Window and ref_window then ImGui.SetNextWindowSize(ref_window.SizeFull) elseif node.AuthorityForSize == ImGuiDataAuthority.DockNode then ImGui.SetNextWindowSize(node.Size) end + -- Sync Collapsed if node.AuthorityForSize == ImGuiDataAuthority.Window and ref_window then ImGui.SetNextWindowCollapsed(ref_window.Collapsed) end ImGui.SetNextWindowClass(node.WindowClass) + -- Begin into the host window local window_label = DockNodeGetHostWindowTitle(node) local window_flags = bit32.bor(ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoScrollWithMouse, ImGuiWindowFlags.DockNodeHost) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoFocusOnAppearing) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoNavFocus, ImGuiWindowFlags.NoCollapse) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoTitleBar) - ImGui.SetNextWindowBgAlpha(0.0) + ImGui.SetNextWindowBgAlpha(0.0) -- Don't set ImGuiWindowFlags.NoBackground because it disables borders ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0, 0)) ImGui.Begin(window_label, nil, window_flags) ImGui.PopStyleVar() @@ -1475,6 +2264,12 @@ function ImGui.DockNodeUpdate(node) node.Pos = ImVec2(host_window.Pos.x, host_window.Pos.y) node.Size = ImVec2(host_window.Size.x, host_window.Size.y) + -- We set ImGuiWindowFlags.NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow) + -- But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags. + -- One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again. + -- When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window + -- during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back + -- after the dock host window, losing their top-most status. if node.HostWindow.Appearing then ImGui.BringWindowToDisplayFront(node.HostWindow) end node.AuthorityForPos = ImGuiDataAuthority.Auto @@ -1491,21 +2286,23 @@ function ImGui.DockNodeUpdate(node) ImGui.DockNodeStartMouseMovingWindow(node, node.HostWindow) end end - node.RefViewportId = 0 + node.RefViewportId = 0 -- Clear when we have a host window + -- Update focused node (the one whose title bar is highlight) within a node tree if node:IsSplitNode() then IM_ASSERT(node.TabBar == nil) end if node:IsRootNode() then local p_window = g.NavWindow and g.NavWindow.RootWindow or nil while p_window ~= nil and p_window.DockNode ~= nil do local p_node = ImGui.DockNodeGetRootNode(p_window.DockNode) if p_node == node then - node.LastFocusedNodeId = p_window.DockNode.ID + node.LastFocusedNodeId = p_window.DockNode.ID -- Note: not using root node ID! break end p_window = p_node.HostWindow and p_node.HostWindow.RootWindow or nil end end + -- Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace local central_node = node.CentralNode local central_node_hole = node:IsRootNode() and host_window ~= nil and bit32.band(node_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0 and central_node ~= nil and central_node:IsEmpty() local central_node_hole_register_hit_test_hole = central_node_hole @@ -1516,7 +2313,10 @@ function ImGui.DockNodeUpdate(node) end end if central_node_hole_register_hit_test_hole then - IM_ASSERT(node:IsDockSpace()) + -- We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily. + -- (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen + -- covering passthru node we'd have a gap on the edge not covered by the hole) + IM_ASSERT(node:IsDockSpace()) -- We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window.ParentNode local root_node = ImGui.DockNodeGetRootNode(central_node) local root_rect = ImRect(root_node.Pos, root_node.Pos + root_node.Size) local hole_rect = ImRect(central_node.Pos, central_node.Pos + central_node.Size) @@ -1524,6 +2324,7 @@ function ImGui.DockNodeUpdate(node) if hole_rect.Max.x < root_rect.Max.x then hole_rect.Max.x = hole_rect.Max.x - g.WindowsBorderHoverPadding end if hole_rect.Min.y > root_rect.Min.y then hole_rect.Min.y = hole_rect.Min.y + g.WindowsBorderHoverPadding end if hole_rect.Max.y < root_rect.Max.y then hole_rect.Max.y = hole_rect.Max.y - g.WindowsBorderHoverPadding end + -- GetForegroundDrawList():AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255)) if central_node_hole and not IsRectInverted(hole_rect) then ImGui.SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min) if host_window.ParentWindow then @@ -1532,6 +2333,7 @@ function ImGui.DockNodeUpdate(node) end end + -- Update position/size, process and draw resizing splitters if node:IsRootNode() and host_window then ImGui.DockNodeTreeUpdatePosSize(node, host_window.Pos, host_window.Size) ImGui.PushStyleColor(ImGuiCol.Separator, g.Style.Colors[ImGuiCol.Border]) @@ -1541,6 +2343,7 @@ function ImGui.DockNodeUpdate(node) ImGui.PopStyleColor(3) end + -- Draw empty node background (currently can only be the Central Node) if host_window and node:IsEmpty() and node.IsVisible then host_window.DrawList:ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG) node.LastBgColor = (bit32.band(node_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0) and 0 or ImGui.GetColorU32(ImGuiCol.DockingEmptyBg) @@ -1550,6 +2353,9 @@ function ImGui.DockNodeUpdate(node) node.IsBgDrawnThisFrame = true end + -- Draw whole dockspace background if ImGuiDockNodeFlags.PassthruCentralNode if set. + -- We need to draw a background at the root level if requested by ImGuiDockNodeFlags.PassthruCentralNode, but we will only know the correct pos/size + -- _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order! local render_dockspace_bg = node:IsRootNode() and host_window ~= nil and bit32.band(node_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0 if render_dockspace_bg and node.IsVisible then host_window.DrawList:ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG) @@ -1560,6 +2366,7 @@ function ImGui.DockNodeUpdate(node) end end + -- Draw and populate Tab Bar if host_window then host_window.DrawList:ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG) end if host_window and node.Windows.Size > 0 then ImGui.DockNodeUpdateTabBar(node, host_window) @@ -1574,20 +2381,27 @@ function ImGui.DockNodeUpdate(node) node.SelectedTabId = node.Windows.Data[1].TabId end + -- Draw payload drop target if host_window and node.IsVisible then if node:IsRootNode() and (g.MovingWindow == nil or g.MovingWindow.RootWindowDockTree ~= host_window) then ImGui.BeginDockableDragDropTarget(host_window) end end + -- We update this after DockNodeUpdateTabBar() node.LastFrameActive = g.FrameCount + -- Recurse into children + -- FIXME-DOCK FIXME-OPT: Should not need to recurse into children if host_window then if node.ChildNodes[0] then ImGui.DockNodeUpdate(node.ChildNodes[0]) end if node.ChildNodes[1] then ImGui.DockNodeUpdate(node.ChildNodes[1]) end + + -- Render outer borders last (after the tab bar) if node:IsRootNode() then ImGui.RenderWindowOuterBorders(host_window) end end + -- End host window if beginned_into_host_window then ImGui.End() end end @@ -1597,6 +2411,7 @@ local GWindowDockStyleColors = { } ImGui.GWindowDockStyleColors = GWindowDockStyleColors +-- Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame. local function TabItemComparerByDockOrder(ta, tb) local a, b = ta.Window, tb.Window local ao = (a.DockOrder == -1) and INT_MAX or a.DockOrder @@ -1605,12 +2420,19 @@ local function TabItemComparerByDockOrder(ta, tb) return a.BeginOrderWithinContext < b.BeginOrderWithinContext end +-- Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node. +-- This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented) +-- Custom overrides may want to decorate, group, sort entries. +-- Please note those are internal structures: if you copy this expect occasional breakage. +-- (if you don't need to modify the "Tabs.Size == 1" behavior/path it is recommend you call this function in your handler) function ImGui.DockNodeWindowMenuHandler_Default(ctx, node, tab_bar) if tab_bar.Tabs.Size == 1 then + -- "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table. if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.DockingHideTabBar), nil, node:IsHiddenTabBar()) then node.WantHiddenTabBarToggle = true end else + -- Display a selectable list of windows in this docking node for tab_n = 1, tab_bar.Tabs.Size do local tab = tab_bar.Tabs.Data[tab_n] if bit32.band(tab.Flags, ImGuiTabItemFlags.Button) == 0 then @@ -1625,6 +2447,7 @@ function ImGui.DockNodeWindowMenuHandler_Default(ctx, node, tab_bar) end function ImGui.DockNodeWindowMenuUpdate(node, tab_bar) + -- Try to position the menu so it is more likely to stays within the same viewport local g = ImGui.GetCurrentContext() if g.Style.WindowMenuButtonPosition == ImGuiDir.Left then ImGui.SetNextWindowPos(ImVec2(node.Pos.x, node.Pos.y + ImGui.GetFrameHeight()), ImGuiCond.Always, ImVec2(0.0, 0.0)) @@ -1638,6 +2461,7 @@ function ImGui.DockNodeWindowMenuUpdate(node, tab_bar) end end +-- User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button. function ImGui.DockNodeBeginAmendTabBar(node) if node.TabBar == nil or node.HostWindow == nil then return false end if bit32.band(node.MergedFlags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then return false end @@ -1656,11 +2480,15 @@ function ImGui.DockNodeEndAmendTabBar() end local function IsDockNodeTitleBarHighlighted(node, root_node) + -- CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy) local g = ImGui.GetCurrentContext() if g.NavWindowingTarget then return g.NavWindowingTarget.DockNode == node end + + -- FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window) if g.NavWindow and root_node.LastFocusedNodeId == node.ID then + -- FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node) local parent_window = g.NavWindow.RootWindow while bit32.band(parent_window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 do parent_window = parent_window.ParentWindow.RootWindow @@ -1675,6 +2503,7 @@ local function IsDockNodeTitleBarHighlighted(node, root_node) return false end +-- Submit the tab bar corresponding to a dock node and various housekeeping details. function ImGui.DockNodeUpdateTabBar(node, host_window) local g = ImGui.GetCurrentContext() local style = g.Style @@ -1683,30 +2512,37 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) node.WantCloseAll = false node.WantCloseTabId = 0 + -- Decide if we should use a focused title bar color local is_focused = false local root_node = ImGui.DockNodeGetRootNode(node) if IsDockNodeTitleBarHighlighted(node, root_node) then is_focused = true end + -- Hidden tab bar will show a triangle on the upper-left (in Begin) if node:IsHiddenTabBar() or node:IsNoTabBar() then node.VisibleWindow = (node.Windows.Size > 0) and node.Windows.Data[1] or nil node.IsFocused = is_focused if is_focused then node.LastFrameFocused = g.FrameCount end if node.VisibleWindow then + -- Notify root of visible window (used to display title in OS task bar) if is_focused or root_node.VisibleWindow == nil then root_node.VisibleWindow = node.VisibleWindow end if node.TabBar then node.TabBar.VisibleTabId = node.VisibleWindow.TabId end end return end + -- Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed local backup_skip_item = host_window.SkipItems if not node:IsDockSpace() then host_window.SkipItems = false host_window.DC.NavLayerCurrent = ImGuiNavLayer.Menu end + -- Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID. + -- This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs, + -- as docked windows themselves will override the stack with their own root ID. ImGui.PushOverrideID(node.ID) local tab_bar = node.TabBar - local tab_bar_is_recreated = (tab_bar == nil) + local tab_bar_is_recreated = (tab_bar == nil) -- Tab bar are automatically destroyed when a node gets hidden if tab_bar == nil then ImGui.DockNodeAddTabBar(node) tab_bar = node.TabBar @@ -1718,6 +2554,8 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) local node_flags = node.MergedFlags local has_window_menu_button = bit32.band(node_flags, ImGuiDockNodeFlags.NoWindowMenuButton) == 0 and (style.WindowMenuButtonPosition ~= ImGuiDir.None) + -- In a dock node, the Collapse Button turns into the Window Menu button. + -- FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes? if has_window_menu_button and ImGui.IsPopupOpen("#WindowMenu") then local next_selected_tab_id = tab_bar.NextSelectedTabId ImGui.DockNodeWindowMenuUpdate(node, tab_bar) @@ -1727,8 +2565,10 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) is_focused = is_focused or node.IsFocused end + -- Layout local title_bar_rect, tab_bar_rect, window_menu_button_pos, close_button_pos = ImGui.DockNodeCalcTabBarLayout(node) + -- Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value. local tabs_count_old = tab_bar.Tabs.Size for window_n = 1, node.Windows.Size do local window = node.Windows.Data[window_n] @@ -1737,13 +2577,15 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) end end + -- Title bar if is_focused then node.LastFrameFocused = g.FrameCount end local title_bar_col = ImGui.GetColorU32(host_window.Collapsed and ImGuiCol.TitleBgCollapsed or (is_focused and ImGuiCol.TitleBgActive or ImGuiCol.TitleBg)) local rounding_flags = ImGui.CalcRoundingFlagsForRectInRect(title_bar_rect, host_window:Rect(), g.Style.DockingSeparatorSize) host_window.DrawList:AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window.WindowRounding, rounding_flags) + -- Docking/Collapse button if has_window_menu_button then - if ImGui.CollapseButton(host_window:GetID("#COLLAPSE"), window_menu_button_pos, node) then + if ImGui.CollapseButton(host_window:GetID("#COLLAPSE"), window_menu_button_pos, node) then -- == DockNodeGetWindowMenuButtonId(node) ImGui.OpenPopup("#WindowMenu") end if ImGui.IsItemActive() then focus_tab_id = tab_bar.SelectedTabId end @@ -1752,9 +2594,11 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) end end + -- If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value local tabs_unsorted_start = tab_bar.Tabs.Size -- 0-based local tab_n = tab_bar.Tabs.Size - 1 while tab_n >= 0 and bit32.band(tab_bar.Tabs.Data[tab_n + 1].Flags, ImGuiTabItemFlags.Unsorted) ~= 0 do + -- FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting? local t = tab_bar.Tabs.Data[tab_n + 1] t.Flags = bit32.band(t.Flags, bit32.bnot(ImGuiTabItemFlags.Unsorted)) tabs_unsorted_start = tab_n @@ -1767,10 +2611,12 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) for i, t in ipairs(slice) do tab_bar.Tabs.Data[tabs_unsorted_start + i] = t end end + -- Apply NavWindow focus back to the tab bar if g.NavWindow and g.NavWindow.RootWindow.DockNode == node then tab_bar.SelectedTabId = g.NavWindow.RootWindow.TabId end + -- Selected newly added tabs, or persistent tab ID if the tab bar was just recreated if tab_bar_is_recreated and ImGui.TabBarFindTabByID(tab_bar, node.SelectedTabId) ~= nil then tab_bar.SelectedTabId = node.SelectedTabId tab_bar.NextSelectedTabId = node.SelectedTabId @@ -1779,27 +2625,32 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) tab_bar.NextSelectedTabId = tab_bar.SelectedTabId end - local tab_bar_flags = bit32.bor(ImGuiTabBarFlags.Reorderable, ImGuiTabBarFlags.AutoSelectNewTabs) + -- Begin tab bar + local tab_bar_flags = bit32.bor(ImGuiTabBarFlags.Reorderable, ImGuiTabBarFlags.AutoSelectNewTabs) -- | ImGuiTabBarFlags.NoTabListScrollingButtons) tab_bar_flags = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.SaveSettings, ImGuiTabBarFlags.DockNode) - tab_bar_flags = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.FittingPolicyMixed) + tab_bar_flags = bit32.bor(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 = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.DrawSelectedOverline) if not host_window.Collapsed and is_focused then tab_bar_flags = bit32.bor(tab_bar_flags, ImGuiTabBarFlags.IsFocused) end - tab_bar.ID = node.ID - tab_bar.SeparatorMinX = node.Pos.x + host_window.WindowBorderSize + tab_bar.ID = node.ID -- GetID("#TabBar") + tab_bar.SeparatorMinX = node.Pos.x + host_window.WindowBorderSize -- Separator cover the whole node width tab_bar.SeparatorMaxX = node.Pos.x + node.Size.x - host_window.WindowBorderSize ImGui.BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags) + -- host_window.DrawList:AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255)) + -- Backup style colors local backup_style_cols = {} for color_n = 0, ImGuiWindowDockStyleCol.COUNT - 1 do local c = g.Style.Colors[GWindowDockStyleColors[color_n]] backup_style_cols[color_n] = ImVec4(c.x, c.y, c.z, c.w) end + -- Submit actual tabs node.VisibleWindow = nil for window_n = 1, node.Windows.Size do local window = node.Windows.Data[window_n] + -- FIXME: Not sure if that's still taken/useful, as windows are normally removed in DockNodeUpdateFlagsAndCollapse(). if not (window.LastFrameActive + 1 < g.FrameCount and node_was_active) then local tab_item_flags = 0 tab_item_flags = bit32.bor(tab_item_flags, window.WindowClass.TabItemFlagsOverrideSet or 0) @@ -1810,33 +2661,42 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) tab_item_flags = bit32.bor(tab_item_flags, ImGuiTabItemFlags.NoCloseWithMiddleMouseButton) end + -- Apply stored style overrides for the window for color_n = 0, ImGuiWindowDockStyleCol.COUNT - 1 do ImVec4_Copy(g.Style.Colors[GWindowDockStyleColors[color_n]], ImGui.ColorConvertU32ToFloat4(window.DockStyle.Colors[color_n])) end + -- Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so) local _, tab_open = ImGui.TabItemEx(tab_bar, window.Name, window.HasCloseButton and true or nil, tab_item_flags, window) if tab_open == false then node.WantCloseTabId = window.TabId end if tab_bar.VisibleTabId == window.TabId then node.VisibleWindow = window end + -- 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 = ImRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max) + -- Update navigation ID on menu layer if g.NavWindow and g.NavWindow.RootWindow == window and bit32.band(window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) == 0 then host_window.NavLastIds[1] = window.TabId end end end + -- Restore style colors for color_n = 0, ImGuiWindowDockStyleCol.COUNT - 1 do ImVec4_Copy(g.Style.Colors[GWindowDockStyleColors[color_n]], backup_style_cols[color_n]) end + -- Notify root of visible window (used to display title in OS task bar) if node.VisibleWindow then if is_focused or root_node.VisibleWindow == nil then root_node.VisibleWindow = node.VisibleWindow end end + -- Close button (after VisibleWindow was updated) + -- Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow.TabId may be ~= from tab_bar.SelectedTabId local close_button_is_enabled = node.HasCloseButton and node.VisibleWindow and node.VisibleWindow.HasCloseButton local close_button_is_visible = node.HasCloseButton + -- local close_button_is_visible = close_button_is_enabled -- Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one) if close_button_is_visible then if not close_button_is_enabled then ImGui.PushItemFlag(ImGuiItemFlags.Disabled, true) @@ -1847,39 +2707,55 @@ function ImGui.DockNodeUpdateTabBar(node, host_window) node.WantCloseAll = true for n = 1, tab_bar.Tabs.Size do ImGui.TabBarCloseTab(tab_bar, tab_bar.Tabs.Data[n]) end end + -- if IsItemActive() then + -- focus_tab_id = tab_bar.SelectedTabId if not close_button_is_enabled then ImGui.PopStyleColor() ImGui.PopItemFlag() end end + -- When clicking on the title bar outside of tabs, we still focus the selected tab for that node + -- FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them. local title_bar_id = host_window:GetID("#TITLEBAR") if g.HoveredId == 0 or g.HoveredId == title_bar_id or g.ActiveId == title_bar_id then + -- AllowOverlap mode required for appending into dock node tab bar, + -- otherwise dragging window will steal HoveredId and amended tabs cannot get them. ImGui.KeepAliveID(title_bar_id) local _, _, held = ImGui.ButtonBehavior(title_bar_rect, title_bar_id, ImGuiButtonFlags.AllowOverlap) if g.HoveredId == title_bar_id then g.LastItemData.ID = title_bar_id end if held then if ImGui.IsMouseClicked(0) then focus_tab_id = tab_bar.SelectedTabId end + + -- Forward moving request to selected window local tab = ImGui.TabBarFindTabByID(tab_bar, tab_bar.SelectedTabId) if tab then - ImGui.StartMouseMovingWindowOrNode(tab.Window or node.HostWindow, node, false) + ImGui.StartMouseMovingWindowOrNode(tab.Window or node.HostWindow, node, false) -- Undock from tab bar empty space end end end + -- Forward focus from host node to selected window + -- if is_focused and g.NavWindow == host_window and not g.NavWindowingTarget then + -- focus_tab_id = tab_bar.SelectedTabId + + -- When clicked on a tab we requested focus to the docked child + -- This overrides the value set by "forward focus from host node to selected window". if tab_bar.NextSelectedTabId ~= 0 then focus_tab_id = tab_bar.NextSelectedTabId end + -- Apply navigation focus if focus_tab_id ~= 0 then local tab = ImGui.TabBarFindTabByID(tab_bar, focus_tab_id) if tab and tab.Window then ImGui.FocusWindow(tab.Window) - if g.NavId == 0 then ImGui.NavInitWindow(tab.Window, false) end + if g.NavId == 0 then ImGui.NavInitWindow(tab.Window, false) end -- only init if FocusWindow() didn't restore anything. end end ImGui.EndTabBar() ImGui.PopID() + -- Restore SkipItems flag if not node:IsDockSpace() then host_window.DC.NavLayerCurrent = ImGuiNavLayer.Main host_window.SkipItems = backup_skip_item @@ -1895,6 +2771,7 @@ function ImGui.DockNodeRemoveTabBar(node) if node.TabBar == nil then return end node.TabBar = nil end + local function DockNodeIsDropAllowedOne(payload, host_window) if host_window.DockNodeAsHost and host_window.DockNodeAsHost:IsDockSpace() and payload.BeginOrderWithinContext < host_window.BeginOrderWithinContext then return false @@ -1909,10 +2786,15 @@ local function DockNodeIsDropAllowedOne(payload, host_window) if not pass then return false end end + -- Prevent docking any window created above a popup + -- Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features), + -- by e.g. adding a 'if not ImGui.IsWindowWithinBeginStackOf(host_window, popup_window)' test. + -- But it would requires more work on our end because the dock host windows is technically created in NewFrame() + -- and our .ParentXXX and .RootXXX pointers inside windows are currently mislading or lacking. local g = ImGui.GetCurrentContext() for i = g.OpenPopupStack.Size, 1, -1 do local popup_window = g.OpenPopupStack.Data[i].Window - if popup_window and ImGui.IsWindowWithinBeginStackOf(payload, popup_window) then + if popup_window and ImGui.IsWindowWithinBeginStackOf(payload, popup_window) then -- Payload is created from within a popup begin stack. return false end end @@ -1920,7 +2802,7 @@ local function DockNodeIsDropAllowedOne(payload, host_window) end function ImGui.DockNodeIsDropAllowed(host_window, root_payload) - if root_payload.DockNodeAsHost and root_payload.DockNodeAsHost:IsSplitNode() then return true end + if root_payload.DockNodeAsHost and root_payload.DockNodeAsHost:IsSplitNode() then return true end -- FIXME-DOCK: Missing filtering local payload_count = root_payload.DockNodeAsHost and root_payload.DockNodeAsHost.Windows.Size or 1 for payload_n = 1, payload_count do local payload = root_payload.DockNodeAsHost and root_payload.DockNodeAsHost.Windows.Data[payload_n] or root_payload @@ -1929,6 +2811,8 @@ function ImGui.DockNodeIsDropAllowed(host_window, root_payload) return false end +-- window menu button == collapse button when not in a dock node. +-- FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code. --- @return ImRect title_rect, ImRect tab_bar_rect, ImVec2 window_menu_button_pos, ImVec2? close_button_pos function ImGui.DockNodeCalcTabBarLayout(node) local g = ImGui.GetCurrentContext() @@ -1967,6 +2851,7 @@ function ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir, pos_new[o] = pos_old[o] size_new[o] = size_old[o] + -- Distribute size on given axis (with a desired size or equally) local w_avail = size_old[a] - dock_spacing if size_new_desired[a] > 0.0 and size_new_desired[a] <= w_avail * 0.5 then size_new[a] = size_new_desired[a] @@ -1976,6 +2861,7 @@ function ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, dir, size_old[a] = IM_TRUNC(w_avail - size_new[a]) end + -- Position each node if dir == ImGuiDir.Right or dir == ImGuiDir.Down then pos_new[a] = pos_old[a] + size_old[a] + dock_spacing elseif dir == ImGuiDir.Left or dir == ImGuiDir.Up then @@ -1991,14 +2877,18 @@ local function ImGetDirQuadrantFromDeltaLocal(dx, dy) return (dy > 0.0) and ImGuiDir.Down or ImGuiDir.Up end +-- Retrieve the drop rectangles for a given direction or for the center + perform hit testing. --- @return bool hit, ImRect out_r function ImGui.DockNodeCalcDropRectsAndTestMousePos(parent, dir, outer_docking, test_mouse_pos) local g = ImGui.GetCurrentContext() local parent_smaller_axis = ImMin(parent:GetWidth(), parent:GetHeight()) local hs_for_central_nodes = ImMin(g.FontSize * 1.5, ImMax(g.FontSize * 0.5, parent_smaller_axis / 8.0)) - local hs_w, hs_h, off + local hs_w, hs_h, off -- Half-size, longer axis / Half-size, smaller axis / Distance from edge or center if outer_docking then + -- hs_w = ImTrunc(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0, g.FontSize * 0.5, g.FontSize * 8.0)) + -- hs_h = ImTrunc(hs_w * 0.15) + -- off = ImVec2(ImTrunc(parent:GetWidth() * 0.5 - GetFrameHeightWithSpacing() * 1.4 - hs_h), ImTrunc(parent:GetHeight() * 0.5 - GetFrameHeightWithSpacing() * 1.4 - hs_h)) hs_w = ImTrunc(hs_for_central_nodes * 1.50) hs_h = ImTrunc(hs_for_central_nodes * 0.80) off = ImVec2(ImTrunc(parent:GetWidth() * 0.5 - hs_h), ImTrunc(parent:GetHeight() * 0.5 - hs_h)) @@ -2021,6 +2911,7 @@ function ImGui.DockNodeCalcDropRectsAndTestMousePos(parent, dir, outer_docking, local hit_r = ImRect(out_r.Min, out_r.Max) if not outer_docking then + -- Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides hit_r:Expand(ImTrunc(hs_w * 0.30)) local mdx, mdy = test_mouse_pos.x - c.x, test_mouse_pos.y - c.y local mouse_delta_len2 = mdx * mdx + mdy * mdy @@ -2036,13 +2927,19 @@ function ImGui.DockNodeCalcDropRectsAndTestMousePos(parent, dir, outer_docking, return hit_r:Contains(test_mouse_pos), out_r end +-- host_node may be nil if the window doesn't have a DockNode already. +-- FIXME-DOCK: This is misnamed since it's also doing the filtering. function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, payload_node, data, is_explicit_target, is_outer_docking) local g = ImGui.GetCurrentContext() + -- There is an edge case when docking into a dockspace which only has inactive nodes. + -- In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive. + -- Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference. if payload_node == nil then payload_node = payload_window.DockNodeAsHost end local ref_node_for_rect = (host_node and not host_node.IsVisible) and ImGui.DockNodeGetRootNode(host_node) or host_node if ref_node_for_rect then IM_ASSERT(ref_node_for_rect.IsVisible == true) end + -- Filter, figure out where we are allowed to dock local src_node_flags = payload_node and payload_node.MergedFlags or payload_window.WindowClass.DockNodeFlagsOverrideSet local dst_node_flags = host_node and host_node.MergedFlags or host_window.WindowClass.DockNodeFlagsOverrideSet data.IsCenterAvailable = true @@ -2054,7 +2951,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, data.IsCenterAvailable = false elseif host_node and bit32.band(dst_node_flags, ImGuiDockNodeFlags.NoDockingOverCentralNode) ~= 0 and host_node:IsCentralNode() then data.IsCenterAvailable = false - elseif (not host_node or not host_node:IsEmpty()) and payload_node and payload_node:IsSplitNode() and (payload_node.OnlyNodeWithWindows == nil) then + elseif (not host_node or not host_node:IsEmpty()) and payload_node and payload_node:IsSplitNode() and (payload_node.OnlyNodeWithWindows == nil) then -- Is _visibly_ split? data.IsCenterAvailable = false elseif bit32.band(src_node_flags, ImGuiDockNodeFlags.NoDockingOverOther) ~= 0 and (not host_node or not host_node:IsEmpty()) then data.IsCenterAvailable = false @@ -2071,6 +2968,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, data.IsSidesAvailable = false end + -- Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split) data.FutureNode.HasCloseButton = (host_node and host_node.HasCloseButton or (not host_node and host_window.HasCloseButton)) or payload_window.HasCloseButton data.FutureNode.HasWindowMenuButton = host_node and true or (bit32.band(host_window.Flags, ImGuiWindowFlags.NoCollapse) == 0) local rp = ref_node_for_rect and ref_node_for_rect.Pos or host_window.Pos @@ -2078,6 +2976,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, data.FutureNode.Pos = ImVec2(rp.x, rp.y) data.FutureNode.Size = ImVec2(rs.x, rs.y) + -- Calculate drop shapes geometry for allowed splitting directions data.SplitNode = host_node data.SplitDir = ImGuiDir.None data.IsSplitDirExplicit = false @@ -2094,11 +2993,13 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, end end + -- When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar data.IsDropAllowed = (data.SplitDir ~= ImGuiDir.None) or data.IsCenterAvailable if not is_explicit_target and not data.IsSplitDirExplicit and not g.IO.ConfigDockingWithShift then data.IsDropAllowed = false end + -- Calculate split area data.SplitRatio = 0.0 if data.SplitDir ~= ImGuiDir.None then local split_dir = data.SplitDir @@ -2107,6 +3008,7 @@ function ImGui.DockNodePreviewDockSetup(host_window, host_node, payload_window, local size_new, size_old = ImVec2(0, 0), ImVec2(data.FutureNode.Size.x, data.FutureNode.Size.y) ImGui.DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window.Size) + -- Calculate split ratio so we can pass it down the docking request local split_ratio = ImSaturate(size_new[split_axis] / data.FutureNode.Size[split_axis]) data.FutureNode.Pos = pos_new data.FutureNode.Size = size_new @@ -2116,17 +3018,21 @@ end function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, data) local g = ImGui.GetCurrentContext() - IM_ASSERT(g.CurrentWindow == host_window) + IM_ASSERT(g.CurrentWindow == host_window) -- Because we rely on font size to calculate tab sizes + -- With this option, we only display the preview on the target viewport, and the payload viewport is made transparent. + -- To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes. local is_transparent_payload = g.IO.ConfigDockingTransparentPayload local overlay_draw_lists = { ImGui.GetForegroundDrawList(host_window.Viewport) } + -- Draw main preview rectangle local overlay_col_main = ImGui.GetColorU32(ImGuiCol.DockingPreview, is_transparent_payload and 0.60 or 0.40) local overlay_col_drop = ImGui.GetColorU32(ImGuiCol.DockingPreview, is_transparent_payload and 0.90 or 0.70) local overlay_col_drop_hovered = ImGui.GetColorU32(ImGuiCol.DockingPreview, is_transparent_payload and 1.20 or 1.00) local overlay_col_lines = ImGui.GetColorU32(ImGuiCol.NavWindowingHighlight, is_transparent_payload and 0.80 or 0.60) + -- Display area preview local can_preview_tabs = (root_payload.DockNodeAsHost == nil or root_payload.DockNodeAsHost.Windows.Size > 0) if data.IsDropAllowed then local overlay_rect = data.FutureNode:Rect() @@ -2140,27 +3046,32 @@ function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, d end end + -- Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read) if data.IsDropAllowed and can_preview_tabs and data.SplitDir == ImGuiDir.None and data.IsCenterAvailable then + -- Compute target tab bar geometry so we can locate our preview tabs local _, tab_bar_rect = ImGui.DockNodeCalcTabBarLayout(data.FutureNode) local tab_pos = ImVec2(tab_bar_rect.Min.x, tab_bar_rect.Min.y) if host_node and host_node.TabBar then if not host_node:IsHiddenTabBar() and not host_node:IsNoTabBar() then - tab_pos.x = tab_pos.x + host_node.TabBar.WidthAllTabs + g.Style.ItemInnerSpacing.x + tab_pos.x = tab_pos.x + host_node.TabBar.WidthAllTabs + g.Style.ItemInnerSpacing.x -- We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission. else tab_pos.x = tab_pos.x + g.Style.ItemInnerSpacing.x + ImGui.TabItemCalcSize(host_node.Windows.Data[1]).x end elseif bit32.band(host_window.Flags, ImGuiWindowFlags.DockNodeHost) == 0 then - tab_pos.x = tab_pos.x + g.Style.ItemInnerSpacing.x + ImGui.TabItemCalcSize(host_window).x + tab_pos.x = tab_pos.x + g.Style.ItemInnerSpacing.x + ImGui.TabItemCalcSize(host_window).x -- Account for slight offset which will be added when changing from title bar to tab bar end + -- Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows) if root_payload.DockNodeAsHost then IM_ASSERT(root_payload.DockNodeAsHost.Windows.Size <= root_payload.DockNodeAsHost.TabBar.Tabs.Size) end local tab_bar_with_payload = root_payload.DockNodeAsHost and root_payload.DockNodeAsHost.TabBar or nil local payload_count = tab_bar_with_payload and tab_bar_with_payload.Tabs.Size or 1 for payload_n = 1, payload_count do + -- DockNode's TabBar may have non-window Tabs manually appended by user local payload_window = tab_bar_with_payload and tab_bar_with_payload.Tabs.Data[payload_n].Window or root_payload if not (tab_bar_with_payload and payload_window == nil) and DockNodeIsDropAllowedOne(payload_window, host_window) then + -- Calculate the tab bounding box for each payload window local tab_size = ImGui.TabItemCalcSize(payload_window) local tab_bb = ImRect(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y) tab_pos.x = tab_pos.x + tab_size.x + g.Style.ItemInnerSpacing.x @@ -2182,7 +3093,8 @@ function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, d end end - local scale = g.Style._MainScale or 1.0 + -- Display drop boxes + local scale = g.Style._MainScale or 1.0 -- FIXME-DPI local overlay_rounding = ImMax(math.floor(3.0 * scale), g.Style.FrameRounding) for dir = ImGuiDir.None, ImGuiDir.COUNT - 1 do local draw_r = data.DropRectsDraw[dir + 1] @@ -2204,15 +3116,25 @@ function ImGui.DockNodePreviewDockRender(host_window, host_node, root_payload, d end end end + + -- Stop after ImGuiDir.None if (host_node and bit32.band(host_node.MergedFlags, ImGuiDockNodeFlags.NoDockingSplit) ~= 0) or g.IO.ConfigDockingNoSplit then return end end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: ImGuiDockNode Tree manipulation functions ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockNodeTreeSplit() +-- - DockNodeTreeMerge() +-- - DockNodeTreeUpdatePosSize() +-- - DockNodeTreeUpdateSplitterFindTouchingNode() +-- - DockNodeTreeUpdateSplitter() +-- - DockNodeTreeFindFallbackLeafNode() +-- - DockNodeTreeFindNodeByPos() +------------------------------------------------------------------------------- function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_child_idx, split_ratio, new_node) local g = ImGui.GetCurrentContext() @@ -2237,7 +3159,7 @@ function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_c local a = split_axis local size_avail = parent_node.Size[a] - g.Style.DockingSeparatorSize size_avail = ImMax(size_avail, g.Style.WindowMinSize[a] * 2.0) - IM_ASSERT(size_avail > 0.0) + IM_ASSERT(size_avail > 0.0) -- If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting. child_0.SizeRef = ImVec2(parent_node.Size.x, parent_node.Size.y) child_1.SizeRef = ImVec2(parent_node.Size.x, parent_node.Size.y) child_0.SizeRef[a] = ImTrunc(size_avail * split_ratio) @@ -2248,6 +3170,7 @@ function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_c ImGui.DockNodeUpdateHasCentralNodeChild(ImGui.DockNodeGetRootNode(parent_node)) ImGui.DockNodeTreeUpdatePosSize(parent_node, parent_node.Pos, parent_node.Size) + -- Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags.CentralNode property) child_0.SharedFlags = bit32.band(parent_node.SharedFlags, ImGuiDockNodeFlags.SharedFlagsInheritMask_) child_1.SharedFlags = bit32.band(parent_node.SharedFlags, ImGuiDockNodeFlags.SharedFlagsInheritMask_) child_inheritor.LocalFlags = bit32.band(parent_node.LocalFlags, ImGuiDockNodeFlags.LocalFlagsTransferMask_) @@ -2261,6 +3184,7 @@ function ImGui.DockNodeTreeSplit(ctx, parent_node, split_axis, split_inheritor_c end function ImGui.DockNodeTreeMerge(ctx, parent_node, merge_lead_child) + -- When called from DockContextProcessUndockNode() it is possible that one of the child is nil. local child_0 = parent_node.ChildNodes[0] local child_1 = parent_node.ChildNodes[1] IM_ASSERT(child_0 or child_1) @@ -2273,7 +3197,7 @@ function ImGui.DockNodeTreeMerge(ctx, parent_node, merge_lead_child) local backup_last_explicit_size = ImVec2(parent_node.SizeRef.x, parent_node.SizeRef.y) ImGui.DockNodeMoveChildNodes(parent_node, merge_lead_child) if child_0 then - ImGui.DockNodeMoveWindows(parent_node, child_0) + ImGui.DockNodeMoveWindows(parent_node, child_0) -- Generally only 1 of the 2 child node will have windows DockSettingsRenameNodeReferences(child_0.ID, parent_node.ID) end if child_1 then @@ -2287,18 +3211,23 @@ function ImGui.DockNodeTreeMerge(ctx, parent_node, merge_lead_child) parent_node.VisibleWindow = merge_lead_child.VisibleWindow parent_node.SizeRef = backup_last_explicit_size + -- Flags transfer local M = ImGuiDockNodeFlags.LocalFlagsTransferMask_ - parent_node.LocalFlags = bit32.band(parent_node.LocalFlags, bit32.bnot(M)) + parent_node.LocalFlags = bit32.band(parent_node.LocalFlags, bit32.bnot(M)) -- Preserve Dockspace flag parent_node.LocalFlags = bit32.bor(parent_node.LocalFlags, bit32.band(child_0 and child_0.LocalFlags or 0, M)) parent_node.LocalFlags = bit32.bor(parent_node.LocalFlags, bit32.band(child_1 and child_1.LocalFlags or 0, M)) - parent_node.LocalFlagsInWindows = bit32.bor(child_0 and child_0.LocalFlagsInWindows or 0, child_1 and child_1.LocalFlagsInWindows or 0) + parent_node.LocalFlagsInWindows = bit32.bor(child_0 and child_0.LocalFlagsInWindows or 0, child_1 and child_1.LocalFlagsInWindows or 0) -- FIXME: Would be more consistent to update from actual windows parent_node:UpdateMergedFlags() if child_0 then ImGui.DockContextDeleteNode(ctx, child_0) end if child_1 then ImGui.DockContextDeleteNode(ctx, child_1) end end +-- Update Pos/Size for a node hierarchy (don't affect child Windows yet) +-- (Depth-first, Pre-Order) function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_node) + -- During the regular dock node update we write to all nodes. + -- 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away. local g = ImGui.GetCurrentContext() local write_to_node = only_write_to_single_node == nil or only_write_to_single_node == node if write_to_node then @@ -2323,8 +3252,15 @@ function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_n local a = node.SplitAxis local size_avail = ImMax(size[a] - spacing, 0.0) + -- Size allocation policy + -- 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows. local size_min_each = ImTrunc(ImMin(size_avail, g.Style.WindowMinSize[a] * 2.0) * 0.5) + -- FIXME: Blocks 2) and 3) are essentially doing nearly the same thing. + -- Difference are: write-back to SizeRef; application of a minimum size; rounding before ImTrunc() + -- Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce + + -- 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge) if child_0.WantLockSizeOnce and not child_1.WantLockSizeOnce then child_0_size[a] = ImMin(size_avail - 1.0, child_0.Size[a]); child_0.SizeRef[a] = child_0_size[a] child_1_size[a] = size_avail - child_0_size[a]; child_1.SizeRef[a] = child_1_size[a] @@ -2332,9 +3268,13 @@ function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_n child_1_size[a] = ImMin(size_avail - 1.0, child_1.Size[a]); child_1.SizeRef[a] = child_1_size[a] child_0_size[a] = size_avail - child_1_size[a]; child_0.SizeRef[a] = child_0_size[a] elseif child_0.WantLockSizeOnce and child_1.WantLockSizeOnce then + -- FIXME-DOCK: We cannot honor the requested size, so apply ratio. + -- Currently this path will only be taken if code programmatically sets WantLockSizeOnce local split_ratio = child_0_size[a] / (child_0_size[a] + child_1_size[a]) child_0_size[a] = ImTrunc(size_avail * split_ratio); child_0.SizeRef[a] = child_0_size[a] child_1_size[a] = size_avail - child_0_size[a]; child_1.SizeRef[a] = child_1_size[a] + + -- 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node elseif child_0.SizeRef[a] ~= 0.0 and child_1.HasCentralNodeChild then child_0_size[a] = ImMin(size_avail - size_min_each, child_0.SizeRef[a]) child_1_size[a] = size_avail - child_0_size[a] @@ -2342,6 +3282,7 @@ function ImGui.DockNodeTreeUpdatePosSize(node, pos, size, only_write_to_single_n child_1_size[a] = ImMin(size_avail - size_min_each, child_1.SizeRef[a]) child_0_size[a] = size_avail - child_1_size[a] else + -- 4) Otherwise distribute according to the relative ratio of each SizeRef value local split_ratio = child_0.SizeRef[a] / (child_0.SizeRef[a] + child_1.SizeRef[a]) child_0_size[a] = ImMax(size_min_each, ImTrunc(size_avail * split_ratio + 0.5)) child_1_size[a] = size_avail - child_0_size[a] @@ -2377,8 +3318,9 @@ local function DockNodeTreeUpdateSplitterFindTouchingNode(node, axis, side, touc end end -local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 +local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 -- Reduce visual noise by only highlighting the border after a certain time. +-- (Depth-First, Pre-Order) function ImGui.DockNodeTreeUpdateSplitter(node) if node:IsLeafNode() then return end @@ -2387,27 +3329,32 @@ function ImGui.DockNodeTreeUpdateSplitter(node) local child_0 = node.ChildNodes[0] local child_1 = node.ChildNodes[1] if child_0.IsVisible and child_1.IsVisible then + -- Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally) local axis = node.SplitAxis IM_ASSERT(axis ~= ImGuiAxis.None) local a, o = axis, 3 - axis -- the port's ImGuiAxis is 1-based (X=1,Y=2): it is directly the ImVec2 index local bb = ImRect(ImVec2(child_0.Pos.x, child_0.Pos.y), ImVec2(child_1.Pos.x, child_1.Pos.y)) bb.Min[a] = bb.Min[a] + child_0.Size[a] bb.Max[o] = bb.Max[o] + child_1.Size[o] + -- if g.IO.KeyCtrl then GetForegroundDrawList(g.CurrentWindow.Viewport):AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255)) end - local merged_flags = bit32.bor(child_0.MergedFlags, child_1.MergedFlags) + local merged_flags = bit32.bor(child_0.MergedFlags, child_1.MergedFlags) -- Merged flags for BOTH childs local no_resize_axis_flag = (axis == ImGuiAxis.X) and ImGuiDockNodeFlags.NoResizeX or ImGuiDockNodeFlags.NoResizeY if bit32.band(merged_flags, ImGuiDockNodeFlags.NoResize) ~= 0 or bit32.band(merged_flags, no_resize_axis_flag) ~= 0 then local window = g.CurrentWindow window.DrawList:AddRectFilled(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.Separator), g.Style.FrameRounding) else + -- bb.Min[axis] = bb.Min[axis] + 1 -- Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node. + -- bb.Max[axis] = bb.Max[axis] - 1 ImGui.PushID(node.ID) + -- Find resizing limits by gathering list of nodes that are touching the splitter line. local touching_nodes = { [0] = {}, [1] = {} } local min_size = g.Style.WindowMinSize[a] local resize_limits = { [0] = node.ChildNodes[0].Pos[a] + min_size, [1] = node.ChildNodes[1].Pos[a] + node.ChildNodes[1].Size[a] - min_size } local splitter_id = ImGui.GetID("##Splitter") - if g.ActiveId == splitter_id then + if g.ActiveId == splitter_id then -- Only process when splitter is active DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, touching_nodes[0]) DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, touching_nodes[1]) for _, tn in ipairs(touching_nodes[0]) do @@ -2418,6 +3365,7 @@ function ImGui.DockNodeTreeUpdateSplitter(node) end end + -- Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters local cur_size_0 = child_0.Size[a] local cur_size_1 = child_1.Size[a] local min_size_0 = resize_limits[0] - child_0.Pos[a] @@ -2431,10 +3379,13 @@ function ImGui.DockNodeTreeUpdateSplitter(node) child_1.Pos[a] = child_1.Pos[a] - (cur_size_1 - child_1.Size[a]) child_1.Size[a] = cur_size_1; child_1.SizeRef[a] = cur_size_1 + -- Lock the size of every node that is a sibling of the node we are touching + -- This might be less desirable if we can merge sibling of a same axis into the same parental level. for side_n = 0, 1 do for _, touching_node in ipairs(touching_nodes[side_n]) do while touching_node.ParentNode ~= node do if touching_node.ParentNode.SplitAxis == axis then + -- Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize(). local node_to_preserve = touching_node.ParentNode.ChildNodes[side_n] node_to_preserve.WantLockSizeOnce = true end @@ -2467,6 +3418,7 @@ end function ImGui.DockNodeTreeFindVisibleNodeByPos(node, pos) if not node.IsVisible then return nil end + local r = ImRect(node.Pos, node.Pos + node.Size) if not r:Contains(pos) then return nil end if node:IsLeafNode() then return node end @@ -2474,22 +3426,32 @@ function ImGui.DockNodeTreeFindVisibleNodeByPos(node, pos) if hovered_node then return hovered_node end hovered_node = ImGui.DockNodeTreeFindVisibleNodeByPos(node.ChildNodes[1], pos) if hovered_node then return hovered_node end + + -- This means we are hovering over the splitter/spacing of a parent node return node end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - SetWindowDock() [Internal] +-- - DockSpace() +-- - DockSpaceOverViewport() +------------------------------------------------------------------------------- +-- [Internal] Called via SetNextWindowDockID() function ImGui.SetWindowDock(window, dock_id, cond) + -- Test condition (NB: bit 0 is always true) and clear flags for next time if cond and cond ~= 0 and bit32.band(window.SetWindowDockAllowFlags, cond) == 0 then return end window.SetWindowDockAllowFlags = bit32.band(window.SetWindowDockAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing))) if window.DockId == dock_id then return end + -- If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot local g = ImGui.GetCurrentContext() local new_node = ImGui.DockContextFindNodeByID(g, dock_id) if new_node and new_node:IsSplitNode() then + -- Policy: Find central node or latest focused node. We first move back to our root node. new_node = ImGui.DockNodeGetRootNode(new_node) if new_node.CentralNode then IM_ASSERT(new_node.CentralNode:IsCentralNode()) @@ -2505,6 +3467,10 @@ function ImGui.SetWindowDock(window, dock_id, cond) window.DockId = dock_id end +-- Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default. +-- The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors. +-- DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app. +-- When ImGuiDockNodeFlags.KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location). function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) if size_arg == nil then size_arg = ImVec2(0, 0) end if flags == nil then flags = 0 end @@ -2512,11 +3478,14 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) local window = ImGui.GetCurrentWindowRead() if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then return 0 end + -- Early out if parent window is hidden/collapsed + -- This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960. + -- If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true. if window.SkipItems then flags = bit32.bor(flags, ImGuiDockNodeFlags.KeepAliveOnly) end - if bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 then window = ImGui.GetCurrentWindow() end + if bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 then window = ImGui.GetCurrentWindow() end -- call to set window.WriteAccessed = true; - IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.DockSpace) == 0) - IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.CentralNode) == 0) + IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.DockSpace) == 0) -- Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! + IM_ASSERT(bit32.band(flags, ImGuiDockNodeFlags.CentralNode) == 0) -- Flag is automatically set by DockSpace() as LocalFlags, not SharedFlags! (#8145) IM_ASSERT(dockspace_id ~= 0) local node = ImGui.DockContextFindNodeByID(g, dockspace_id) @@ -2527,6 +3496,8 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) node.SharedFlags = flags node.WindowClass = window_class or ImGuiWindowClass() + -- When a DockSpace transitioned form implicit to explicit this may be called a second time + -- It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again. if node.LastFrameActive == g.FrameCount and bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 then IM_ASSERT(node:IsDockSpace() == false, "Cannot call DockSpace() twice a frame with the same ID") node:SetLocalFlags(bit32.bor(node.LocalFlags, ImGuiDockNodeFlags.DockSpace)) @@ -2534,6 +3505,7 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) end node:SetLocalFlags(bit32.bor(node.LocalFlags, ImGuiDockNodeFlags.DockSpace)) + -- Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible if bit32.band(flags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then node.LastFrameAlive = g.FrameCount return dockspace_id @@ -2541,7 +3513,7 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) local content_avail = ImGui.GetContentRegionAvail() local size = ImVec2(ImTrunc(size_arg.x), ImTrunc(size_arg.y)) - if size.x <= 0.0 then size.x = ImMax(content_avail.x + size.x, 4.0) end + if size.x <= 0.0 then size.x = ImMax(content_avail.x + size.x, 4.0) end -- Arbitrary minimum child size (0.0f causing too much issues) if size.y <= 0.0 then size.y = ImMax(content_avail.y + size.y, 4.0) end IM_ASSERT(size.x > 0.0 and size.y > 0.0) @@ -2552,6 +3524,8 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) ImGui.SetNextWindowSize(node.Size) g.NextWindowData.PosUndock = false + -- FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window? + -- FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented) local window_flags = bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.DockNodeHost) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoCollapse, ImGuiWindowFlags.NoTitleBar) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoScrollWithMouse) @@ -2570,29 +3544,41 @@ function ImGui.DockSpace(dockspace_id, size_arg, flags, window_class) IM_ASSERT(node:IsRootNode()) + -- We need to handle the rare case were a central node is missing. + -- This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags.Dockspace. + -- Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split. + -- It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining. + -- The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property, + -- as it doesn't make sense for an empty dockspace to not have this property. if node:IsLeafNode() and not node:IsCentralNode() then node:SetLocalFlags(bit32.bor(node.LocalFlags, ImGuiDockNodeFlags.CentralNode)) end + -- Update the node ImGui.DockNodeUpdate(node) ImGui.End() local bb = ImRect(node.Pos, node.Pos + size) ImGui.ItemSize(size) - ImGui.ItemAdd(bb, dockspace_id, nil, ImGuiItemFlags.NoNav) - if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) ~= 0 and ImGui.IsWindowChildOf(g.HoveredWindow, host_window, false, true) then + ImGui.ItemAdd(bb, dockspace_id, nil, ImGuiItemFlags.NoNav) -- Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?) + if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) ~= 0 and ImGui.IsWindowChildOf(g.HoveredWindow, host_window, false, true) then -- To fullfill IsItemHovered(), similar to EndChild() g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end return dockspace_id end +-- Tips: Use with ImGuiDockNodeFlags.PassthruCentralNode! +-- The limitation with this call is that your window won't have a local menu bar, but you can also use BeginMainMenuBar(). +-- Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function. +-- If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it. function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, window_class) if dockspace_id == nil then dockspace_id = 0 end if dockspace_flags == nil then dockspace_flags = 0 end if viewport == nil then viewport = ImGui.GetMainViewport() end + -- Submit a window filling the entire viewport ImGui.SetNextWindowPos(viewport.WorkPos) ImGui.SetNextWindowSize(viewport.WorkSize) ImGui.SetNextWindowViewport(viewport.ID) @@ -2603,6 +3589,9 @@ function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, wi if bit32.band(dockspace_flags, ImGuiDockNodeFlags.PassthruCentralNode) ~= 0 then host_window_flags = bit32.bor(host_window_flags, ImGuiWindowFlags.NoBackground) end + + -- 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 bit32.band(dockspace_flags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then host_window_flags = bit32.bor(host_window_flags, ImGuiWindowFlags.NoMouseInputs) end @@ -2615,6 +3604,7 @@ function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, wi ImGui.Begin(label, nil, host_window_flags) ImGui.PopStyleVar(3) + -- Submit the dockspace if dockspace_id == 0 then dockspace_id = ImGui.GetID("DockSpace") end ImGui.DockSpace(dockspace_id, ImVec2(0.0, 0.0), dockspace_flags, window_class) @@ -2623,18 +3613,40 @@ function ImGui.DockSpaceOverViewport(dockspace_id, viewport, dockspace_flags, wi return dockspace_id end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Builder Functions ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Very early end-user API to manipulate dock nodes. +-- Only available in imgui_internal.h. Expect this API to change/break! +-- It is expected that those functions are all called _before_ the dockspace node submission. +------------------------------------------------------------------------------- +-- - DockBuilderDockWindow() +-- - DockBuilderGetNode() +-- - DockBuilderSetNodePos() +-- - DockBuilderSetNodeSize() +-- - DockBuilderAddNode() +-- - DockBuilderRemoveNode() +-- - DockBuilderRemoveNodeChildNodes() +-- - DockBuilderRemoveNodeDockedWindows() +-- - DockBuilderSplitNode() +-- - DockBuilderCopyNodeRec() +-- - DockBuilderCopyNode() +-- - DockBuilderCopyWindowSettings() +-- - DockBuilderCopyDockSpace() +-- - DockBuilderFinish() +------------------------------------------------------------------------------- function ImGui.DockBuilderDockWindow(window_name, node_id) + -- We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1) local window_id = ImHashStr(window_name) local window = ImGui.FindWindowByID(window_id) if window then + -- Apply to created window local prev_node_id = window.DockId ImGui.SetWindowDock(window, node_id, ImGuiCond.Always) if window.DockId ~= prev_node_id then window.DockOrder = -1 end else + -- Apply to settings local settings = ImGui.FindWindowSettingsByID(window_id) if settings == nil then settings = ImGui.CreateNewWindowSettings(window_name) end if settings.DockId ~= node_id then settings.DockOrder = -1 end @@ -2668,6 +3680,13 @@ function ImGui.DockBuilderSetNodeSize(node_id, size) node.AuthorityForSize = ImGuiDataAuthority.DockNode end +-- Make sure to use the ImGuiDockNodeFlags.DockSpace flag to create a dockspace node! Otherwise this will create a floating node! +-- - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node. +-- - Dockspace node: calling DockBuilderSetNodePos() is unnecessary. +-- - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand! +-- For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect. +-- - Use (id == 0) to let the system allocate a node identifier. +-- - Existing node with a same id will be removed. function ImGui.DockBuilderAddNode(node_id, flags) if node_id == nil then node_id = 0 end if flags == nil then flags = 0 end @@ -2682,7 +3701,7 @@ function ImGui.DockBuilderAddNode(node_id, flags) node = ImGui.DockContextAddNode(g, node_id) node:SetLocalFlags(flags) end - node.LastFrameAlive = g.FrameCount + node.LastFrameAlive = g.FrameCount -- Set this otherwise BeginDocked will undock during the same frame. return node.ID end @@ -2692,6 +3711,7 @@ function ImGui.DockBuilderRemoveNode(node_id) if node == nil then return end ImGui.DockBuilderRemoveNodeDockedWindows(node_id, true) ImGui.DockBuilderRemoveNodeChildNodes(node_id) + -- Node may have moved or deleted if e.g. any merge happened node = ImGui.DockContextFindNodeByID(g, node_id) if node == nil then return end if node:IsCentralNode() and node.ParentNode then @@ -2700,6 +3720,7 @@ function ImGui.DockBuilderRemoveNode(node_id) ImGui.DockContextRemoveNode(g, node, true) end +-- root_id = 0 to remove all, root_id != 0 to remove child of given node. function ImGui.DockBuilderRemoveNodeChildNodes(root_id) local g = ImGui.GetCurrentContext() local dc = g.DockContext @@ -2711,6 +3732,7 @@ function ImGui.DockBuilderRemoveNodeChildNodes(root_id) local backup_root_node_authority_for_pos = root_node and root_node.AuthorityForPos or ImGuiDataAuthority.Auto local backup_root_node_authority_for_size = root_node and root_node.AuthorityForSize or ImGuiDataAuthority.Auto + -- Process active windows local nodes_to_remove = {} for _, id in ipairs(DockContextNodesSorted(g)) do local node = dc.Nodes[id] @@ -2728,11 +3750,14 @@ function ImGui.DockBuilderRemoveNodeChildNodes(root_id) end end + -- DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge) + -- Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead) if root_node then root_node.AuthorityForPos = backup_root_node_authority_for_pos root_node.AuthorityForSize = backup_root_node_authority_for_size end + -- Apply to settings for _, settings in g.SettingsWindows:iter() do local window_settings_dock_id = settings.DockId if window_settings_dock_id and window_settings_dock_id ~= 0 then @@ -2745,6 +3770,7 @@ function ImGui.DockBuilderRemoveNodeChildNodes(root_id) end end + -- Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes if #nodes_to_remove > 1 then local depth = {} for _, n in ipairs(nodes_to_remove) do depth[n] = ImGui.DockNodeGetDepth(n) end @@ -2765,6 +3791,7 @@ end function ImGui.DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs) if clear_settings_refs == nil then clear_settings_refs = true end + -- Clear references in settings local g = ImGui.GetCurrentContext() if clear_settings_refs then for _, settings in g.SettingsWindows:iter() do @@ -2777,6 +3804,7 @@ function ImGui.DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs) end end + -- Clear references in windows for n = 1, g.Windows.Size do local window = g.Windows.Data[n] local want_removal = (root_id == 0) or (window.DockNode and ImGui.DockNodeGetRootNode(window.DockNode).ID == root_id) or (window.DockNodeAsHost and window.DockNodeAsHost.ID == root_id) @@ -2788,6 +3816,9 @@ function ImGui.DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs) end end +-- Returns (id_at_dir, id_at_opposite_dir): the IDs of the two new nodes created. +-- First return value is ID of the node at the specified direction. +-- FIXME-DOCK: We are not exposing nor using split_outer. --- @return ImGuiID id_at_dir, ImGuiID id_at_opposite_dir function ImGui.DockBuilderSplitNode(id, split_dir, size_ratio_for_node_at_dir) local g = ImGui.GetCurrentContext() @@ -2881,6 +3912,7 @@ function ImGui.DockBuilderCopyWindowSettings(src_name, dst_name) end end +-- FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed. --- @param in_window_remap_pairs table # 1-based array of window names: src0, dst0, src1, dst1, ... function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_window_remap_pairs) IM_ASSERT(src_dockspace_id ~= 0) @@ -2888,9 +3920,14 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w IM_ASSERT(in_window_remap_pairs ~= nil) IM_ASSERT((#in_window_remap_pairs % 2) == 0) + -- Duplicate entire dock + -- FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart, + -- whereas we could attempt to at least keep them together in a new, same floating node. local node_remap_pairs = {} ImGui.DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, node_remap_pairs) + -- Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes + -- (The windows associated to src_dockspace_id are staying in place) local src_windows = {} for remap_window_n = 1, #in_window_remap_pairs, 2 do local src_window_name = in_window_remap_pairs[remap_window_n] @@ -2898,6 +3935,7 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w local src_window_id = ImHashStr(src_window_name) src_windows[src_window_id] = true + -- Search in the remapping tables local src_dock_id = 0 local src_window = ImGui.FindWindowByID(src_window_id) if src_window then @@ -2910,17 +3948,24 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w for dock_remap_n = 1, #node_remap_pairs, 2 do if node_remap_pairs[dock_remap_n] == src_dock_id then dst_dock_id = node_remap_pairs[dock_remap_n + 1] + --node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0 -- Clear break end end if dst_dock_id ~= 0 then + -- Docked windows gets redocked into the new node hierarchy. ImGui.DockBuilderDockWindow(dst_window_name, dst_dock_id) else + -- Floating windows gets their settings transferred (regardless of whether the new window already exist or not) + -- When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together? ImGui.DockBuilderCopyWindowSettings(src_window_name, dst_window_name) end end + -- Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list. + -- Find those windows and move to them to the cloned dock node. This may be optional? + -- Dock those are a second step as undocking would invalidate source dock nodes. local dock_remaining_windows = {} for dock_remap_n = 1, #node_remap_pairs, 2 do local src_dock_id = node_remap_pairs[dock_remap_n] @@ -2929,6 +3974,7 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w local node = ImGui.DockBuilderGetNode(src_dock_id) for _, window in node.Windows:iter() do if not src_windows[window.ID] then + -- Docked windows gets redocked into the new node hierarchy. table.insert(dock_remaining_windows, { Window = window, DockId = dst_dock_id }) end end @@ -2939,19 +3985,27 @@ function ImGui.DockBuilderCopyDockSpace(src_dockspace_id, dst_dockspace_id, in_w end end +-- FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node. function ImGui.DockBuilderFinish(root_id) + --DockContextRebuild(g) ImGui.DockContextBuildAddWindowsToNodes(ImGui.GetCurrentContext(), root_id) end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Begin/End Support Functions (called from Begin/End) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - GetWindowAlwaysWantOwnTabBar() +-- - DockContextBindNodeToWindow() +-- - BeginDocked() +-- - BeginDockableDragDropSource() +-- - BeginDockableDragDropTarget() +------------------------------------------------------------------------------- function ImGui.GetWindowAlwaysWantOwnTabBar(window) local g = ImGui.GetCurrentContext() if g.IO.ConfigDockingAlwaysTabBar or window.WindowClass.DockingAlwaysTabBar then if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoDocking)) == 0 then - if not window.IsFallbackWindow then return true end + if not window.IsFallbackWindow then return true end -- We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise end end return false @@ -2962,11 +4016,13 @@ function ImGui.DockContextBindNodeToWindow(ctx, window) local node = ImGui.DockContextFindNodeByID(ctx, window.DockId) IM_ASSERT(window.DockNode == nil) + -- We should not be docking into a split node (SetWindowDock should avoid this) if node and node:IsSplitNode() then ImGui.DockContextProcessUndockWindow(ctx, window) return nil end + -- Create node if node == nil then node = ImGui.DockContextAddNode(ctx, window.DockId) node.AuthorityForPos = ImGuiDataAuthority.Window @@ -2975,6 +4031,10 @@ function ImGui.DockContextBindNodeToWindow(ctx, window) node.LastFrameAlive = g.FrameCount end + -- If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet, + -- so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node). + -- If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout. + -- This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame. if not node.IsVisible then local ancestor_node = node while not ancestor_node.IsVisible and ancestor_node.ParentNode do @@ -2985,9 +4045,10 @@ function ImGui.DockContextBindNodeToWindow(ctx, window) ImGui.DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node.Pos, ancestor_node.Size, node) end + -- Add window to node local node_was_visible = node.IsVisible ImGui.DockNodeAddWindow(node, window, true) - node.IsVisible = node_was_visible + node.IsVisible = node_was_visible -- Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see) IM_ASSERT(node == window.DockNode) return node end @@ -3004,6 +4065,7 @@ ImGui.StoreDockStyleForWindow = StoreDockStyleForWindow function ImGui.BeginDocked(window, p_open) local g = ImGui.GetCurrentContext() + -- Specific extra processing for fallback window (#9151), could be in Begin() as well. if window.IsFallbackWindow and not window.WasActive then DockNodeHideWindowDuringHostWindowCreation(window) return p_open @@ -3016,6 +4078,7 @@ function ImGui.BeginDocked(window, p_open) window.DockId = ImGui.DockContextGenNodeID(g) end else + -- Calling SetNextWindowPos() undock windows by default (by setting PosUndock) local want_undock = false want_undock = want_undock or bit32.band(window.Flags, ImGuiWindowFlags.NoDocking) ~= 0 want_undock = want_undock or (bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) ~= 0 and bit32.band(window.SetWindowPosAllowFlags, g.NextWindowData.PosCond) ~= 0 and g.NextWindowData.PosUndock) @@ -3025,6 +4088,7 @@ function ImGui.BeginDocked(window, p_open) end end + -- Bind to our dock node local node = window.DockNode if node ~= nil then IM_ASSERT(window.DockId == node.ID) end if window.DockId ~= 0 and node == nil then @@ -3032,7 +4096,10 @@ function ImGui.BeginDocked(window, p_open) if node == nil then return p_open end end + -- Undock if our dockspace node disappeared + -- Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags.KeepAliveOnly. if node.LastFrameAlive < g.FrameCount then + -- If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking() local root_node = ImGui.DockNodeGetRootNode(node) if root_node.LastFrameAlive < g.FrameCount then ImGui.DockContextProcessUndockWindow(g, window) @@ -3042,47 +4109,58 @@ function ImGui.BeginDocked(window, p_open) return p_open end + -- Store style overrides StoreDockStyleForWindow(window) + -- Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window, + -- and never create neither a host window neither a tab bar. + -- FIXME-DOCK: replace .HostWindow nil compare with something more explicit (~was initially intended as a first frame test) if node.HostWindow == nil then if node.State == ImGuiDockNodeState.HostWindowHiddenBecauseWindowsAreResizing then window.DockIsActive = true end - if node.Windows.Size > 1 and window.Appearing then + if node.Windows.Size > 1 and window.Appearing then -- Only hide appearing window DockNodeHideWindowDuringHostWindowCreation(window) end return p_open end + -- We can have zero-sized nodes (e.g. children of a small-size dockspace) IM_ASSERT(node.HostWindow) IM_ASSERT(node:IsLeafNode()) IM_ASSERT(node.Size.x >= 0.0 and node.Size.y >= 0.0) node.State = ImGuiDockNodeState.HostWindowVisible + -- Undock if we are submitted earlier than the host window if bit32.band(node.MergedFlags, ImGuiDockNodeFlags.KeepAliveOnly) == 0 and window.BeginOrderWithinContext < node.HostWindow.BeginOrderWithinContext then ImGui.DockContextProcessUndockWindow(g, window) return p_open end + -- Position/Size window ImGui.SetNextWindowPos(node.Pos) ImGui.SetNextWindowSize(node.Size) - g.NextWindowData.PosUndock = false + g.NextWindowData.PosUndock = false -- Cancel implicit undocking of SetNextWindowPos() window.DockIsActive = true window.DockNodeIsVisible = true window.DockTabIsVisible = false if bit32.band(node.MergedFlags, ImGuiDockNodeFlags.KeepAliveOnly) ~= 0 then return p_open end + -- When the window is selected we mark it as visible. if node.VisibleWindow == window then window.DockTabIsVisible = true end + -- Update window flag IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0) window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.NoResize) window.ChildFlags = bit32.bor(window.ChildFlags, ImGuiChildFlags.AlwaysUseWindowPadding) if node:IsHiddenTabBar() or node:IsNoTabBar() then window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.NoTitleBar) else - window.Flags = bit32.band(window.Flags, bit32.bnot(ImGuiWindowFlags.NoTitleBar)) + window.Flags = bit32.band(window.Flags, bit32.bnot(ImGuiWindowFlags.NoTitleBar)) -- Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed! end + -- Save new dock order only if the window has been visible once already + -- This allows multiple windows to be created in the same frame and have their respective dock orders preserved. if node.TabBar and window.WasActive then window.DockOrder = ImGui.DockNodeGetTabOrder(window) end @@ -3091,6 +4169,7 @@ function ImGui.BeginDocked(window, p_open) p_open = false end + -- Update ChildId to allow returning from Child to Parent with Escape local parent_window = window.DockNode.HostWindow window.ChildId = parent_window:GetID(window.Name) return p_open @@ -3102,7 +4181,11 @@ function ImGui.BeginDockableDragDropSource(window) IM_ASSERT(g.MovingWindow == window) IM_ASSERT(g.CurrentWindow == window) + -- 0: Hold SHIFT to disable docking, 1: Hold SHIFT to enable docking. if g.IO.ConfigDockingWithShift ~= g.IO.KeyShift then + -- When ConfigDockingWithShift is set, display a tooltip to increase UI affordance. + -- We cannot set for HoveredWindowUnderMovingWindow ~= nil 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) if g.IO.ConfigDockingWithShift and g.MouseStationaryTimer >= 1.0 and g.ActiveId >= 1 then ImGui.SetTooltip("%s", ImGui.LocalizeGetMsg(ImGuiLocKey.DockingHoldShiftToDock)) end @@ -3112,21 +4195,26 @@ function ImGui.BeginDockableDragDropSource(window) g.LastItemData.ID = window.MoveId window = window.RootWindowDockTree IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.NoDocking) == 0) - local is_drag_docking = g.IO.ConfigDockingWithShift or ImRect(0, 0, window.SizeFull.x, ImGui.GetFrameHeight()):Contains(g.ActiveIdClickOffset) + local is_drag_docking = g.IO.ConfigDockingWithShift or ImRect(0, 0, window.SizeFull.x, ImGui.GetFrameHeight()):Contains(g.ActiveIdClickOffset) -- FIXME-DOCKING: Need to make this stateful and explicit local drag_drop_flags = bit32.bor(ImGuiDragDropFlags.SourceNoPreviewTooltip, ImGuiDragDropFlags.SourceNoHoldToOpenOthers, ImGuiDragDropFlags.PayloadAutoExpire, ImGuiDragDropFlags.PayloadNoCrossContext, ImGuiDragDropFlags.PayloadNoCrossProcess) if is_drag_docking and ImGui.BeginDragDropSource(drag_drop_flags) then ImGui.SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, window) ImGui.EndDragDropSource() - StoreDockStyleForWindow(window) + StoreDockStyleForWindow(window) -- Store style overrides while dragging (even when not docked) because docking preview may need it. end end function ImGui.BeginDockableDragDropTarget(window) local g = ImGui.GetCurrentContext() + + --IM_ASSERT(window.RootWindowDockTree == window) -- May also be a DockSpace IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.NoDocking) == 0) if not g.DragDropActive then return end + --GetForegroundDrawList(window):AddRect(window.Pos, window.Pos + window.Size, IM_COL32(255, 255, 0, 255)) if not ImGui.BeginDragDropTargetCustom(window:Rect(), window.ID) then return end + -- Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering + -- (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly) local payload = g.DragDropPayload if not ImGuiPayload_IsDataType(payload, IMGUI_PAYLOAD_TYPE_WINDOW) or not ImGui.DockNodeIsDropAllowed(window, payload.Data) then ImGui.EndDragDropTarget() @@ -3135,10 +4223,17 @@ function ImGui.BeginDockableDragDropTarget(window) local payload_window = payload.Data if ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, bit32.bor(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoDrawDefaultRect)) then + -- Select target node + -- (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation) local dock_into_floating_window = false local node = nil if window.DockNodeAsHost then + -- Cannot assume that node will ~= nil even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos(). node = ImGui.DockNodeTreeFindVisibleNodeByPos(window.DockNodeAsHost, g.IO.MousePos) + + -- There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active) + -- In this case we need to fallback into any leaf mode, possibly the central node. + -- FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first. if node and node:IsDockSpace() and node:IsRootNode() then node = (node.CentralNode and node:IsLeafNode()) and node.CentralNode or ImGui.DockNodeTreeFindFallbackLeafNode(node) end @@ -3146,7 +4241,7 @@ function ImGui.BeginDockableDragDropTarget(window) if window.DockNode then node = window.DockNode else - dock_into_floating_window = true + dock_into_floating_window = true -- Dock into a regular window end end @@ -3158,8 +4253,11 @@ function ImGui.BeginDockableDragDropTarget(window) end local is_explicit_target = g.IO.ConfigDockingWithShift or ImGui.IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max) + -- Preview docking request and find out split direction/ratio + --local do_preview = true -- Ignore testing for payload:IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window. local do_preview = ImGuiPayload_IsPreview(payload) or ImGuiPayload_IsDelivery(payload) if do_preview and (node ~= nil or dock_into_floating_window) then + -- If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear. local split_inner = ImGuiDockPreviewData() local split_outer = ImGuiDockPreviewData() local split_data = split_inner @@ -3175,9 +4273,11 @@ function ImGui.BeginDockableDragDropTarget(window) end if split_data == split_outer then split_inner.IsDropAllowed = false end + -- Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes ImGui.DockNodePreviewDockRender(window, node, payload_window, split_inner) ImGui.DockNodePreviewDockRender(window, node, payload_window, split_outer) + -- Queue docking request if split_data.IsDropAllowed and ImGuiPayload_IsDelivery(payload) then ImGui.DockContextQueueDock(g, window, split_data.SplitNode, payload_window, split_data.SplitDir, split_data.SplitRatio, split_data == split_outer) end @@ -3186,24 +4286,36 @@ function ImGui.BeginDockableDragDropTarget(window) ImGui.EndDragDropTarget() end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: Settings ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DockSettingsRenameNodeReferences() +-- - DockSettingsRemoveNodeReferences() +-- - DockSettingsFindNodeSettings() +-- - DockSettingsHandler_ApplyAll() +-- - DockSettingsHandler_ReadOpen() +-- - DockSettingsHandler_ReadLine() +-- - DockSettingsHandler_DockNodeToSettings() +-- - DockSettingsHandler_WriteAll() +------------------------------------------------------------------------------- DockSettingsRenameNodeReferences = function(old_node_id, new_node_id) local g = ImGui.GetCurrentContext() for _, window in g.Windows:iter() do if window.DockId == old_node_id and window.DockNode == nil then window.DockId = new_node_id end end + ---- FIXME-OPT: We could remove this loop by storing the index in the map for _, settings in g.SettingsWindows:iter() do if settings.DockId == old_node_id then settings.DockId = new_node_id end end end +-- Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings --- @param node_ids table # 1-based array DockSettingsRemoveNodeReferences = function(node_ids, node_ids_count) local g = ImGui.GetCurrentContext() local found = 0 + ---- FIXME-OPT: We could remove this loop by storing the index in the map for _, settings in g.SettingsWindows:iter() do for node_n = 1, node_ids_count do if settings.DockId == node_ids[node_n] then @@ -3218,19 +4330,23 @@ DockSettingsRemoveNodeReferences = function(node_ids, node_ids_count) end DockSettingsFindNodeSettings = function(ctx, id) + -- FIXME-OPT for _, s in ctx.DockContext.NodesSettings:iter() do if s.ID == id then return s end end return nil end +-- Clear settings data DockSettingsHandler_ClearAll = function(ctx, handler) local dc = ctx.DockContext dc.NodesSettings:clear() ImGui.DockContextClearNodes(ctx, 0, true) end +-- Recreate nodes based on settings data DockSettingsHandler_ApplyAll = function(ctx, handler) + -- Prune settings at boot time only local dc = ctx.DockContext if ctx.Windows.Size == 0 then ImGui.DockContextPruneUnusedSettingsNodes(ctx) end ImGui.DockContextBuildNodesFromSettings(ctx, dc.NodesSettings.Data or {}, dc.NodesSettings.Size) @@ -3243,6 +4359,10 @@ DockSettingsHandler_ReadOpen = function(ctx, handler, name) end DockSettingsHandler_ReadLine = function(ctx, handler, entry, line) + -- Parsing, e.g. + -- " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 " + -- " DockNode ID=0x00000002 Parent=0x00000001 " + -- Important: this code expect currently fields in a fixed order. local node = ImGuiDockNodeSettings() line = line:gsub("^[ \t]+", "") if line:sub(1, 8) == "DockNode" then @@ -3324,6 +4444,8 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) local dc = ctx.DockContext if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then return end + -- Gather settings data + -- (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer) dc.NodesSettings:resize(0) for _, id in ipairs(DockContextNodesSorted(ctx)) do local node = dc.Nodes[id] @@ -3335,9 +4457,10 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) local max_depth = 0 for _, s in dc.NodesSettings:iter() do max_depth = ImMax(s.Depth, max_depth) end + -- Write to text buffer buf:appendf("[%s][Data]\n", handler.TypeName) for _, s in dc.NodesSettings:iter() do - buf:append(string.rep(" ", s.Depth * 2) .. ((bit32.band(s.Flags, ImGuiDockNodeFlags.DockSpace) ~= 0) and "DockSpace" or "DockNode ") .. string.rep(" ", (max_depth - s.Depth) * 2)) + buf:append(string.rep(" ", s.Depth * 2) .. ((bit32.band(s.Flags, ImGuiDockNodeFlags.DockSpace) ~= 0) and "DockSpace" or "DockNode ") .. string.rep(" ", (max_depth - s.Depth) * 2)) -- Text align nodes to facilitate looking at .ini file buf:appendf(" ID=0x%08X", s.ID) if s.ParentNodeId ~= 0 then buf:appendf(" Parent=0x%08X SizeRef=%d,%d", s.ParentNodeId, s.SizeRef.x, s.SizeRef.y) @@ -3358,9 +4481,9 @@ DockSettingsHandler_WriteAll = function(ctx, handler, buf) buf:append("\n") end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- Docking: helpers (imgui_internal.h inlines) + widgets used by docking ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.DockNodeGetRootNode(node) while node.ParentNode do node = node.ParentNode end @@ -3400,10 +4523,14 @@ function ImGui.SetNextWindowDockID(id, cond) g.NextWindowData.DockId = id end +-- We use 'undock == false' when dragging from title bar to allow moving groups of floating nodes without undocking them. function ImGui.StartMouseMovingWindowOrNode(window, node, undock) local g = ImGui.GetCurrentContext() local can_undock_node = false if undock and node ~= nil and node.VisibleWindow and bit32.band(node.VisibleWindow.Flags, ImGuiWindowFlags.NoMove) == 0 and bit32.band(node.MergedFlags, ImGuiDockNodeFlags.NoUndocking) == 0 then + -- 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. Undocking from a fixed/central node will create a new node and copy windows. local root_node = ImGui.DockNodeGetRootNode(node) if root_node.OnlyNodeWithWindows ~= node or root_node.CentralNode ~= nil then can_undock_node = true @@ -3413,18 +4540,21 @@ function ImGui.StartMouseMovingWindowOrNode(window, node, undock) local clicked = ImGui.IsMouseClicked(0) local dragging = ImGui.IsMouseDragging(0) if can_undock_node and dragging then - ImGui.DockContextQueueUndockNode(g, node) + ImGui.DockContextQueueUndockNode(g, node) -- Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame elseif not can_undock_node and (clicked or dragging) and g.MovingWindow ~= window then ImGui.StartMouseMovingWindow(window) end end +-- This is less wide than RenderArrow() and we use in dock nodes instead of the regular RenderArrow() to denote a change of functionality, +-- and because the saved space means that the left-most tab label can stay at exactly the same position as the label of a loose window. function ImGui.RenderArrowDockMenu(draw_list, p_min, sz, col) draw_list:AddRectFilled(p_min + ImVec2(sz * 0.20, sz * 0.15), p_min + ImVec2(sz * 0.80, sz * 0.30), col) ImGui.RenderArrowPointingAt(draw_list, p_min + ImVec2(sz * 0.50, sz * 0.85), ImVec2(sz * 0.30, sz * 0.40), ImGuiDir.Down, col) end -- Upstream CollapseButton (docking branch): replaces the port's simpler version +-- The Collapse button also functions as a Dock Menu button. function ImGui.CollapseButton(id, pos, dock_node) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow @@ -3434,6 +4564,8 @@ function ImGui.CollapseButton(id, pos, dock_node) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, ImGuiButtonFlags.None) if is_clipped then return pressed end + -- Render + --local is_dock_menu = (window.DockNodeAsHost and not window.Collapsed) local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.ButtonActive or (hovered and ImGuiCol.ButtonHovered or ImGuiCol.Button)) local text_col = ImGui.GetColorU32(ImGuiCol.Text) if hovered or held then @@ -3447,13 +4579,15 @@ function ImGui.CollapseButton(id, pos, dock_node) ImGui.RenderArrow(window.DrawList, bb.Min, text_col, window.Collapsed and ImGuiDir.Right or ImGuiDir.Down, 1.0) end + -- Switch to moving the window after mouse is moved beyond the initial drag threshold if ImGui.IsItemActive() and ImGui.IsMouseDragging(0) then - ImGui.StartMouseMovingWindowOrNode(window, dock_node, true) + ImGui.StartMouseMovingWindowOrNode(window, dock_node, true) -- Undock from window/collapse menu button end return pressed end +-- Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise. --- @return bool held, float size1, float size2 function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2, hover_extend, hover_visibility_delay, bg_col) hover_extend = hover_extend or 0.0 @@ -3464,13 +4598,16 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 if not ImGui.ItemAdd(bb, id, nil, ImGuiItemFlags.NoNav) then return false, size1, size2 end + -- FIXME: AFAIK the only leftover reason for passing ImGuiButtonFlags.AllowOverlap here is + -- to allow caller of SplitterBehavior() to call SetItemAllowOverlap() after the item. + -- Nowadays we would instead want to use SetNextItemAllowOverlap() before the item. local button_flags = bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.AllowOverlap) local bb_interact = ImRect(bb.Min, bb.Max) bb_interact:Expand(axis == ImGuiAxis.Y and ImVec2(0.0, hover_extend) or ImVec2(hover_extend, 0.0)) local _, hovered, held = ImGui.ButtonBehavior(bb_interact, id, button_flags) if hovered then - g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) + g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredRect) -- for IsItemHovered(), because bb_interact is larger than bb end if held or (hovered and g.HoveredIdPreviousFrame == id and g.HoveredIdTimer >= hover_visibility_delay) then @@ -3482,11 +4619,13 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 local d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min local mouse_delta = d[axis] + -- Minimum pane size local size_1_maximum_delta = ImMax(0.0, size1 - min_size1) local size_2_maximum_delta = ImMax(0.0, size2 - min_size2) if mouse_delta < -size_1_maximum_delta then mouse_delta = -size_1_maximum_delta end if mouse_delta > size_2_maximum_delta then mouse_delta = size_2_maximum_delta end + -- Apply resize if mouse_delta ~= 0.0 then size1 = ImMax(size1 + mouse_delta, min_size1) size2 = ImMax(size2 - mouse_delta, min_size2) @@ -3495,6 +4634,7 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 end end + -- Render at new position if bit32.band(bg_col, IM_COL32_A_MASK) ~= 0 then window.DrawList:AddRectFilled(bb_render.Min, bb_render.Max, bg_col, 0.0) end @@ -3505,19 +4645,22 @@ function ImGui.SplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2 end end --[[ [SECTION] imgui_docking (was imgui_docking.lua) ]] -local IMGUI_DEBUG_NAV_SCORING = false -local IMGUI_DEBUG_NAV_RECTS = false +-- Debug options +local IMGUI_DEBUG_NAV_SCORING = false -- Display navigation scoring preview when hovering items. Hold Ctrl to display for all candidates. Ctrl+Arrow to change last direction. +local IMGUI_DEBUG_NAV_RECTS = false -- Display the reference navigation rectangle for each window +-- Default font size if unspecified in both style.FontSizeBase and AddFontXXX() calls. local FONT_DEFAULT_SIZE_BASE = 20 -local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 -local WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70 +local WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04 -- Reduce visual noise by only highlighting the border after a certain time. +local WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 0.70 -- Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved. +-- Tooltip offset local TOOLTIP_DEFAULT_OFFSET_MOUSE = ImVec2(16, 10) -- Multiplied by g.Style.MouseCursorScale local TOOLTIP_DEFAULT_OFFSET_TOUCH = ImVec2(0, -20) -- Multiplied by g.Style.MouseCursorScale local TOOLTIP_DEFAULT_PIVOT_TOUCH = ImVec2(0.5, 1.0) -- Multiplied by g.Style.MouseCursorScale -local IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111 +local 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. local string = string ImFormatString = string.format -- TODO: an simplified version that operates on byte tables directly? @@ -3528,9 +4671,9 @@ ImStd.sscanf = IM_INCLUDE"imstd_minstdio.lua" local math = math local bit32 = bit32 ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] MISC HELPERS/UTILITIES (File functions) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- This closes the _file. --- @param _file any # File object @@ -3566,6 +4709,7 @@ if gmod then IM_FILE_READ = FindMetaTable("File").Read --- @type function end +-- Default file functions if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then --- [GMod] Another Platform specific if gmod then @@ -3595,6 +4739,8 @@ if not IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS then end end + -- Helper: Load file content into memory + -- This can't really be used with "rt" because fseek size won't match read size. --- @param filename string --- @param mode string --- @return table?, integer? @@ -3626,6 +4772,9 @@ local CalcNextScrollFromScrollTargetAndClamp local MT = ImGui.GetMetatables() +-- Scale all spacing/padding/thickness values. Do not scale fonts. +-- Consider not calling this if your initial scale factor if <1.0. +-- 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. --- @param scale_factor float function MT.ImGuiStyle:ScaleAllSizes(scale_factor) self._MainScale = self._MainScale * scale_factor @@ -3682,17 +4831,20 @@ function MT.ImGuiStyle:ScaleAllSizes(scale_factor) self.MouseCursorScale = ImTrunc(self.MouseCursorScale * scale_factor) end +-- Data for resizing from resize grip / corner local ImGuiResizeGripDef = { - {CornerPosN = ImVec2(1, 1), InnerDir = ImVec2(-1, -1), AngleMin12 = 0, AngleMax12 = 3}, -- Bottom right grip - {CornerPosN = ImVec2(0, 1), InnerDir = ImVec2( 1, -1), AngleMin12 = 3, AngleMax12 = 6} -- Bottom left + {CornerPosN = ImVec2(1, 1), InnerDir = ImVec2(-1, -1), AngleMin12 = 0, AngleMax12 = 3}, -- Lower-right + {CornerPosN = ImVec2(0, 1), InnerDir = ImVec2( 1, -1), AngleMin12 = 3, AngleMax12 = 6} -- Lower-left } +-- Data for resizing from borders +-- InnerDir: Normal toward inside, SegmentN1/SegmentN2: End positions, normalized (0,0: upper left), OuterAngle: Angle toward outside --- [1] Left, [2] Right, [3] Up, [4] Down local ImGuiResizeBorderDef = { - {InnerDir = ImVec2( 1, 0), SegmentN1 = ImVec2( 0, 1), SegmentN2 = ImVec2( 0, 0), OuterAngle = IM_PI * 1.00}, - {InnerDir = ImVec2(-1, 0), SegmentN1 = ImVec2( 1, 0), SegmentN2 = ImVec2( 1, 1), OuterAngle = IM_PI * 0.00}, - {InnerDir = ImVec2( 0, 1), SegmentN1 = ImVec2( 0, 0), SegmentN2 = ImVec2( 1, 0), OuterAngle = IM_PI * 1.50}, - {InnerDir = ImVec2( 0, -1), SegmentN1 = ImVec2( 1, 1), SegmentN2 = ImVec2( 0, 1), OuterAngle = IM_PI * 0.50} + {InnerDir = ImVec2( 1, 0), SegmentN1 = ImVec2( 0, 1), SegmentN2 = ImVec2( 0, 0), OuterAngle = IM_PI * 1.00}, -- Left + {InnerDir = ImVec2(-1, 0), SegmentN1 = ImVec2( 1, 0), SegmentN2 = ImVec2( 1, 1), OuterAngle = IM_PI * 0.00}, -- Right + {InnerDir = ImVec2( 0, 1), SegmentN1 = ImVec2( 0, 0), SegmentN2 = ImVec2( 1, 0), OuterAngle = IM_PI * 1.50}, -- Up + {InnerDir = ImVec2( 0, -1), SegmentN1 = ImVec2( 1, 1), SegmentN2 = ImVec2( 0, 1), OuterAngle = IM_PI * 0.50} -- Down } --- @param window ImGuiWindow @@ -3722,6 +4874,8 @@ local function GetResizeBorderRect(window, border_n, perp_padding, thickness) return ImRect() end +-- Known size hash +-- It is ok to call ImHashData on a string with known length but the ### operator won't be supported. --- @param data table|number --- @param size int? # size = -1 to indicate that `data` is a single number --- @param seed int? @@ -3748,6 +4902,8 @@ function ImHashData(data, size, seed) return hash end +-- Zero-terminated string hash, with support for ### to reset back to seed value. +-- e.g. "label###id" outputs the same hash as "id" (and "label" is generally displayed by the UI functions) -- Use FNV1a, as one ImGui FIXME suggested --- @param str string --- @param size int? @@ -3817,6 +4973,9 @@ local shifte = {0, 6, 4, 2, 0} local s = {0, 0, 0, 0} +-- Convert UTF-8 to 32-bit character, process single character input. +-- A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8). +-- We handle UTF-8 decoding error by skipping forward. --- @param in_text ImString --- @param pos int --- @param in_text_end int @@ -3826,15 +4985,19 @@ function ImStd.ImTextCharFromUtf8(in_text, pos, in_text_end) local len = lengths[bit32.rshift(ImStrByte(in_text, pos), 3) + 1] local wanted = len > 0 and len or 1 + -- IMPORTANT: if in_text_end == nil it assume we have enough space! if in_text_end == nil then - in_text_end = pos + wanted + in_text_end = pos + wanted -- Max length, nulls will be taken into account. end + -- Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here, + -- so it is fast even with excessive branching. s[1] = (pos < in_text_end) and ImStrByte(in_text, pos) or 0 s[2] = (pos + 1 < in_text_end) and ImStrByte(in_text, pos + 1) or 0 s[3] = (pos + 2 < in_text_end) and ImStrByte(in_text, pos + 2) or 0 s[4] = (pos + 3 < in_text_end) and ImStrByte(in_text, pos + 3) or 0 + -- Assume a four-byte character and load four bytes. Unused bits are shifted out. local out_char out_char = bit32.lshift(bit32.band(s[1], masks[len + 1]), 18) out_char = bit32.bor(out_char, bit32.lshift(bit32.band(s[2], 0x3f), 12)) @@ -3842,17 +5005,22 @@ function ImStd.ImTextCharFromUtf8(in_text, pos, in_text_end) out_char = bit32.bor(out_char, bit32.lshift(bit32.band(s[4], 0x3f), 0)) out_char = bit32.rshift(out_char, shiftc[len + 1]) + -- Accumulate the various error conditions. local e = 0 - e = bit32.lshift((out_char < mins[len + 1]) and 1 or 0, 6) - e = bit32.bor(e, bit32.lshift((bit32.rshift(out_char, 11) == 0x1b) and 1 or 0, 7)) - e = bit32.bor(e, bit32.lshift((out_char > IM_UNICODE_CODEPOINT_MAX) and 1 or 0, 8)) + e = bit32.lshift((out_char < mins[len + 1]) and 1 or 0, 6) -- non-canonical encoding + e = bit32.bor(e, bit32.lshift((bit32.rshift(out_char, 11) == 0x1b) and 1 or 0, 7)) -- surrogate half? + e = bit32.bor(e, bit32.lshift((out_char > IM_UNICODE_CODEPOINT_MAX) and 1 or 0, 8)) -- out of range we can store in ImWchar (FIXME: May evolve) e = bit32.bor(e, bit32.rshift(bit32.band(s[2], 0xc0), 2)) e = bit32.bor(e, bit32.rshift(bit32.band(s[3], 0xc0), 4)) e = bit32.bor(e, bit32.rshift(s[4], 6)) - e = bit32.bxor(e, 0x2a) + e = bit32.bxor(e, 0x2a) -- top two bits of each tail byte correct? e = bit32.rshift(e, shifte[len + 1]) if e ~= 0 then + -- No bytes are consumed when in_text[pos] == 0 || pos == in_text_end. + -- One byte is consumed in case of invalid first byte of in_text. + -- All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes. + -- Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s. wanted = ImMin(wanted, (s[1] ~= 0 and 1 or 0) + (s[2] ~= 0 and 1 or 0) + (s[3] ~= 0 and 1 or 0) + (s[4] ~= 0 and 1 or 0)) out_char = IM_UNICODE_CODEPOINT_INVALID end @@ -3862,6 +5030,7 @@ end end +-- Based on stb_to_utf8() from github.com/nothings/stb/ --- @param buf char[] --- @param buf_size int --- @param c unsigned_int @@ -3910,6 +5079,7 @@ function ImStd.ImTextCharToUtf8(out_buf, c) return count end +-- Not optimal but we very rarely use this function. --- @param in_text ImString --- @param pos int --- @param in_text_end int @@ -4041,6 +5211,7 @@ function ImStd.ImStrncpy(dst, dst_pos, src, src_pos, count) dst[dst_pos + (count - 1)] = 0 end +-- find beginning-of-line --- @param str char[] --- @param mid_line int --- @param begin int @@ -4052,31 +5223,55 @@ function ImStd.ImStrbol(str, mid_line, begin) return mid_line end +-- Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. --- @param buf char[] function ImStd.ImStrTrimBlanks(buf) local p = 1 -- buf_begin - while buf[p] == 32 or buf[p] == 9 do + while buf[p] == 32 or buf[p] == 9 do -- Leading blanks p = p + 1 end local p_start = p - while buf[p] ~= 0 do + while buf[p] ~= 0 do -- Find end of string p = p + 1 end - while p > p_start and (buf[p - 1] == 32 or buf[p - 1] == 9) do + while p > p_start and (buf[p - 1] == 32 or buf[p - 1] == 9) do -- Trailing blanks p = p - 1 end - if p_start > 1 then + if p_start > 1 then -- Copy memory if we had leading blanks ImStd.memmove(buf, 1, buf, p_start, p - p_start) end - buf[p - p_start + 1] = 0 + buf[p - p_start + 1] = 0 -- Zero terminate end +------------------------------------------------------------------------------- +-- [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] +-- - RegisterFontAtlas() [Internal] +-- - UnregisterFontAtlas() [Internal] +-- - SetCurrentFont() [Internal] +-- - UpdateCurrentFontSize() [Internal] +-- - PushFont() +-- - PopFont() +------------------------------------------------------------------------------- + function ImGui.UpdateCurrentFontSize(restore_font_size_after_scaling) local g = GImGui local window = g.CurrentWindow g.Style.FontSizeBase = g.FontSizeBase + -- Early out to avoid hidden window keeping bakes referenced and out of GC reach. + -- - However this leave a pretty subtle and damning error surface area if g.FontBaked was mismatching. + -- Probably needs to be reevaluated into e.g. setting g.FontBaked = nil to mark it as dirty. + -- - Note that 'PushFont(); Begin(); End(); PopFont()' from within any collapsed window is not compromised, because Begin() calls SetCurrentWindow()->...->UpdateCurrentSize() -- if (window ~= nil and window.SkipItems) then -- local table = g.CurrentTable -- if (table == nil or (table.CurrentColumn ~= -1 and table.Columns[table.CurrentColumn].IsSkipItems == false)) then @@ -4084,17 +5279,24 @@ function ImGui.UpdateCurrentFontSize(restore_font_size_after_scaling) -- end -- end + -- Restoring is pretty much only used by PopFont() local final_size = (restore_font_size_after_scaling > 0.0) and restore_font_size_after_scaling or 0.0 if final_size == 0.0 then final_size = g.FontSizeBase - final_size = final_size * g.Style.FontScaleMain - final_size = final_size * g.Style.FontScaleDpi + -- Global scale factors + final_size = final_size * g.Style.FontScaleMain -- Main global scale factor + final_size = final_size * g.Style.FontScaleDpi -- Per-monitor/viewport DPI scale factor (in docking branch: automatically updated when io.ConfigDpiScaleFonts is enabled). + + -- Window scale (mostly obsolete now) if window ~= nil then final_size = final_size * window.FontWindowScale end end + -- 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 = ImGui.GetRoundedFontSize(final_size) final_size = ImClamp(final_size, 4.0, IMGUI_FONT_SIZE_MAX) if (g.Font ~= nil and bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) ~= 0) then @@ -4107,6 +5309,14 @@ function ImGui.UpdateCurrentFontSize(restore_font_size_after_scaling) g.DrawListSharedData.FontScale = g.FontBakedScale end +-- 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() ? function ImGui.SetCurrentFont(font, font_size_before_scaling, font_size_after_scaling) local g = GImGui @@ -4115,7 +5325,7 @@ function ImGui.SetCurrentFont(font, font_size_before_scaling, font_size_after_sc ImGui.UpdateCurrentFontSize(font_size_after_scaling) if font ~= nil then - IM_ASSERT(font and font:IsLoaded()) + IM_ASSERT(font and font:IsLoaded()) -- Font Atlas not created. Did you call io.Fonts:GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? local atlas = font.OwnerAtlas g.DrawListSharedData.FontAtlas = atlas g.DrawListSharedData.Font = font @@ -4126,10 +5336,11 @@ function ImGui.SetCurrentFont(font, font_size_before_scaling, font_size_after_sc end end +-- If you want to scale an existing font size! Read comments in imgui.h! function ImGui.PushFont(font, font_size_base) local g = GImGui - if font == nil then + if font == nil then -- Before 1.92 (June 2025), PushFont(nil) == PushFont(GetDefaultFont()) font = g.Font end @@ -4139,7 +5350,7 @@ function ImGui.PushFont(font, font_size_base) g.FontStack:push_back(ImFontStackData(font, g.FontSizeBase, g.FontSize)) if font_size_base == 0.0 then - font_size_base = g.FontSizeBase + font_size_base = g.FontSizeBase -- Keep current font size end ImGui.SetCurrentFont(font, font_size_base, 0.0) @@ -4161,12 +5372,17 @@ function ImGui.PopFont() end function 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. local g = GImGui local has_textures = bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.RendererHasTextures) ~= 0 for _, atlas in g.FontAtlases:iter() do if (atlas.OwnerContext == g) then 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 ~= nil and atlas.Builder.FrameCount ~= -1) IM_ASSERT(atlas.RendererHasTextures == has_textures) end @@ -4177,11 +5393,14 @@ function ImGui.UpdateTexturesNewFrame() end end +-- Build a single texture list function ImGui.UpdateTexturesEndFrame() local g = GImGui g.PlatformIO.Textures:resize(0) for _, atlas in g.FontAtlases:iter() do for _, tex in atlas.TexList:iter() do + -- 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 = atlas.RefCount g.PlatformIO.Textures:push_back(tex) end @@ -4204,16 +5423,18 @@ function ImGui.UpdateFontsNewFrame() g.Style._NextFrameFontSizeBase = 0.0 end + -- Apply default font size the first time local font = ImGui.GetDefaultFont() if g.Style.FontSizeBase <= 0.0 then g.Style.FontSizeBase = ((font.LegacySize > 0.0) and font.LegacySize or FONT_DEFAULT_SIZE_BASE) end + -- Set initial font g.Font = font g.FontSizeBase = g.Style.FontSizeBase g.FontSize = 0.0 - local font_stack_data = ImFontStackData(font, g.Style.FontSizeBase, g.Style.FontSizeBase) - ImGui.SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0) + local font_stack_data = ImFontStackData(font, g.Style.FontSizeBase, g.Style.FontSizeBase) -- <--- Will restore FontSize + ImGui.SetCurrentFont(font_stack_data.Font, font_stack_data.FontSizeBeforeScaling, 0.0) -- <--- but use 0.0f to enable scale g.FontStack:push_back(font_stack_data) IM_ASSERT(g.Font:IsLoaded()) end @@ -4258,6 +5479,11 @@ function ImGui.UnregisterFontAtlas(atlas) end end +------------------------------------------------------------------------------- +-- [SECTION] INITIALIZATION, SHUTDOWN +------------------------------------------------------------------------------- + +-- Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself function ImGui.GetCurrentContext() return GImGui end @@ -4289,12 +5515,14 @@ local function ImGuiLocEntry(key, text) return { Key = key, Text = text } end +-- IMPORTANT: interactive elements requires a fixed ###xxx suffix, it must be same in ALL languages to allow for automation. local GLocalizationEntriesEnUS = { ImGuiLocEntry(ImGuiLocKey.VersionStr, "Dear ImGui WIP"), ImGuiLocEntry(ImGuiLocKey.TableSizeOne, "Size column to fit###SizeOne"), ImGuiLocEntry(ImGuiLocKey.TableSizeAllFit, "Size all columns to fit###SizeAll"), ImGuiLocEntry(ImGuiLocKey.TableSizeAllDefault, "Size all columns to default###SizeAll"), ImGuiLocEntry(ImGuiLocKey.TableReset, "Reset"), + --ImGuiLocEntry(ImGuiLocKey.TableResetAll, "Reset to default###ResetAll"), ImGuiLocEntry(ImGuiLocKey.TableResetOrder, "Reset order###ResetOrder"), ImGuiLocEntry(ImGuiLocKey.TableResetVisibility, "Reset visibility###ResetVisibility"), ImGuiLocEntry(ImGuiLocKey.WindowingMainMenuBar, "(Main menu bar)"), @@ -4311,11 +5539,15 @@ function ImGui.Initialize() local g = GImGui IM_ASSERT(not g.Initialized and not g.SettingsLoaded) + -- Add .ini handle for ImGuiWindow and ImGuiTable types ImGui.WindowSettingsAddSettingsHandler() if ImGui.TableSettingsAddSettingsHandler then ImGui.TableSettingsAddSettingsHandler() end + -- Initialize Docking ImGui.DockContextInitialize(g) + -- Setup default localization table ImGui.LocalizeRegisterEntries(GLocalizationEntriesEnUS, #GLocalizationEntriesEnUS) + -- Create default viewport local viewport = ImGuiViewportP() viewport.ID = IMGUI_VIEWPORT_DEFAULT_ID viewport.Idx = 1 @@ -4325,6 +5557,7 @@ function ImGui.Initialize() g.ViewportCreatedCount = g.ViewportCreatedCount + 1 g.PlatformIO.Viewports:push_back(g.Viewports.Data[1]) + -- Build KeysMayBeCharInput[] lookup table (1 bit per named key) for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do if (key >= ImGuiKey.K0 and key <= ImGuiKey.K9) or (key >= ImGuiKey.A and key <= ImGuiKey.Z) or (key >= ImGuiKey.Keypad0 and key <= ImGuiKey.Keypad9) or key == ImGuiKey.Tab or key == ImGuiKey.Space or key == ImGuiKey.Apostrophe or key == ImGuiKey.Comma or key == ImGuiKey.Minus or key == ImGuiKey.Period @@ -4334,6 +5567,8 @@ function ImGui.Initialize() end end + -- 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. local atlas = g.IO.Fonts g.DrawListSharedData.Context = g ImGui.RegisterFontAtlas(atlas) @@ -4364,6 +5599,7 @@ function ImGui.DestroyContext(ctx) ImGui.SetCurrentContext((prev_ctx ~= ctx) and prev_ctx or nil) end +-- This is faster if you are holding on a Window already as we don't need to perform a search. --- @param window ImGuiWindow --- @return any function ImGui.FindWindowSettingsByWindow(window) @@ -4374,6 +5610,8 @@ function ImGui.FindWindowSettingsByWindow(window) return ImGui.FindWindowSettingsByID(window.ID) end +-- We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names. +-- This is called once per window .ini entry + once per newly instantiated window. --- @param id ImGuiID --- @return any function ImGui.FindWindowSettingsByID(id) @@ -4449,6 +5687,8 @@ local function ApplyWindowSettings(window, settings) end end +-- Note that 'settings' may be nil. +-- Sets _Once, _Appearing, _FirstUseEver. _FirstUseEver will be cleared again if there are settings. --- @param window ImGuiWindow --- @param settings ImGuiWindowSettings local function InitOrLoadWindowSettings(window, settings) @@ -4473,6 +5713,8 @@ end --- @param flags ImGuiWindowFlags --- @return ImGuiWindow local function CreateNewWindow(name, flags) + -- Create window the first time + --IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags) local g = GImGui local window_id = ImHashStr(name) @@ -4495,7 +5737,7 @@ local function CreateNewWindow(name, flags) InitOrLoadWindowSettings(window, settings) if bit32.band(flags, ImGuiWindowFlags.NoBringToFrontOnFocus) ~= 0 then - g.Windows:push_front(window) + g.Windows:push_front(window) -- Quite slow but rare and only once else g.Windows:push_back(window) end @@ -4504,21 +5746,41 @@ local function CreateNewWindow(name, flags) end ---------------------------------------------------------------------------------------- --- [SECTION] SETTINGS (in-memory .ini; Roblox has no disk) ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] SETTINGS +-- (in-memory .ini; Roblox has no disk) +------------------------------------------------------------------------------- +-- - UpdateSettings() [Internal] +-- - MarkIniSettingsDirty() [Internal] +-- - FindSettingsHandler() [Internal] +-- - ClearIniSettings() [Internal] +-- - LoadIniSettingsFromDisk() +-- - LoadIniSettingsFromMemory() +-- - SaveIniSettingsToDisk() +-- - SaveIniSettingsToMemory() +------------------------------------------------------------------------------- +-- - CreateNewWindowSettings() [Internal] +-- - FindWindowSettingsByID() [Internal] +-- - FindWindowSettingsByWindow() [Internal] +-- - ClearWindowSettings() [Internal] +-- - WindowSettingsHandler_***() [Internal] +------------------------------------------------------------------------------- +-- Called by NewFrame() function ImGui.UpdateSettings() + -- Load settings on first frame (if not explicitly loaded manually before) local g = GImGui if not g.SettingsLoaded then if g.IO.IniFilename then ImGui.LoadIniSettingsFromDisk(g.IO.IniFilename) end g.SettingsLoaded = true end + + -- Save settings (with a delay after the last modification, so we don't spam disk too much) if g.SettingsDirtyTimer > 0.0 then g.SettingsDirtyTimer = g.SettingsDirtyTimer - g.IO.DeltaTime if g.SettingsDirtyTimer <= 0.0 then -- No disk: always let the user know they can call SaveIniSettingsToMemory() - g.IO.WantSaveIniSettings = true + g.IO.WantSaveIniSettings = true -- Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. g.SettingsDirtyTimer = 0.0 end end @@ -4556,6 +5818,7 @@ function ImGui.FindSettingsHandler(type_name) return nil end +-- Clear all settings (windows, tables, docking etc.) function ImGui.ClearIniSettings() local g = GImGui g.SettingsIniData = "" @@ -4583,13 +5846,20 @@ function ImGui.LoadIniSettingsFromDisk(ini_filename) ImGui.LoadIniSettingsFromMemory(table.concat(parts)) end ---- Zero-tolerance, cheap .ini parsing. `ini_size` ignored (Lua strings know their length). +-- Zero-tolerance, no error reporting, cheap .ini parsing +-- Set ini_size==0 (or nil) to use the whole string (Lua strings know their length). function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) local g = GImGui IM_ASSERT(g.Initialized) + --IM_ASSERT(not g.WithinFrameScope, "Cannot be called between NewFrame() and EndFrame()") + --IM_ASSERT(g.SettingsLoaded == false and g.FrameCount == 0) + + -- For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). if ini_size and ini_size > 0 then ini_data = ini_data:sub(1, ini_size) end g.SettingsIniData = ini_data + -- Call pre-read handlers + -- Some types will clear their data (e.g. dock information) some types will allow merge/override (window) for _, handler in g.SettingsHandlers:iter() do if handler.ReadInitFn then handler.ReadInitFn(g, handler) end end @@ -4600,7 +5870,7 @@ function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) if c == ";" then -- comment elseif c == "[" and line:sub(-1) == "]" then - -- "[Type][Name]" (Name may contain [] characters) + -- Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. local type_name, name = line:match("^%[([^%]]*)%]%[(.*)%]$") if type_name then entry_handler = ImGui.FindSettingsHandler(type_name) @@ -4609,11 +5879,13 @@ function ImGui.LoadIniSettingsFromMemory(ini_data, ini_size) entry_handler, entry_data = nil, nil end elseif entry_handler ~= nil and entry_data ~= nil then + -- Let type handler parse the line entry_handler.ReadLineFn(g, entry_handler, entry_data, line) end end g.SettingsLoaded = true + -- Call post-read handlers for _, handler in g.SettingsHandlers:iter() do if handler.ApplyAllFn then handler.ApplyAllFn(g, handler) end end @@ -4625,6 +5897,7 @@ function ImGui.SaveIniSettingsToDisk(ini_filename) -- Roblox: no disk. Call SaveIniSettingsToMemory() and persist the string yourself (e.g. DataStore). end +-- Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer --- @return string ini_data, int size function ImGui.SaveIniSettingsToMemory() local g = GImGui @@ -4639,6 +5912,8 @@ end function ImGui.CreateNewWindowSettings(name) local g = GImGui + + -- Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier. if not g.IO.ConfigDebugIniSettings then -- ImHashSkipUncontributingPrefix: skip everything up to the last "###" local p = name:match("^.*()###") @@ -4651,7 +5926,9 @@ function ImGui.CreateNewWindowSettings(name) return settings end +-- This will revert window to its initial state, including enabling the ImGuiCond.FirstUseEver/ImGuiCond.Once conditions once more. function ImGui.ClearWindowSettings(name) + --IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name) local window = ImGui.FindWindowByName(name) if window ~= nil then window.Flags = bit32.bor(window.Flags, ImGuiWindowFlags.NoSavedSettings) @@ -4674,6 +5951,7 @@ local function WindowSettingsHandler_ReadOpen(ctx, handler, name) local id = ImHashStr(name) local settings = ImGui.FindWindowSettingsByID(id) if settings then + -- Clear existing if recycling previous entry local fresh = ImGuiWindowSettings() for k, v in pairs(fresh) do settings[k] = v end settings.Name = name @@ -4708,6 +5986,7 @@ local function WindowSettingsHandler_ReadLine(ctx, handler, settings, line) if x then settings.ClassId = tonumber(x, 16) return end end +-- Apply to existing windows (if any) local function WindowSettingsHandler_ApplyAll(ctx, handler) local g = ctx for _, settings in g.SettingsWindows:iter() do @@ -4720,6 +5999,8 @@ local function WindowSettingsHandler_ApplyAll(ctx, handler) end local function WindowSettingsHandler_WriteAll(ctx, handler, buf) + -- Gather data from windows that were active during this session + -- (if a window wasn't opened in this session we preserve its settings) local g = ctx for _, window in g.Windows:iter() do if bit32.band(window.Flags, ImGuiWindowFlags.NoSavedSettings) == 0 then @@ -4737,14 +6018,15 @@ local function WindowSettingsHandler_WriteAll(ctx, handler, buf) settings.ClassId = window.WindowClass and window.WindowClass.ClassId or 0 settings.DockOrder = window.DockOrder or -1 settings.Collapsed = window.Collapsed - settings.IsChild = (window.RootWindow ~= window) + settings.IsChild = (window.RootWindow ~= window) -- Cannot rely on ImGuiWindowFlags.ChildWindow here as docked windows have this set. settings.WantDelete = false end end + -- Write to text buffer for _, settings in g.SettingsWindows:iter() do if not settings.WantDelete then - buf:appendf("[%s][%s]\n", handler.TypeName, settings.Name) + buf:appendf("[%s][%s]\n", handler.TypeName, settings.Name) -- [Window][name] if settings.IsChild then buf:appendf("IsChild=1\n") buf:appendf("Size=%d,%d\n", settings.Size.x, settings.Size.y) @@ -4761,6 +6043,7 @@ local function WindowSettingsHandler_WriteAll(ctx, handler, buf) end buf:appendf("Collapsed=%d\n", settings.Collapsed and 1 or 0) if settings.DockId ~= 0 then + --buf:appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings.ID)) -- window.TabId: this is not read back but writing it makes "debugging" the .ini data easier. if settings.DockOrder == -1 then buf:appendf("DockId=0x%08X\n", settings.DockId) else @@ -4786,14 +6069,18 @@ function ImGui.WindowSettingsAddSettingsHandler() ImGui.AddSettingsHandler(ini_handler) end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] LOGGING/CAPTURING ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- All text output from the interface can be captured into tty/file/clipboard. +-- By default, tree nodes are automatically opened during logging. +------------------------------------------------------------------------------- ImGuiLogFlags = ImGuiLogFlags or { None = 0, OutputTTY = 1, OutputFile = 2, OutputBuffer = 4, OutputClipboard = 8, OutputMask_ = 15, } +-- Pass text data straight to log (without being displayed) local function LogTextV_Internal(g, fmt, ...) local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt if g.LogFile then @@ -4810,7 +6097,9 @@ function ImGui.LogText(fmt, ...) end ImGui.LogTextV = ImGui.LogText ---- Internal version that takes a position to decide on newline placement and pad items according to their depth. +-- Internal version that takes a position to decide on newline placement and pad items according to their depth. +-- We split text into individual lines to add current tree level padding +-- FIXME: This code is a little complicated perhaps, considering simplifying the whole system. --- `text` is a Lua string, `text_begin/text_end` optional 1-based byte range (text_end exclusive). function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) local g = GImGui @@ -4829,13 +6118,16 @@ function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) g.LogLineFirstItem = true end - if prefix then ImGui.LogRenderedText(ref_pos, prefix, #prefix + 1) end + if prefix then ImGui.LogRenderedText(ref_pos, prefix, #prefix + 1) end -- 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 then g.LogDepthRef = window.DC.TreeDepth end local tree_depth = window.DC.TreeDepth - g.LogDepthRef local text_remaining = text_begin while true do + -- Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry. + -- We don't add a trailing \n yet to allow a subsequent item on the same line to be captured. local line_start = text_remaining local nl = string.find(text, "\n", line_start, true) local line_end = (nl and nl < text_end) and nl or text_end @@ -4856,6 +6148,7 @@ function ImGui.LogRenderedText(ref_pos, text, text_end, text_begin) if suffix then ImGui.LogRenderedText(ref_pos, suffix, #suffix + 1) end end +-- Start logging/capturing text output function ImGui.LogBegin(flags, auto_open_depth) local g = GImGui local window = g.CurrentWindow @@ -4871,6 +6164,7 @@ function ImGui.LogBegin(flags, auto_open_depth) g.LogBuffer = ImGuiTextBuffer() end +-- Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText) function ImGui.LogSetNextTextDecoration(prefix, suffix) local g = GImGui g.LogNextPrefix = prefix @@ -4884,11 +6178,13 @@ function ImGui.LogToTTY(auto_open_depth) g.LogFile = "stdout" end +-- Start logging/capturing text output to given file function ImGui.LogToFile(auto_open_depth, filename) -- Roblox: no file access. Falls back to TTY (output window). ImGui.LogToTTY(auto_open_depth) end +-- Start logging/capturing text output to clipboard function ImGui.LogToClipboard(auto_open_depth) local g = GImGui if g.LogEnabled then return end @@ -4915,6 +6211,8 @@ function ImGui.LogFinish() g.LogBuffer = ImGuiTextBuffer() end +-- Helper to display logging buttons +-- FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!) function ImGui.LogButtons() local g = GImGui ImGui.PushID("LogButtons") @@ -4926,6 +6224,8 @@ function ImGui.LogButtons() g.LogDepthToExpandDefault = ImGui.SliderInt("Default Depth", g.LogDepthToExpandDefault, 0, 9, nil) ImGui.PopItemFlag() ImGui.PopID() + + -- Start logging at the end of the function so that the buttons don't appear in the log if log_to_tty then ImGui.LogToTTY() end if log_to_file then ImGui.LogToFile() end if log_to_clipboard then ImGui.LogToClipboard() end @@ -4941,6 +6241,7 @@ local function GetWindowForTitleDisplay(window) end end +-- Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID(). --- @param id ImGuiID @native function ImGui.KeepAliveID(id) @@ -4955,6 +6256,9 @@ function ImGui.KeepAliveID(id) end end +-- Test if mouse cursor is hovering given rectangle +-- NB- Rectangle is clipped by our current clip setting +-- NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) --- @param r_min ImVec2 --- @param r_max ImVec2 --- @param clip? bool @@ -4964,6 +6268,7 @@ function ImGui.IsMouseHoveringRect(r_min, r_max, clip) local g = GImGui -- [Luau] scalar version of: rect_clipped = ImRect(r_min, r_max); ClipWith(window.ClipRect); ContainsWithPad(); viewport Overlaps() + -- Clip local x0, y0, x1, y1 = r_min.x, r_min.y, r_max.x, r_max.y if clip then local cr = g.CurrentWindow.ClipRect @@ -4972,6 +6277,7 @@ function ImGui.IsMouseHoveringRect(r_min, r_max, clip) x1 = math.min(x1, cmax.x); y1 = math.min(y1, cmax.y) end + -- Hit testing, expanded for touch input local p, pad = g.IO.MousePos, g.Style.TouchExtraPadding if not (p.x >= x0 - pad.x and p.y >= y0 - pad.y and p.x < x1 + pad.x and p.y < y1 + pad.y) then return false @@ -5014,6 +6320,8 @@ function ImGui.IsMouseDragging(button, lock_threshold) return ImGui.IsMouseDragPastThreshold(button, lock_threshold) end +-- This is called TeleportMousePos() and not SetMousePos() to emphasis that setting MousePosPrev will effectively clear mouse delta as well. +-- It is expected you only call this if (io.BackendFlags & ImGuiBackendFlags.HasSetMousePos) is set and supported by backend. --- @param pos ImVec2 function ImGui.TeleportMousePos(pos) local g = GImGui @@ -5024,11 +6332,12 @@ function ImGui.TeleportMousePos(pos) -- IMGUI_DEBUG_LOG_IO("TeleportMousePos: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y) end +-- Called from within ItemAdd: at this point we can read from NextItemData and write to LastItemData --- @param id ImGuiID function ImGui.ItemHandleShortcut(id) local g = GImGui local flags = g.NextItemData.ShortcutFlags - IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetNextItemShortcut)) == 0) + IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetNextItemShortcut)) == 0) -- Passing flags not supported by SetNextItemShortcut()! if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.Disabled) ~= 0 then return @@ -5041,13 +6350,19 @@ function ImGui.ItemHandleShortcut(id) return end - g.NavActivateId = id + -- FIXME: Generalize Activation queue? + g.NavActivateId = id -- Will effectively disable clipping. g.NavActivateFlags = bit32.bor(ImGuiActivateFlags.PreferInput, ImGuiActivateFlags.FromShortcut) + -- if (g.ActiveId == 0 || g.ActiveId == id) g.NavActivateDownId = id g.NavActivatePressedId = id ImGui.NavHighlightActivated(id) end +-- Declare item bounding box for clipping and interaction. +-- Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface +-- declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction. +-- THIS IS IN THE PERFORMANCE CRITICAL PATH (UNTIL THE CLIPPING TEST AND EARLY-RETURN) --- @param bb ImRect --- @param id ImGuiID --- @param nav_bb_arg? ImRect @@ -5059,16 +6374,30 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) local g = GImGui local window = g.CurrentWindow + -- Set item data + -- (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags.HasDisplayRect is set) g.LastItemData.ID = id ImRect_Copy(g.LastItemData.Rect, bb) ImRect_Copy(g.LastItemData.NavRect, nav_bb_arg and nav_bb_arg or bb) g.LastItemData.ItemFlags = bit32.bor(g.CurrentItemFlags, g.NextItemData.ItemFlagsSet, extra_flags) g.LastItemData.StatusFlags = ImGuiItemStatusFlags.None + -- Note: we don't copy 'g.NextItemData.SelectionUserData' to an hypothetical g.LastItemData.SelectionUserData: since the former is not cleared. if id ~= 0 then ImGui.KeepAliveID(id) + -- Directional navigation processing + -- Runs prior to clipping early-out + -- (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget + -- (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests + -- unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of + -- thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. + -- We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able + -- to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick). + -- We intentionally don't check if g.NavWindow ~= nil because g.NavAnyRequest should only be set when it is non nil. + -- If we crash on a nil g.NavWindow we need to fix the bug elsewhere. if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoNav) == 0 then + -- FIXME-NAV: investigate changing the window tests into a simple 'if (g.NavFocusScopeId == g.CurrentFocusScopeId)' test. window.DC.NavLayersActiveMaskNext = bit32.bor(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, window.DC.NavLayerCurrent)) if g.NavId == id or g.NavAnyRequest then @@ -5085,9 +6414,13 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) end end + -- Lightweight clear of SetNextItemXXX data. g.NextItemData.HasFlags = ImGuiNextItemDataFlags.None g.NextItemData.ItemFlagsSet = ImGuiItemFlags.None + -- Clipping test + -- (this is an inline copy of IsClippedEx() so we can reuse the is_rect_visible value, otherwise we'd do 'if (IsClippedEx(bb, id)) return false') + -- g.NavActivateId is not necessarily == g.NavId, in the case of remote activation (e.g. shortcuts) local bmin, bmax, cr = bb.Min, bb.Max, window.ClipRect local is_rect_visible = bmin.x <= cr.Max.x and bmax.x >= cr.Min.x and bmin.y <= cr.Max.y and bmax.y >= cr.Min.y if not is_rect_visible then @@ -5100,6 +6433,7 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) g.DeactivatedItemData.ElapseFrame = g.FrameCount end + -- 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 then g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) end @@ -5111,6 +6445,39 @@ function ImGui.ItemAdd(bb, id, nav_bb_arg, extra_flags) return true end +------------------------------------------------------------------------------- +-- [SECTION] LAYOUT +------------------------------------------------------------------------------- +-- - ItemSize() +-- - SameLine() +-- - GetCursorScreenPos() +-- - SetCursorScreenPos() +-- - GetCursorPos(), GetCursorPosX(), GetCursorPosY() +-- - SetCursorPos(), SetCursorPosX(), SetCursorPosY() +-- - GetCursorStartPos() +-- - Indent() +-- - Unindent() +-- - SetNextItemWidth() +-- - PushItemWidth() +-- - PushMultiItemsWidths() +-- - PopItemWidth() +-- - CalcItemWidth() +-- - CalcItemSize() +-- - GetTextLineHeight() +-- - GetTextLineHeightWithSpacing() +-- - GetFrameHeight() +-- - GetFrameHeightWithSpacing() +-- - GetContentRegionMax() +-- - GetContentRegionAvail(), +-- - BeginGroup() +-- - EndGroup() +-- Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns. +------------------------------------------------------------------------------- + +-- Advance cursor given item size for layout. +-- Register minimum needed size so it can extend the bounding box used for auto-fit calculation. +-- See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different. +-- THIS IS IN THE PERFORMANCE CRITICAL PATH. --- @param size_or_bb ImVec2|ImRect --- @param text_baseline_y? float @native @@ -5136,6 +6503,9 @@ function ImGui.ItemSize(size_or_bb, text_baseline_y) local dc = window.DC local mathMax = math.max + -- We increase the height in this function to accommodate for baseline offset. + -- In theory we should be offsetting the starting position (window.DC.CursorPos), that will be the topic of a larger refactor, + -- but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect. local offset_to_match_baseline_y if text_baseline_y >= 0 then offset_to_match_baseline_y = mathMax(0, dc.CurrLineTextBaseOffset - text_baseline_y) @@ -5154,12 +6524,15 @@ function ImGui.ItemSize(size_or_bb, text_baseline_y) local line_height = mathMax(dc.CurrLineSize.y, cursor.y - line_y1 + size_y + offset_to_match_baseline_y) local spacing_y = g.Style.ItemSpacing.y + -- Always align ourselves on pixel boundaries + -- if (g.IO.KeyAlt) window.DrawList:AddRect(window.DC.CursorPos, window.DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)) -- [DEBUG] prev_line.x = cursor.x + size_x prev_line.y = line_y1 - cursor.x = math.floor(window.Pos.x + dc.Indent.x + dc.ColumnsOffset.x) - cursor.y = math.floor(line_y1 + line_height + spacing_y) + cursor.x = math.floor(window.Pos.x + dc.Indent.x + dc.ColumnsOffset.x) -- Next line + cursor.y = math.floor(line_y1 + line_height + spacing_y) -- Next line max_pos.x = mathMax(max_pos.x, prev_line.x) max_pos.y = mathMax(max_pos.y, cursor.y - spacing_y) + -- if (g.IO.KeyAlt) window.DrawList:AddCircle(window.DC.CursorMaxPos, 3.0, IM_COL32(255,0,0,255), 4) -- [DEBUG] dc.PrevLineSize.y = line_height dc.CurrLineSize.y = 0 @@ -5168,12 +6541,17 @@ function ImGui.ItemSize(size_or_bb, text_baseline_y) dc.IsSetPos = false dc.IsSameLine = false - --- Horizontal layout mode + -- Horizontal layout mode if (dc.LayoutType == ImGuiLayoutType.Horizontal) then ImGui.SameLine() end end +-- Gets back to previous line and continue with horizontal layout +-- offset_from_start_x == 0 : follow right after previous item +-- offset_from_start_x != 0 : align to specified x position (relative to window/group left) +-- spacing_w < 0 : use default spacing if offset_from_start_x == 0, no spacing if offset_from_start_x != 0 +-- spacing_w >= 0 : enforce spacing amount --- @param offset_from_start_x float? --- @param spacing_w float? @native @@ -5234,7 +6612,7 @@ function ImGui.Unindent(indent_w) window.DC.CursorPos.x = window.Pos.x + window.DC.Indent.x + window.DC.ColumnsOffset.x end --- Affect large frame+labels widgets only +-- Affect large frame+labels widgets only. --- @param item_width float function ImGui.SetNextItemWidth(item_width) local g = GImGui @@ -5242,11 +6620,12 @@ function ImGui.SetNextItemWidth(item_width) g.NextItemData.Width = item_width end +-- FIXME: Remove the == 0.0f behavior? --- @param item_width float function ImGui.PushItemWidth(item_width) local g = GImGui local window = g.CurrentWindow - window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) + window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) -- Backup current width window.DC.ItemWidth = (item_width == 0.0) and window.DC.ItemWidthDefault or item_width g.NextItemData.HasFlags = bit32.band(g.NextItemData.HasFlags, bit32.bnot(ImGuiNextItemDataFlags.HasWidth)) end @@ -5269,7 +6648,7 @@ function ImGui.PushMultiItemsWidths(components, w_full) local window = g.CurrentWindow IM_ASSERT(components > 0) local style = g.Style - window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) + window.DC.ItemWidthStack:push_back(window.DC.ItemWidth) -- Backup current width local w_items = w_full - style.ItemInnerSpacing.x * (components - 1) local prev_split = w_items for i = components - 1, 1, -1 do @@ -5317,10 +6696,12 @@ end function ImGui.SetCursorScreenPos(pos) local window = ImGui.GetCurrentWindow() ImVec2_Copy(window.DC.CursorPos, pos) + -- window.DC.CursorMaxPos = ImMax(window.DC.CursorMaxPos, window.DC.CursorPos) window.DC.IsSetPos = true end --- [window-local] cursor position, in window coordinates (relative to window position, including scrolling) +-- User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. +-- Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. --- @return ImVec2 function ImGui.GetCursorPos() local window = ImGui.GetCurrentWindowRead() @@ -5341,6 +6722,7 @@ end function ImGui.SetCursorPos(local_pos) local window = ImGui.GetCurrentWindow() ImVec2_CopyV(window.DC.CursorPos, window.Pos.x - window.Scroll.x + local_pos.x, window.Pos.y - window.Scroll.y + local_pos.y) + -- window.DC.CursorMaxPos = ImMax(window.DC.CursorMaxPos, window.DC.CursorPos) window.DC.IsSetPos = true end @@ -5348,6 +6730,7 @@ end function ImGui.SetCursorPosX(x) local window = ImGui.GetCurrentWindow() window.DC.CursorPos.x = window.Pos.x - window.Scroll.x + x + -- window.DC.CursorMaxPos.x = ImMax(window.DC.CursorMaxPos.x, window.DC.CursorPos.x) window.DC.IsSetPos = true end @@ -5355,6 +6738,7 @@ end function ImGui.SetCursorPosY(y) local window = ImGui.GetCurrentWindow() window.DC.CursorPos.y = window.Pos.y - window.Scroll.y + y + -- window.DC.CursorMaxPos.y = ImMax(window.DC.CursorMaxPos.y, window.DC.CursorPos.y) window.DC.IsSetPos = true end @@ -5374,6 +6758,8 @@ function ImGui.GetTextLineHeightWithSpacing() return g.FontSize + g.Style.ItemSpacing.y end +-- You should never need those functions. Always use GetCursorScreenPos() and GetContentRegionAvail()! +-- They are bizarre local-coordinates which don't play well with scrolling. --- @return ImVec2 function ImGui.GetContentRegionMax() local window = GImGui.CurrentWindow @@ -5432,7 +6818,7 @@ function ImGui.BeginGroup() ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorPos) ImVec2_CopyV(window.DC.CurrLineSize, 0.0, 0.0) if (g.LogEnabled) then - g.LogLinePosY = -FLT_MAX + g.LogLinePosY = -FLT_MAX -- To enforce a carriage return end end @@ -5449,6 +6835,7 @@ function ImGui.EndGroup() -- TODO: ImGui.ErrorCheckUsingSetCursorPosToExtendParentBoundaries() end + -- Include LastItemData.Rect.Max as a workaround for e.g. EndTable() undershooting with CursorMaxPos report. (#7543) local group_bb = ImRect(group_data.BackupCursorPos, ImMax(ImMax(window.DC.CursorMaxPos, g.LastItemData.Rect.Max), group_data.BackupCursorPos)) ImVec2_Copy(window.DC.CursorPos, group_data.BackupCursorPos) ImVec2_Copy(window.DC.CursorPosPrevLine, group_data.BackupCursorPosPrevLine) @@ -5467,7 +6854,7 @@ function ImGui.EndGroup() return end - window.DC.CurrLineTextBaseOffset = ImMax(window.DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset) -- FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now + window.DC.CurrLineTextBaseOffset = ImMax(window.DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset) -- FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. ImGui.ItemSize(group_bb:GetSize()) ImGui.ItemAdd(group_bb, 0, nil, ImGuiItemFlags.NoTabStop) @@ -5507,6 +6894,8 @@ function ImGui.EndGroup() end end +-- Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(). +-- The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags() @native function ImGui.CalcItemWidth() local g = GImGui @@ -5528,6 +6917,10 @@ function ImGui.CalcItemWidth() return w end +-- [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth(). +-- Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. +-- Note that only CalcItemWidth() is publicly exposed. +-- The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) --- @param size ImVec2 --- @param default_w float --- @param default_h float @@ -5541,13 +6934,13 @@ function ImGui.CalcItemSize(size, default_w, default_h) if size.x == 0.0 then size.x = default_w elseif size.x < 0.0 then - size.x = ImMax(4.0, avail.x + size.x) -- size.x is negative here so we are subtracting + size.x = ImMax(4.0, avail.x + size.x) -- <-- size.x is negative here so we are subtracting end if size.y == 0.0 then size.y = default_h elseif size.y < 0.0 then - size.y = ImMax(4.0, avail.y + size.y) -- size.y is negative here so we are subtracting + size.y = ImMax(4.0, avail.y + size.y) -- <-- size.y is negative here so we are subtracting end return size @@ -5568,12 +6961,15 @@ function ImGui.IsItemActive() return false end +-- == (GetItemID() == GetFocusID() && GetFocusID() != 0) function ImGui.IsItemFocused() local g = GImGui if g.NavId ~= g.LastItemData.ID or g.NavId == 0 then return false end + -- Special handling for the dummy item after Begin() which represent the title bar or tab. + -- When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. local window = g.CurrentWindow if g.LastItemData.ID == window.ID and window.WriteAccessed then return false @@ -5590,6 +6986,7 @@ function ImGui.IsItemDeactivated() return g.DeactivatedItemData.ID == g.LastItemData.ID and g.LastItemData.ID ~= 0 and g.DeactivatedItemData.ElapseFrame >= g.FrameCount end +-- Since 1.92.9: consider using NoLiveEdit flags if all you need to that values are not written bo backing variable while typing. function ImGui.IsItemDeactivatedAfterEdit() local g = GImGui return ImGui.IsItemDeactivated() and g.DeactivatedItemData.HasBeenEditedBefore @@ -5606,6 +7003,7 @@ function ImGui.IsItemActivated() end -- Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()! +-- Most widgets have specific reactions based on mouse-up/down state, mouse position etc. --- @param mouse_button? ImGuiMouseButton function ImGui.IsItemClicked(mouse_button) if mouse_button == nil then mouse_button = 0 end @@ -5616,12 +7014,21 @@ function ImGui.IsItemToggledOpen() return bit32.band(GImGui.LastItemData.StatusFlags, ImGuiItemStatusFlags.ToggledOpen) ~= 0 end +-- Call after a Selectable() or TreeNode() items inside a BeginMultiSelect()/EndMultiSelect() scope. +-- - Useful if you need the per-item information before reaching EndMultiSelect(), e.g. for rendering purpose. +-- Outside of a multi-select block: +-- - It would be misleading/ambiguous to report this signal, as widgets return e.g. a pressed event, +-- and user code is in charge of altering selection in ways we cannot predict. +-- Prefer using 'if (IsItemClicked() && !IsItemToggledOpen())' for a manual reimplementation of selection. function ImGui.IsItemToggledSelection() local g = GImGui IM_ASSERT(g.CurrentMultiSelect ~= nil) -- Can only be used inside a BeginMultiSelect()/EndMultiSelect() return bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.ToggledSelection) ~= 0 end +-- IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, +-- you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! +-- Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. function ImGui.IsAnyItemHovered() local g = GImGui return g.HoveredId ~= 0 or g.HoveredIdPreviousFrame ~= 0 @@ -5645,6 +7052,8 @@ function ImGui.IsItemEdited() end -- Allow next item to be overlapped by subsequent items. +-- This works by requiring HoveredId to match for two subsequent frames, +-- so if a following items overwrite it our interactions will naturally be disabled. function ImGui.SetNextItemAllowOverlap() local g = GImGui g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.AllowOverlap) @@ -5668,10 +7077,23 @@ function ImGui.GetHoveredID() return (g.HoveredId ~= 0) and g.HoveredId or g.HoveredIdPreviousFrame end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] WINDOW FOCUS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - SetWindowFocus() +-- - SetNextWindowFocus() +-- - IsWindowFocused() +-- - UpdateWindowInFocusOrderList() [Internal] +-- - BringWindowToFocusFront() [Internal] +-- - BringWindowToDisplayFront() [Internal] +-- - BringWindowToDisplayBack() [Internal] +-- - BringWindowToDisplayBehind() [Internal] +-- - FindWindowDisplayIndex() [Internal] +-- - FocusWindow() [Internal] +-- - FocusTopMostWindowUnderOne() [Internal] +------------------------------------------------------------------------------- +-- Moving window to front of display and set focus (which happens to be back of our sorted list) --- @param window? ImGuiWindow --- @param flags? ImGuiFocusRequestFlags function ImGui.FocusWindow(window, flags) @@ -5679,28 +7101,34 @@ function ImGui.FocusWindow(window, flags) local g = GImGui - if bit32.band(flags, ImGuiFocusRequestFlags.UnlessBelowModal) ~= 0 and g.NavWindow ~= window then + -- Modal check? + if bit32.band(flags, ImGuiFocusRequestFlags.UnlessBelowModal) ~= 0 and g.NavWindow ~= window then -- Early out in common case. local blocking_modal = ImGui.FindBlockingModal(window) if blocking_modal then + -- 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 == nil) -- IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".", window ? window->Name : "", blocking_modal->Name) if window and window == window.RootWindow and bit32.band(window.Flags, ImGuiWindowFlags.NoBringToFrontOnFocus) == 0 then - ImGui.BringWindowToDisplayBehind(window, blocking_modal) + ImGui.BringWindowToDisplayBehind(window, blocking_modal) -- Still bring right under modal. (FIXME: Could move in focus list too?) end - ImGui.ClosePopupsOverWindow(ImGui.GetTopMostPopupModal(), false) + ImGui.ClosePopupsOverWindow(ImGui.GetTopMostPopupModal(), false) -- Note how we need to use GetTopMostPopupModal() aad NOT blocking_modal, to handle nested modals return end end + -- Find last focused child (if any) and focus it instead. if bit32.band(flags, ImGuiFocusRequestFlags.RestoreFocusedChild) ~= 0 and window ~= nil then window = ImGui.NavRestoreLastChildNavWindow(window) end + -- Apply focus if g.NavWindow ~= window then ImGui.SetNavWindow(window) if window and g.NavHighlightItemUnderNav then g.NavMousePosDirty = true end - g.NavId = window and window.NavLastIds[0] or 0 + g.NavId = window and window.NavLastIds[0] or 0 -- Restore NavId g.NavLayer = ImGuiNavLayer.Main ImGui.SetNavFocusScope(window and window.NavRootFocusScopeId or 0) g.NavIdIsAlive = false @@ -5710,23 +7138,35 @@ function ImGui.FocusWindow(window, flags) ImGui.ClosePopupsOverWindow(window, false) end + -- Move the root window to the top of the pile IM_ASSERT(window == nil or window.RootWindowDockTree ~= nil) local focus_front_window = window and window.RootWindow or nil local display_front_window = window and window.RootWindowDockTree or nil local dock_node = window and window.DockNode or nil local active_id_window_is_dock_node_host = g.ActiveIdWindow and dock_node and 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 and g.ActiveIdWindow and g.ActiveIdWindow.RootWindow ~= focus_front_window then if not g.ActiveIdNoClearOnFocusLoss and not active_id_window_is_dock_node_host then ImGui.ClearActiveID() end end + -- Passing nil allow to disable keyboard focus if not window then return end 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 ImGui.BringWindowToFocusFront(focus_front_window) if bit32.band(bit32.bor(window.Flags, focus_front_window.Flags, display_front_window.Flags), ImGuiWindowFlags.NoBringToFrontOnFocus) == 0 then ImGui.BringWindowToDisplayFront(display_front_window) @@ -5744,6 +7184,9 @@ function ImGui.FindWindowFocusIndex(window) return order end +-- 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. --- @param window ImGuiWindow --- @return bool function ImGui.IsWindowNavFocusable(window) @@ -5754,7 +7197,7 @@ end --- @param i_stop int --- @param dir int --- @return ImGuiWindow? -function ImGui.FindWindowNavFocusable(i_start, i_stop, dir) +function ImGui.FindWindowNavFocusable(i_start, i_stop, dir) -- FIXME-OPT O(N) local g = GImGui local i = i_start while i >= 1 and i <= g.WindowsFocusOrder.Size and i ~= i_stop do @@ -5815,13 +7258,15 @@ function ImGui.BringWindowToFocusFront(window) window.FocusOrder = new_order end +-- Note technically focus related but rather adjacent and close to BringWindowToFocusFront() +-- FIXME-FOCUS: Could opt-in/opt-out enable modal check like in FocusWindow(). --- @param window? ImGuiWindow function ImGui.BringWindowToDisplayFront(window) local g = GImGui local current_front_window = g.Windows:back() - if current_front_window == window or current_front_window.RootWindowDockTree == window then + if current_front_window == window or current_front_window.RootWindowDockTree == window then -- Cheap early out (could be better) return end @@ -5864,6 +7309,7 @@ function ImGui.FocusTopMostWindowUnderOne(under_this_window, ignore_window, filt end for i = start_idx, 1, -1 do repeat + -- 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. local window = g.WindowsFocusOrder.Data[i] if window == ignore_window or not window.WasActive then break @@ -5872,6 +7318,11 @@ function ImGui.FocusTopMostWindowUnderOne(under_this_window, ignore_window, filt break end if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs)) ~= bit32.bor(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs) then + -- 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? ImGui.FocusWindow(window, flags) return end @@ -5891,6 +7342,8 @@ function ImGui.SetFocusID(id, window) ImGui.SetNavWindow(window) end + -- Assume that SetFocusID() is called in the context where its window.DC.NavLayerCurrent and g.CurrentFocusScopeId are valid. + -- Note that window may be ~= g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text) local nav_layer = window.DC.NavLayerCurrent g.NavId = id g.NavLayer = nav_layer @@ -5910,23 +7363,33 @@ function ImGui.SetFocusID(id, window) g.NavCursorVisible = false end + -- Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y) end +-- This is not 100% symmetric 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). function ImGui.StopMouseMovingWindow() local g = GImGui local window = g.MovingWindow + -- Ref commits 6b7766817, 36055213c for some partial history on checking if viewport ~= nil. if window and window.Viewport then + -- 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 bit32.band(g.ConfigFlagsCurrFrame, ImGuiConfigFlags.ViewportsEnable) ~= 0 then ImGui.UpdateTryMergeWindowIntoHostViewport(window.RootWindowDockTree, g.MouseViewport) end + -- 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 (not ImGui.IsDragDropPayloadBeingAccepted()) then g.MouseViewport = window.Viewport end + -- Clear the NoInputs window flag set by the Viewport system in AddUpdateViewport() local window_can_use_inputs = bit32.band(window.Flags, ImGuiWindowFlags.NoMouseInputs) == 0 or bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) == 0 if window_can_use_inputs then window.Viewport.Flags = bit32.band(window.Viewport.Flags, bit32.bnot(ImGuiViewportFlags.NoInputs)) @@ -5941,23 +7404,32 @@ end function ImGui.SetActiveID(id, window) local g = GImGui + -- Clear previous active id if g.ActiveId ~= 0 then + -- Store deactivate data local deactivated_data = g.DeactivatedItemData deactivated_data.ID = g.ActiveId deactivated_data.ElapseFrame = (g.LastItemData.ID == g.ActiveId) and g.FrameCount or 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 then ImGui.InputTextDeactivateHook(g.ActiveId) end + -- 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 and (g.ActiveId == g.MovingWindow.MoveId) then print("SetActiveID() cancel MovingWindow") ImGui.StopMouseMovingWindow() end end + -- Set active id g.ActiveIdIsJustActivated = (g.ActiveId ~= id) if (g.ActiveIdIsJustActivated) then -- IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() 0x%08X in \"%s\"%*s(previously 0x%08X in \"%s\")\n", id, window ? window->Name : "", @@ -5989,14 +7461,20 @@ function ImGui.SetActiveID(id, window) IM_ASSERT(g.ActiveIdSource ~= ImGuiInputSource.None) end + -- Clear declaration of inputs claimed by the widget + -- (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet) g.ActiveIdUsingNavDirMask = 0x00 g.ActiveIdUsingAllKeyboardKeys = false end function ImGui.ClearActiveID() - ImGui.SetActiveID(0, nil) + ImGui.SetActiveID(0, nil) -- g.ActiveId = 0 end +------------------------------------------------------------------------------- +-- [SECTION] ID STACK +------------------------------------------------------------------------------- + --- @param str_id string|int @native function ImGui.PushID(str_id) @@ -6006,6 +7484,7 @@ function ImGui.PushID(str_id) window.IDStack:push_back(id) end +-- Push a given id value ignoring the ID stack as a seed. --- @param id ImGuiID function ImGui.PushOverrideID(id) local g = GImGui @@ -6023,6 +7502,8 @@ function ImGui.PopID() window.IDStack:pop_back() end +-- This is one of the very rare legacy case where we use ImGuiWindow methods, +-- it should ideally be flattened at some point but it's been used a lots by widgets. --- @param id string|int --- @return ImGuiID @native @@ -6042,7 +7523,7 @@ function MT.ImGuiWindow:GetID(id) return h end --- This is only used in rare/specific situations to manufacture an ID out of nowhere +-- This is only used in rare/specific situations to manufacture an ID out of nowhere. -- FIXME: Consider instead storing last non-zero ID + count of successive zero-ID, and combine those? --- @param p_abs ImVec2 --- @return ImGuiID @@ -6073,6 +7554,9 @@ function ImGui.GetID(str_or_int, str_end) return window:GetID(str_or_int) end +-- Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call +-- (note that when using this pattern, ID Stack Tool will tend to not display the intermediate stack level. +-- for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more) -- Overloads: GetIDWithSeed(str, str_end, seed) / GetIDWithSeed(n, seed) function ImGui.GetIDWithSeed(a, b, c) local id @@ -6115,6 +7599,7 @@ end --- @param user_flags ImGuiHoveredFlags --- @param shared_flags ImGuiHoveredFlags local function ApplyHoverFlagsForTooltip(user_flags, shared_flags) + -- Allow instance flags to override shared flags if bit32.band(user_flags, bit32.bor(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.DelayNormal)) ~= 0 then shared_flags = bit32.band(shared_flags, bit32.bnot(bit32.bor(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.DelayNormal))) end @@ -6127,6 +7612,7 @@ function ImGui.MarkItemEdited(id) -- ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data. local g = GImGui + -- IM_ASSERT(g.LastItemData.ID == id) -- Failing cases include: "widgets_inputtext_scrolling", "widgets_inputtext_multiline_status", "widgets_selectable_input" = case of e.g TempInputText() overlayed manually with different ID (#2718) g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal) if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited) ~= 0 then return @@ -6189,6 +7675,9 @@ function ImGui.IsWindowContentHoverable(window, flags) return true end +-- This is roughly matching the behavior of internal-facing ItemHoverable() +-- - we allow hovering to be true when ActiveId==window.MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() +-- - this should work even for non-interactive items that have no ID, so we cannot use LastItemId --- @param flags? ImGuiHoveredFlags @native function ImGui.IsItemHovered(flags) @@ -6210,6 +7699,7 @@ function ImGui.IsItemHovered(flags) flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipNav) end else + -- Test for bounding box overlap, as updated as ItemAdd() local status_flags = g.LastItemData.StatusFlags if bit32.band(status_flags, ImGuiItemStatusFlags.HoveredRect) == 0 then return false @@ -6219,19 +7709,31 @@ function ImGui.IsItemHovered(flags) flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse) end + -- Done with rectangle culling so we can perform heavier checks now + -- Test if we are hovering the right window (our window could be behind another window) + -- [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851) + -- [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable + -- to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was + -- the test that has been running for a long while. if g.HoveredWindow ~= window and bit32.band(status_flags, ImGuiItemStatusFlags.HoveredWindow) == 0 then if bit32.band(flags, ImGuiHoveredFlags.AllowWhenOverlappedByWindow) == 0 then return false end end + -- Test if another item is active (e.g. being dragged) local id = g.LastItemData.ID if bit32.band(flags, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) == 0 then if g.ActiveId ~= 0 and g.ActiveId ~= id and not g.ActiveIdAllowOverlap and not g.ActiveIdFromShortcut then + -- 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. local cancel_is_hovered = true if g.ActiveId == window.MoveId and (id == 0 or g.ActiveIdDisabledId == id) then cancel_is_hovered = false end + -- When ActiveId == TabId it means user clicked docking tab for the window. if g.ActiveId == window.TabId then cancel_is_hovered = false end @@ -6241,18 +7743,25 @@ function ImGui.IsItemHovered(flags) end end + -- Test if interactions on this window are blocked by an active popup or modal. + -- The ImGuiHoveredFlags.AllowWhenBlockedByPopup flag will be tested here. if not ImGui.IsWindowContentHoverable(window, flags) and bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.NoWindowHoverableCheck) == 0 then return false end + -- Test if the item is disabled if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.Disabled) ~= 0 and bit32.band(flags, ImGuiHoveredFlags.AllowWhenDisabled) == 0 then return false end + -- Special handling for calling after Begin() which represent the title bar or tab. + -- When the window is skipped/collapsed (SkipItems==true) that last item (always .MoveId submitted by Begin) + -- will never be overwritten so we need to detect the case. if id == window.MoveId and window.WriteAccessed then return false end + -- Test if using AllowOverlap and overlapped if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowOverlap) ~= 0 and id ~= 0 then if bit32.band(flags, ImGuiHoveredFlags.AllowWhenOverlappedByItem) == 0 then if g.HoveredIdPreviousFrame ~= g.LastItemData.ID then @@ -6262,6 +7771,8 @@ function ImGui.IsItemHovered(flags) end end + -- Handle hover delay + -- (some ideas: https://www.nngroup.com/articles/timing-exposing-content) local delay = CalcDelayFromHoveredFlags(flags) if delay > 0.0 or bit32.band(flags, ImGuiHoveredFlags.Stationary) ~= 0 then local hover_delay_id @@ -6275,6 +7786,9 @@ function ImGui.IsItemHovered(flags) end g.HoverItemDelayId = hover_delay_id + -- When changing hovered item we requires a bit of stationary delay before activating hover timer, + -- but once unlocked on a given item we also moving. + -- if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); } if bit32.band(flags, ImGuiHoveredFlags.Stationary) ~= 0 and g.HoverItemUnlockedStationaryId ~= hover_delay_id then return false end @@ -6287,6 +7801,13 @@ function ImGui.IsItemHovered(flags) return true end +-- 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: +-- - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.ItemFlags'. +-- - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags.None) unless you want to benefit from special behavior handled by ItemHoverable. --- @param bb ImRect --- @param id ImGuiID --- @param item_flags ImGuiItemFlags @@ -6295,6 +7816,8 @@ function ImGui.ItemHoverable(bb, id, item_flags) local g = GImGui local 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) if not IMGUI_DISABLE_DEBUG_TOOLS then if id ~= 0 and g.HoveredIdPreviousFrame == id and bit32.band(item_flags, ImGuiItemFlags.AllowDuplicateId) == 0 then g.HoveredIdPreviousFrameItemCount = g.HoveredIdPreviousFrameItemCount + 1 @@ -6322,18 +7845,24 @@ end end end + -- We are done with rectangle culling so we can perform heavier checks now. if (bit32.band(item_flags, ImGuiItemFlags.NoWindowHoverableCheck) == 0) and not ImGui.IsWindowContentHoverable(window, ImGuiHoveredFlags.None) then g.HoveredIdIsDisabled = true return false end + -- We exceptionally allow this function to be called with id==0 to allow using it for easy high-level + -- hover test in widgets code. We could also decide to split this function is two. if id ~= 0 then + -- Drag source doesn't report as hovered if g.DragDropActive and g.DragDropPayload.SourceId == id and (bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceNoDisableHover) == 0) then return false end ImGui.SetHoveredID(id) + -- AllowOverlap mode (rarely used) requires previous frame HoveredId to be nil or to match. + -- This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test. if bit32.band(item_flags, ImGuiItemFlags.AllowOverlap) ~= 0 then g.HoveredIdAllowOverlap = true if g.HoveredIdPreviousFrame ~= id then @@ -6341,6 +7870,8 @@ end end end + -- Display shortcut (only works with mouse) + -- (ImGuiItemStatusFlags.HasShortcut in LastItemData denotes we want a tooltip) if id == g.LastItemData.ID and (bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasShortcut) ~= 0) and g.ActiveId ~= id then if ImGui.IsItemHovered(bit32.bor(ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.DelayNormal)) then ImGui.SetTooltip("%s", ImGui.GetKeyChordName(g.LastItemData.Shortcut)) @@ -6348,6 +7879,7 @@ end end end + -- When disabled we'll return false but still set HoveredId if bit32.band(item_flags, ImGuiItemFlags.Disabled) ~= 0 then -- Release active id if turning disabled if g.ActiveId == id and id ~= 0 then @@ -6364,6 +7896,8 @@ end return true end +-- FIXME: This is inlined/duplicated in ItemAdd() +-- FIXME: The id ~= 0 path is not used by our codebase, may get rid of it? --- @param bb ImRect --- @param id ImGuiID --- @return bool @@ -6380,6 +7914,8 @@ function ImGui.IsClippedEx(bb, id) return false end +-- This is also inlined in ItemAdd() +-- Note: if ImGuiItemStatusFlags.HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect. --- @param item_id ImGuiID --- @param item_flags ImGuiItemFlags --- @param status_flags ImGuiItemStatusFlags @@ -6404,6 +7940,10 @@ function ImGui.SetLastItemDataForWindow(window, rect) end end +-- Pass in translated ASCII characters for text input. +-- - with glfw you can get those from the callback set in glfwSetCharCallback() +-- - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message +-- FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API --- @param c unsigned_int function MT.ImGuiIO:AddInputCharacter(c) IM_ASSERT(self.Ctx ~= nil) @@ -6423,6 +7963,8 @@ function MT.ImGuiIO:AddInputCharacter(c) g.InputEventsQueue:push_back(e) end +-- UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so +-- we should save the high surrogate. --- @param c ImWchar16 function MT.ImGuiIO:AddInputCharacterUTF16(c) if (c == 0 and self.InputQueueSurrogate == 0) or not self.AppAcceptingEvents then @@ -6439,11 +7981,11 @@ function MT.ImGuiIO:AddInputCharacterUTF16(c) local cp = c if self.InputQueueSurrogate ~= 0 then - if bit32.band(c, 0xFC00) ~= 0xDC00 then -- Invalid low surrogate + if bit32.band(c, 0xFC00) ~= 0xDC00 then -- Invalid low surrogate self:AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID) else -- #if IM_UNICODE_CODEPOINT_MAX == 0xFFFF - cp = IM_UNICODE_CODEPOINT_INVALID + cp = IM_UNICODE_CODEPOINT_INVALID -- Codepoint will not fit in ImWchar -- #endif end @@ -6452,12 +7994,14 @@ function MT.ImGuiIO:AddInputCharacterUTF16(c) self:AddInputCharacter(cp) end +-- Clear all incoming events. function MT.ImGuiIO:ClearEventsQueue() IM_ASSERT(self.Ctx ~= nil) local g = GImGui g.InputEventsQueue:clear() end +-- Clear current keyboard/gamepad state + current frame text input buffer. Equivalent to releasing all keys/buttons. function MT.ImGuiIO:ClearInputKeys() local g = self.Ctx for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do @@ -6473,7 +8017,7 @@ function MT.ImGuiIO:ClearInputKeys() self.KeyAlt = false self.KeySuper = false self.KeyMods = ImGuiMod_None - self.InputQueueCharacters:resize(0) + self.InputQueueCharacters:resize(0) -- Behavior of old ClearInputCharacters(). end function MT.ImGuiIO:ClearInputMouse() @@ -6520,18 +8064,25 @@ function MT.ImGuiIO:FindLatestInputEvent(ctx, type, arg) return nil end +-- Queue a new key down/up event. +-- - ImGuiKey key: Translated key (as in, generally ImGuiKey.A matches the key end-user would use to emit an 'A' character) +-- - bool down: Is the key down? use false to signify a key release. +-- - float analog_value: 0.0f..1.0f +-- IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE. +-- WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT. --- @param key ImGuiKey --- @param down bool --- @param analog_value float function MT.ImGuiIO:AddKeyAnalogEvent(key, down, analog_value) + -- if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); } IM_ASSERT(self.Ctx ~= nil) if key == ImGuiKey.None or not self.AppAcceptingEvents then return end local g = self.Ctx - IM_ASSERT(ImGui.IsNamedKeyOrMod(key)) - IM_ASSERT(ImGui.IsAliasKey(key) == false) + IM_ASSERT(ImGui.IsNamedKeyOrMod(key)) -- Backend needs to pass a valid ImGuiKey constant. 0..511 values are legacy native key codes which are not accepted by this API. + IM_ASSERT(ImGui.IsAliasKey(key) == false) -- Backend cannot submit ImGuiKey.MouseXXX values they are automatically inferred from AddMouseXXX() events. -- MacOS: swap Cmd(Super) and Ctrl if (g.IO.ConfigMacOSXBehaviors) then @@ -6544,6 +8095,7 @@ function MT.ImGuiIO:AddKeyAnalogEvent(key, down, analog_value) end end + -- Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed) local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.Key, key) local key_data = ImGui.GetKeyData(g, key) local latest_key_down = latest_event and latest_event.Key.Down or key_data.Down @@ -6552,6 +8104,7 @@ function MT.ImGuiIO:AddKeyAnalogEvent(key, down, analog_value) return end + -- Add event local e = ImGuiInputEvent() e.Type = ImGuiInputEventType.Key e.Source = ImGui.IsGamepadKey(key) and ImGuiInputSource.Gamepad or ImGuiInputSource.Keyboard @@ -6573,11 +8126,14 @@ function MT.ImGuiIO:AddKeyEvent(key, down) self:AddKeyAnalogEvent(key, down, (down and 1.0 or 0.0)) end +-- 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. --- @param accepting_events bool function MT.ImGuiIO:SetAppAcceptingEvents(accepting_events) self.AppAcceptingEvents = accepting_events end +-- This is not a real event, the data is latched in order to be stored in actual Mouse events. +-- This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes. --- @param source ImGuiMouseSource function MT.ImGuiIO:AddMouseSourceEvent(source) IM_ASSERT(self.Ctx ~= nil) @@ -6589,7 +8145,7 @@ end function MT.ImGuiIO:AddMouseViewportEvent(viewport_id) IM_ASSERT(self.Ctx ~= nil) local g = self.Ctx - -- IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags.HasMouseHoveredViewport); + -- IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags.HasMouseHoveredViewport) if (not self.AppAcceptingEvents) then return end @@ -6619,6 +8175,7 @@ function MT.ImGuiIO:AddFocusEvent(focused) IM_ASSERT(self.Ctx ~= nil) local g = self.Ctx + -- Filter duplicate local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.Focus) local latest_focused = latest_event and latest_event.AppFocused.Focused or (not g.IO.AppFocusLost) if latest_focused == focused or (self.ConfigDebugIgnoreFocusLoss and not focused) then @@ -6634,6 +8191,7 @@ function MT.ImGuiIO:AddFocusEvent(focused) g.InputEventsQueue:push_back(e) end +-- Queue a mouse move event --- @param x float --- @param y float function MT.ImGuiIO:AddMousePosEvent(x, y) @@ -6644,6 +8202,7 @@ function MT.ImGuiIO:AddMousePosEvent(x, y) local g = self.Ctx + -- Apply same flooring as UpdateMouseInputs() local x_val = x if x > -FLT_MAX then x_val = ImFloor(x) @@ -6653,6 +8212,7 @@ function MT.ImGuiIO:AddMousePosEvent(x, y) y_val = ImFloor(y) end + -- Filter duplicate local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.MousePos) local latest_pos = latest_event and ImVec2(latest_event.MousePos.PosX, latest_event.MousePos.PosY) or self.MousePos if latest_pos.x == x_val and latest_pos.y == y_val then @@ -6690,6 +8250,7 @@ function MT.ImGuiIO:AddMouseButtonEvent(mouse_button, down) end end + -- Filter duplicate local latest_event = self:FindLatestInputEvent(g, ImGuiInputEventType.MouseButton, mouse_button) local latest_button_down = latest_event and latest_event.MouseButton.Down or self.MouseDown[mouse_button] if latest_button_down == down then @@ -6721,11 +8282,13 @@ function MT.ImGuiIO:AddMouseButtonEvent(mouse_button, down) g.InputEventsQueue:push_back(e) end +-- Queue a mouse wheel event (some mouse/API may only have a Y component) --- @param wheel_x float --- @param wheel_y float function MT.ImGuiIO:AddMouseWheelEvent(wheel_x, wheel_y) IM_ASSERT(self.Ctx ~= nil) local g = self.Ctx + -- Filter duplicate (unlike most events, wheel values are relative and easy to filter) if not self.AppAcceptingEvents or (wheel_x == 0 and wheel_y == 0) then return end @@ -6742,6 +8305,73 @@ function MT.ImGuiIO:AddMouseWheelEvent(wheel_x, wheel_y) g.InputEventsQueue:push_back(e) end +------------------------------------------------------------------------------- +-- [SECTION] INPUTS +------------------------------------------------------------------------------- +-- - GetModForLRModKey() [Internal] +-- - FixupKeyChord() [Internal] +-- - GetKeyData() [Internal] +-- - GetKeyIndex() [Internal] +-- - GetKeyName() +-- - GetKeyChordName() [Internal] +-- - CalcTypematicRepeatAmount() [Internal] +-- - GetTypematicRepeatRate() [Internal] +-- - GetKeyPressedAmount() [Internal] +-- - GetKeyMagnitude2d() [Internal] +------------------------------------------------------------------------------- +-- - UpdateKeyRoutingTable() [Internal] +-- - GetRoutingIdFromOwnerId() [Internal] +-- - GetShortcutRoutingData() [Internal] +-- - CalcRoutingScore() [Internal] +-- - SetShortcutRouting() [Internal] +-- - TestShortcutRouting() [Internal] +------------------------------------------------------------------------------- +-- - IsKeyDown() +-- - IsKeyPressed() +-- - IsKeyReleased() +------------------------------------------------------------------------------- +-- - IsMouseDown() +-- - IsMouseClicked() +-- - IsMouseReleased() +-- - IsMouseDoubleClicked() +-- - GetMouseClickedCount() +-- - GetItemClickedCountWithSingleClickDelay() +-- - IsMouseHoveringRect() [Internal] +-- - IsMouseDragPastThreshold() [Internal] +-- - IsMouseDragging() +-- - GetMousePos() +-- - SetMousePos() [Internal] +-- - GetMousePosOnOpeningCurrentPopup() +-- - IsMousePosValid() +-- - IsAnyMouseDown() +-- - GetMouseDragDelta() +-- - ResetMouseDragDelta() +-- - GetMouseCursor() +-- - SetMouseCursor() +------------------------------------------------------------------------------- +-- - UpdateAliasKey() +-- - GetMergedModsFromKeys() +-- - UpdateKeyboardInputs() +-- - UpdateMouseInputs() +------------------------------------------------------------------------------- +-- - LockWheelingWindow [Internal] +-- - FindBestWheelingWindow [Internal] +-- - UpdateMouseWheel() [Internal] +------------------------------------------------------------------------------- +-- - SetNextFrameWantCaptureKeyboard() +-- - SetNextFrameWantCaptureMouse() +------------------------------------------------------------------------------- +-- - GetInputSourceName() [Internal] +-- - DebugPrintInputEvent() [Internal] +-- - UpdateInputEvents() [Internal] +------------------------------------------------------------------------------- +-- - GetKeyOwner() [Internal] +-- - TestKeyOwner() [Internal] +-- - SetKeyOwner() [Internal] +-- - SetItemKeyOwner() [Internal] +-- - Shortcut() [Internal] +------------------------------------------------------------------------------- + --- @param key ImGuiKey local function GetModForLRModKey(key) if key == ImGuiKey.LeftCtrl or key == ImGuiKey.RightCtrl then @@ -6761,6 +8391,7 @@ end --- @param key_chord ImGuiKeyChord function ImGui.FixupKeyChord(key_chord) + -- Add ImGuiMod_XXXX when a corresponding ImGuiKey.LeftXXX/ImGuiKey.RightXXX is specified. local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if ImGui.IsLRModKey(key) then key_chord = bit32.bor(key_chord, GetModForLRModKey(key)) @@ -6774,6 +8405,7 @@ end function ImGui.GetKeyData(ctx, key) if ctx == nil then ctx = GImGui end + -- Special storage location for mods if bit32.band(key, ImGuiMod_Mask_) ~= 0 then key = ImGui.ConvertSingleModFlagToKey(key) end @@ -6783,6 +8415,7 @@ function ImGui.GetKeyData(ctx, key) return ctx.IO.KeysData[idx], idx end +-- Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey.GamepadLStick* values). --- @param key_left ImGuiKey --- @param key_right ImGuiKey --- @param key_up ImGuiKey @@ -6794,6 +8427,10 @@ function ImGui.GetKeyMagnitude2d(key_left, key_right, key_up, key_down) ) end +-- TestKeyOwner(..., ID) : (owner == None || owner == ID) +-- TestKeyOwner(..., None) : (owner == None) +-- TestKeyOwner(..., Any) : no owner test +-- All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags.LockXXX flags. --- @param key ImGuiKey --- @param owner_id ImGuiID function ImGui.TestKeyOwner(key, owner_id) @@ -6813,6 +8450,9 @@ function ImGui.TestKeyOwner(key, owner_id) return not owner_data.LockThisFrame end + -- Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId + -- are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things. + -- Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions. if owner_data.OwnerCurr ~= owner_id then if owner_data.LockThisFrame then return false @@ -6825,6 +8465,8 @@ function ImGui.TestKeyOwner(key, owner_id) return true end +-- Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes. +-- Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey.A) (>= 1.87) --- @param key ImGuiKey --- @param owner_id? ImGuiID function ImGui.IsKeyDown(key, owner_id) @@ -6864,6 +8506,7 @@ function ImGui.IsKeyReleased(key, owner_id) return true end +-- Important: unlike legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat. --- @param key ImGuiKey --- @param flags ImGuiInputFlags --- @param owner_id? ImGuiID @@ -6873,8 +8516,7 @@ function ImGui.IsKeyPressedEx(key, flags, owner_id) local g = GImGui local key_data = ImGui.GetKeyData(g, key) - -- In theory this should already be encoded as (DownDuration < 0.0), but testing this facilitates eating mechanism (until we finish work on key ownership) - if not key_data.Down then + if not key_data.Down then -- In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership) return false end local t = key_data.DownDuration @@ -6917,6 +8559,7 @@ function ImGui.IsKeyPressedEx(key, flags, owner_id) end -- TODO: +-- Return untranslated names: on macOS, Cmd key will show as Ctrl, Ctrl key will show as super. function ImGui.GetKeyChordName(key_chord) local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if ImGui.IsLRModKey(key) then @@ -6933,6 +8576,7 @@ function ImGui.GetKeyChordName(key_chord) return s end +-- Those names are provided for debugging purpose and are not meant to be saved persistently nor compared. local GKeyNames = { "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown", "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape", @@ -6993,6 +8637,10 @@ function ImGui.GetKeyOwner(key) return owner_id end +-- t0 = previous time (e.g.: g.Time - g.IO.DeltaTime) +-- t1 = current time (e.g.: g.Time) +-- An event is triggered at: +-- t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N --- @param t0 float --- @param t1 float --- @param repeat_delay float @@ -7036,6 +8684,8 @@ function ImGui.GetTypematicRepeatRate(flags) else repeat_delay = g.IO.KeyRepeatDelay * 1.00; repeat_rate = g.IO.KeyRepeatRate * 1.00; return repeat_delay, repeat_rate end end +-- Return value representing the number of presses in the last time period, for the given repeat rate +-- (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate) --- @param key ImGuiKey --- @param repeat_delay float --- @param repeat_rate float @@ -7049,6 +8699,10 @@ function ImGui.GetKeyPressedAmount(key, repeat_delay, repeat_rate) return ImGui.CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate) end +-- Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data. +-- Entries D,A,B,B,A,C,B --> A,A,B,B,B,C,D +-- Index A:1 B:2 C:5 D:0 --> A:0 B:2 C:5 D:6 +-- See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation. --- @param rt ImGuiKeyRoutingTable function ImGui.UpdateKeyRoutingTable(rt) local g = GImGui --[[@as ImGuiContext]] @@ -7061,19 +8715,22 @@ function ImGui.UpdateKeyRoutingTable(rt) repeat routing_entry = rt.Entries[old_routing_idx] routing_entry.RoutingCurrScore = routing_entry.RoutingNextScore - routing_entry.RoutingCurr = routing_entry.RoutingNext + routing_entry.RoutingCurr = routing_entry.RoutingNext -- Update entry routing_entry.RoutingNext = ImGuiKeyOwner_NoOwner routing_entry.RoutingNextScore = 0 if routing_entry.RoutingCurr == ImGuiKeyOwner_NoOwner then break end - rt.EntriesNext:push_back(routing_entry) + rt.EntriesNext:push_back(routing_entry) -- Write alive ones into new buffer + -- Apply routing to owner if there's no owner already (RoutingCurr == None at this point) + -- This is the result of previous frame's SetShortcutRouting() call. if routing_entry.Mods == g.IO.KeyMods then local owner_data = ImGui.GetKeyOwnerData(g, key) if owner_data.OwnerCurr == ImGuiKeyOwner_NoOwner then owner_data.OwnerCurr = routing_entry.RoutingCurr + -- IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X) via Routing\n", GetKeyName(key), routing_entry->RoutingCurr); end end @@ -7082,15 +8739,16 @@ function ImGui.UpdateKeyRoutingTable(rt) old_routing_idx = routing_entry.NextEntryIndex end + -- Rewrite linked-list rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] = (new_routing_start_idx <= rt.EntriesNext.Size and new_routing_start_idx or -1) for n = new_routing_start_idx, rt.EntriesNext.Size do rt.EntriesNext[n].NextEntryIndex = (n + 1 <= rt.EntriesNext.Size) and (n + 1) or -1 end end - rt.Entries:swap(rt.EntriesNext) + rt.Entries:swap(rt.EntriesNext) -- Swap new and old indexes end --- owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope() +-- owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope(). --- @param owner_id ImGuiID local function GetRoutingIdFromOwnerId(owner_id) local g = GImGui @@ -7100,6 +8758,12 @@ end --- @param key_chord ImGuiKeyChord --- @return ImGuiKeyRoutingData function ImGui.GetShortcutRoutingData(key_chord) + -- Majority of shortcuts will be Key + any number of Mods + -- We accept _Single_ mod with ImGuiKey.None. + -- - Shortcut(ImGuiKey.S | ImGuiMod_Ctrl) -- Legal + -- - Shortcut(ImGuiKey.S | ImGuiMod_Ctrl | ImGuiMod_Shift) -- Legal + -- - Shortcut(ImGuiMod_Ctrl) -- Legal + -- - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift) -- Not legal local g = GImGui local rt = g.KeysRoutingTable local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) @@ -7109,6 +8773,8 @@ function ImGui.GetShortcutRoutingData(key_chord) end IM_ASSERT(ImGui.IsNamedKey(key)) + -- Get (in the majority of case, the linked list will have one element so this should be 2 reads. + -- Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame). local routing_data local idx = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] while idx ~= -1 do @@ -7120,32 +8786,51 @@ function ImGui.GetShortcutRoutingData(key_chord) idx = routing_data.NextEntryIndex end + -- Add to linked-list local routing_data_idx = rt.Entries.Size + 1 rt.Entries:push_back(ImGuiKeyRoutingData()) routing_data = rt.Entries[routing_data_idx] routing_data.Mods = mods - routing_data.NextEntryIndex = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] + routing_data.NextEntryIndex = rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] -- Setup linked list rt.Index[key - ImGuiKey.NamedKey_BEGIN + 1] = routing_data_idx return routing_data end +-- Current score encoding +-- - 0: Never route +-- - 1: ImGuiInputFlags.RouteGlobal (lower priority) +-- - 100..199: ImGuiInputFlags.RouteFocused (if window in focus-stack) +-- 200: ImGuiInputFlags.RouteGlobal | ImGuiInputFlags.RouteOverFocused +-- 300: ImGuiInputFlags.RouteActive or ImGuiInputFlags.RouteFocused (if item active) +-- 400: ImGuiInputFlags.RouteGlobal | ImGuiInputFlags.RouteOverActive +-- - 500..599: ImGuiInputFlags.RouteFocused | ImGuiInputFlags.RouteOverActive (if window in focus-stack) (higher priority) +-- 'flags' should include an explicit routing policy --- @param focus_scope_id ImGuiID --- @param owner_id ImGuiID --- @param flags ImGuiInputFlags local function CalcRoutingScore(focus_scope_id, owner_id, flags) local g = GImGui if bit32.band(flags, ImGuiInputFlags.RouteFocused) ~= 0 then + -- ActiveID gets high priority + -- (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it) if owner_id ~= 0 and g.ActiveId == owner_id then return 300 end + -- Score based on distance to focused window (lower is better) + -- Assuming both windows are submitting a routing request, + -- - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match) + -- - When Window/ChildB is focused -> Window scores 4, Window/ChildB scores 3 (best) + -- Assuming only WindowA is submitting a routing request, + -- - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score. + -- This essentially follow the window.ParentWindowForFocusRoute chain. if focus_scope_id == 0 then return 0 end for index_in_focus_path = 1, g.NavFocusRoute.Size do if g.NavFocusRoute.Data[index_in_focus_path].ID == focus_scope_id then - if bit32.band(flags, ImGuiInputFlags.RouteOverActive) ~= 0 then + if bit32.band(flags, ImGuiInputFlags.RouteOverActive) ~= 0 then -- && g.ActiveId != 0 && g.ActiveId != owner_id) return 599 - (index_in_focus_path - 1) else return 199 - (index_in_focus_path - 1) @@ -7174,16 +8859,22 @@ local function CalcRoutingScore(focus_scope_id, owner_id, flags) return 0 end +-- - We need this to filter some Shortcut() routes when an item e.g. an InputText() is active +-- e.g. ImGuiKey.G won't be considered a shortcut when item is active, but ImGuiMod|ImGuiKey.G can be. +-- - This is also used by UpdateInputEvents() to avoid trickling in the most common case of e.g. pressing ImGuiKey.G also emitting a G character. --- @param key_chord ImGuiKeyChord local function IsKeyChordPotentiallyCharInput(key_chord) + -- Mimic 'ignore_char_inputs' logic in InputText() local g = GImGui + -- When the right mods are pressed it cannot be a char input so we won't filter the shortcut out. local mods = bit32.band(key_chord, ImGuiMod_Mask_) local ignore_char_inputs = ((bit32.band(mods, ImGuiMod_Ctrl) ~= 0) and (bit32.band(mods, ImGuiMod_Alt) == 0)) or (g.IO.ConfigMacOSXBehaviors and (bit32.band(mods, ImGuiMod_Ctrl) ~= 0)) if ignore_char_inputs then return false end + -- Return true for A-Z, 0-9 and other keys associated to char inputs. Other keys such as F1-F12 won't be filtered. local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if key == ImGuiKey.None then return false @@ -7191,6 +8882,11 @@ local function IsKeyChordPotentiallyCharInput(key_chord) return g.KeysMayBeCharInput:TestBit(key + 1) -- TestBit requires 1-based index end +-- Request a desired route for an input chord (key + mods). +-- Return true if the route is available this frame. +-- - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state. +-- (Conceptually this does a "Submit for next frame" + "Test for current frame". +-- As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.) --- @param key_chord ImGuiKeyChord --- @param flags ImGuiInputFlags --- @param owner_id ImGuiID @@ -7210,8 +8906,10 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiInputFlags.RouteGlobal, ImGuiInputFlags.RouteFocused)) ~= 0) end + -- Add ImGuiMod_XXXX when a corresponding ImGuiKey.LeftXXX/ImGuiKey.RightXXX is specified. key_chord = ImGui.FixupKeyChord(key_chord) + -- [DEBUG] Debug break requested by user if g.DebugBreakInShortcutRouting == key_chord then -- IM_DEBUG_BREAK() end @@ -7222,21 +8920,29 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) end end + -- Note how ImGuiInputFlags.RouteAlways won't set routing and thus won't set owner. May want to rework this? if bit32.band(flags, ImGuiInputFlags.RouteAlways) ~= 0 then -- IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> always, no register", ImGui.GetKeyChordName(key_chord), flags, owner_id) return true end + -- Specific culling when there's an active item. if g.ActiveId ~= 0 and g.ActiveId ~= owner_id then if bit32.band(flags, ImGuiInputFlags.RouteActive) ~= 0 then return false end + -- Cull shortcuts with no modifiers when it could generate a character. + -- e.g. Shortcut(ImGuiKey.G) also generates 'g' character, should not trigger when InputText() is active. + -- but Shortcut(Ctrl+G) should generally trigger when InputText() is active. + -- TL;DR: lettered shortcut with no mods or with only Alt mod will not trigger while an item reading text input is active. + -- (We cannot filter based on io.InputQueueCharacters[] contents because of trickling and key<>chars submission order are undefined) if g.IO.WantTextInput and IsKeyChordPotentiallyCharInput(key_chord) then -- IMGUI_DEBUG_LOG_INPUTROUTING("SetShortcutRouting(%s, flags=%04X, owner_id=0x%08X) -> filtered as potential char input", ImGui.GetKeyChordName(key_chord), flags, owner_id) return false end + -- ActiveIdUsingAllKeyboardKeys trumps all for ActiveId if bit32.band(flags, ImGuiInputFlags.RouteOverActive) == 0 and g.ActiveIdUsingAllKeyboardKeys then local key = bit32.band(key_chord, bit32.bnot(ImGuiMod_Mask_)) if key == ImGuiKey.None then @@ -7248,9 +8954,10 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) end end + -- Where do we evaluate route for? local focus_scope_id = g.CurrentFocusScopeId if bit32.band(flags, ImGuiInputFlags.RouteFromRootWindow) ~= 0 then - focus_scope_id = g.CurrentWindow.RootWindow.ID + focus_scope_id = g.CurrentWindow.RootWindow.ID -- See PushFocusScope() call in Begin() end local score = CalcRoutingScore(focus_scope_id, owner_id, flags) @@ -7259,18 +8966,23 @@ function ImGui.SetShortcutRouting(key_chord, flags, owner_id) return false end + -- Submit routing for NEXT frame (assuming score is sufficient) + -- FIXME: Could expose a way to use a "serve last" policy for same score resolution (using >= instead of >). local routing_data = ImGui.GetShortcutRoutingData(key_chord) + -- const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score >= routing_data->RoutingNextScore) : (score > routing_data->RoutingNextScore); if score > routing_data.RoutingNextScore then routing_data.RoutingNext = owner_id routing_data.RoutingNextScore = score end + -- Return routing state for CURRENT frame if routing_data.RoutingCurr == owner_id then -- IMGUI_DEBUG_LOG_INPUTROUTING("--> granting current route") end return routing_data.RoutingCurr == owner_id end +-- We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position. --- @param mouse_pos? ImVec2 function ImGui.IsMousePosValid(mouse_pos) local MOUSE_INVALID = -256000.0 @@ -7279,6 +8991,7 @@ function ImGui.IsMousePosValid(mouse_pos) return p.x >= MOUSE_INVALID and p.y >= MOUSE_INVALID end +-- [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid. --- @return bool function ImGui.IsAnyMouseDown() local g = GImGui @@ -7297,7 +9010,7 @@ function ImGui.IsMouseDown(button, owner_id) local g = GImGui IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown) - return g.IO.MouseDown[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) + return g.IO.MouseDown[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) -- Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array. end --- @param button ImGuiMouseButton @@ -7318,14 +9031,14 @@ function ImGui.IsMouseClickedEx(button, flags, owner_id) local g = GImGui IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown) - if not g.IO.MouseDown[button] then + if not g.IO.MouseDown[button] then -- In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership) return false end local t = g.IO.MouseDownDuration[button] if t < 0.0 then return false end - IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedByIsMouseClicked)) == 0) + IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedByIsMouseClicked)) == 0) -- Passing flags not supported by this function! -- FIXME: Could support RepeatRate and RepeatUntil flags here. local is_repeat = (bit32.band(flags, ImGuiInputFlags.Repeat) ~= 0) local pressed = (t == 0.0) or (is_repeat and t > g.IO.KeyRepeatDelay and ImGui.CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0) @@ -7348,10 +9061,13 @@ function ImGui.IsMouseReleased(button, owner_id) local g = GImGui IM_ASSERT(button >= 0 and button < 3) -- IM_COUNTOF(g.IO.MouseDown) - return g.IO.MouseReleased[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) + return g.IO.MouseReleased[button] and ImGui.TestKeyOwner(ImGui.MouseButtonToKey(button), owner_id) -- Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id) end +-- Prefer higher-level helper GetItemClickedCountWithSingleClickDelay() -- 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. --- @param button ImGuiMouseButton --- @param delay? float function ImGui.IsMouseReleasedWithDelay(button, delay) @@ -7403,6 +9119,22 @@ local function LastItemOverlayButtonForNullId(mouse_button) return id end +-- [BETA] Building block for disambiguation between single-click and double-click. +-- - Returns 1 on single-click but delayed by io.MouseSingleClickDelay (which is always > io.MouseDoubleClickTime) after mouse release. +-- - Returns 2+ on double-click and subsequent repeated clicks. +-- In order use that to replicate Windows Explorer's "click on label to rename after a delay", +-- When the function returns 1 for a delayed single click, you can add with further tests: +-- - If you want to test that the mouse position AT THE TIME of the click (before the delay): you can use the 'io.MouseClickedPos[mouse_button]' position. +-- - If you want to test that the mouse position is still over the item at the end of delay: you can use '&& IsItemHovered()'. +-- - If you want to test that the item was selected or the sole selection AT THE TIME of the click (before the delay): you can test for 'g.LastActiveIdWasSelected' or 'g.LastActiveIdWasSoleSelected'. +-- e.g. +-- local click_count = ImGui.GetItemClickedCountWithSingleClickDelay(mouse_button) +-- if click_count == 1 and ImGui.GetCurrentContext().LastActiveIdWasSoleSelected then +-- StartRename() +-- end +-- if click_count == 2 then +-- Launch() +-- end --- @param mouse_button? ImGuiMouseButton --- @param delay? float --- @return int @@ -7446,6 +9178,8 @@ function ImGui.GetMousePosOnOpeningCurrentPopup() end -- Return the delta from the initial clicking position while the mouse button is clicked or was just released. +-- This is locked and return 0.0f until the mouse moves past a distance threshold at least once. +-- NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window. --- @param button? ImGuiMouseButton --- @param lock_threshold? float --- @return ImVec2 @@ -7480,11 +9214,18 @@ do local key_changed_mask = ImBitArray(ImGuiKey.NamedKey_COUNT) +-- Process input queue +-- We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'. +-- - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost) +-- - trickle_fast_inputs = true : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87) --- @param trickle_fast_inputs bool function ImGui.UpdateInputEvents(trickle_fast_inputs) local g = GImGui local io = g.IO + -- Only trickle chars<>key when working with InputText() + -- FIXME: InputText() could parse event trail? + -- FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters) local trickle_interleaved_nonchar_keys_and_text = trickle_fast_inputs and g.WantTextInputNextFrame == 1 local mouse_moved = false @@ -7505,7 +9246,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) if g.IO.WantSetMousePos then break end - + -- Trickling Rule: Stop processing queued events if we already handled a mouse button change if trickle_fast_inputs and (mouse_button_changed ~= 0 or mouse_wheeled or key_changed or text_inputted) then stop_3231 = true; break end @@ -7514,12 +9255,13 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) io.MouseSource = e.MousePos.MouseSource mouse_moved = true elseif e.Type == ImGuiInputEventType.MouseButton then + -- Trickling Rule: Stop processing queued events if we got multiple action on the same button local button = e.MouseButton.Button IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT) if trickle_fast_inputs and ((bit32.band(mouse_button_changed, bit32.lshift(1, button)) ~= 0) or mouse_wheeled) then stop_3231 = true; break end - if trickle_fast_inputs and e.MouseButton.MouseSource == ImGuiMouseSource.TouchScreen and mouse_moved then + if trickle_fast_inputs and e.MouseButton.MouseSource == ImGuiMouseSource.TouchScreen and mouse_moved then -- #2702: TouchScreen have no initial hover. stop_3231 = true; break end @@ -7527,6 +9269,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) io.MouseSource = e.MouseButton.MouseSource mouse_button_changed = bit32.bor(mouse_button_changed, bit32.lshift(1, button)) elseif e.Type == ImGuiInputEventType.MouseWheel then + -- Trickling Rule: Stop processing queued events if we got multiple action on the event if trickle_fast_inputs and (mouse_moved or mouse_button_changed ~= 0) then stop_3231 = true; break end @@ -7558,7 +9301,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) stop_3231 = true; break end - if key_data.Down ~= e.Key.Down then + if key_data.Down ~= e.Key.Down then -- 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 + 1) if trickle_interleaved_nonchar_keys_and_text and not key_is_potentially_for_char_input then @@ -7572,7 +9315,7 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoKeyboard) ~= 0 then break end - + -- Trickling Rule: Stop processing queued events if keys/mouse have been interacted with if trickle_fast_inputs and (mouse_button_changed ~= 0 or mouse_moved or mouse_wheeled) then stop_3231 = true; break end @@ -7585,6 +9328,8 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) text_inputted = true end elseif e.Type == ImGuiInputEventType.Focus then + -- We intentionally overwrite this and process in NewFrame(), in order to give a chance + -- to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame. local focus_lost = not e.AppFocused.Focused io.AppFocusLost = focus_lost else @@ -7597,6 +9342,9 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) event_n = event_n + 1 end + -- Remaining events will be processed on the next frame + -- FIXME-MULTITHREADING: io.AddKeyEvent() etc. calls are mostly thread-safe apart from the fact they push to this + -- queue which may be resized here. Could potentially rework this to narrow down the section needing a mutex? (#5772) if event_n == g.InputEventsQueue.Size + 1 then g.InputEventsQueue:resize(0) else @@ -7605,6 +9353,10 @@ function ImGui.UpdateInputEvents(trickle_fast_inputs) end end + -- Clear buttons state when focus is lost + -- - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle. + -- - we clear in EndFrame() and not now in order allow application/user code polling this flag + -- (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event). if g.IO.AppFocusLost then g.IO:ClearInputKeys() g.IO:ClearInputMouse() @@ -7613,6 +9365,12 @@ end end +-- _LockXXX flags are useful to lock keys away from code which is not input-owner aware. +-- When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone. +-- - SetKeyOwner(..., None) : clears owner +-- - SetKeyOwner(..., Any, !Lock) : illegal (assert) +-- - SetKeyOwner(..., Any or None, Lock) : set lock +-- Ownership is automatically released on the frame after a release, see code in UpdateKeyboardInputs(). --- @param key ImGuiKey --- @param owner_id ImGuiID --- @param flags? ImGuiInputFlags @@ -7622,11 +9380,14 @@ function ImGui.SetKeyOwner(key, owner_id, flags) local g = GImGui --- @cast g ImGuiContext IM_ASSERT(ImGui.IsNamedKeyOrMod(key) and (owner_id ~= ImGuiKeyOwner_Any or (bit32.band(flags, bit32.bor(ImGuiInputFlags.LockThisFrame, ImGuiInputFlags.LockUntilRelease)) ~= 0)), "Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)") IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetKeyOwner)) == 0, "Passing flags not supported by this function!") + -- IMGUI_DEBUG_LOG("SetKeyOwner(%s, owner_id=0x%08X, flags=%08X)\n", GetKeyName(key), owner_id, flags) local owner_data = ImGui.GetKeyOwnerData(g, key) owner_data.OwnerCurr = owner_id owner_data.OwnerNext = owner_id + -- We cannot lock by default as it would likely break lots of legacy code. + -- In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data.Down test) owner_data.LockUntilRelease = (bit32.band(flags, ImGuiInputFlags.LockUntilRelease) ~= 0) owner_data.LockThisFrame = (bit32.band(flags, ImGuiInputFlags.LockThisFrame) ~= 0) or owner_data.LockUntilRelease end @@ -7655,6 +9416,12 @@ function ImGui.SetKeyOwnersForKeyChord(key_chord, owner_id, flags) end end +-- This is more or less equivalent to a fancier version of: +-- if (IsItemHovered() || IsItemActive()) +-- SetKeyOwner(key, GetItemID()); +-- Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times. +-- More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition. +-- Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority. --- @param key ImGuiKey --- @param flags? ImGuiInputFlags function ImGui.SetItemKeyOwner(key, flags) @@ -7669,7 +9436,7 @@ function ImGui.SetItemKeyOwner(key, flags) flags = bit32.bor(flags, ImGuiInputFlags.CondDefault_) end if (g.HoveredId == id and bit32.band(flags, ImGuiInputFlags.CondHovered) ~= 0) or (g.ActiveId == id and bit32.band(flags, ImGuiInputFlags.CondActive) ~= 0) then - IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetItemKeyOwner)) == 0) + IM_ASSERT(bit32.band(flags, bit32.bnot(ImGuiInputFlags.SupportedBySetItemKeyOwner)) == 0) -- Passing flags not supported by this function! if not ImGui.TestKeyOwner(key, id) then return false end @@ -7679,6 +9446,7 @@ function ImGui.SetItemKeyOwner(key, flags) return false end +-- This is equivalent to comparing KeyMods + doing a IsKeyPressed() --- @param key_chord ImGuiKeyChord --- @param flags ImGuiInputFlags --- @param owner_id ImGuiID @@ -7717,7 +9485,7 @@ end --- @param owner_id ImGuiID function ImGui.Shortcut(key_chord, flags, owner_id) local g = GImGui - -- IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)", ImGui.GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id) + -- IMGUI_DEBUG_LOG("Shortcut(%s, flags=%X, owner_id=0x%08X)\n", ImGui.GetKeyChordName(key_chord, g.TempBuffer.Data, g.TempBuffer.Size), flags, owner_id) -- When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any. if bit32.band(flags, ImGuiInputFlags.RouteTypeMask_) == 0 then @@ -7765,6 +9533,9 @@ end --- @param window ImGuiWindow --- @nodiscard local function CalcWindowMinSize(window) + -- We give windows non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) + -- FIXME: Essentially we want to restrict manual resizing to WindowMinSize+Decoration, and allow api resizing to be smaller. + -- Perhaps should tend further a neater test for this. local g = GImGui local size_min = ImVec2() @@ -7795,6 +9566,7 @@ local function CalcWindowMinSize(window) end end + -- Reduce artifacts with very small windows local window_for_height = window size_min.y = ImMax(size_min.y, window_for_height.TitleBarHeight + window_for_height.MenuBarHeight + ImMax(0, g.Style.WindowRounding - 1)) @@ -7812,6 +9584,7 @@ local function CalcWindowSizeAfterConstraint(window, size_desired) ImVec2_Copy(new_size, size_desired) if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) ~= 0 then + -- See comments in SetNextWindowSizeConstraints() for details about setting size_min an size_max. local cr = ImRect() ImRect_Copy(cr, g.NextWindowData.SizeConstraintRect) @@ -7831,6 +9604,7 @@ local function CalcWindowSizeAfterConstraint(window, size_desired) new_size.y = IM_TRUNC(new_size.y) end + -- Minimum size local size_min = CalcWindowMinSize(window) return ImMax(new_size, size_min) end @@ -7873,6 +9647,8 @@ local function CalcWindowAutoFitSize(window, size_contents, axis_mask) size_desired.x = (bit32.band(axis_mask, 1) ~= 0) and (size_contents.x + size_pad.x + decoration_w_without_scrollbars) or window.Size.x size_desired.y = (bit32.band(axis_mask, 2) ~= 0) and (size_contents.y + size_pad.y + decoration_h_without_scrollbars) or window.Size.y + -- Determine maximum window size + -- Child windows are laid within their parent (unless they are also popups/menus) and thus have no restriction local size_max = ImVec2(FLT_MAX, FLT_MAX) if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0 or bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then if not window.ViewportOwned then @@ -7885,13 +9661,16 @@ local function CalcWindowAutoFitSize(window, size_contents, axis_mask) end if bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0 then + -- Tooltip always resize (up to maximum size) return ImMin(size_desired, size_max) else local size_min = CalcWindowMinSize(window) local size_auto_fit = ImClamp(size_desired, ImMin(size_min, size_max), size_max) + -- When the window cannot fit all contents (either because of constraints, either because screen is too small), + -- we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. local size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit) - local size_contents_for_scrollbar_x = (bit32.band(axis_mask, 1) ~= 0) and size_contents.x or window.ContentSize.x + local size_contents_for_scrollbar_x = (bit32.band(axis_mask, 1) ~= 0) and size_contents.x or window.ContentSize.x -- See #9352. In theory this should use same logic as `window.ScrollbarY = ...` codepath in Begin(). Needs some plumbling. local size_contents_for_scrollbar_y = (bit32.band(axis_mask, 2) ~= 0) and size_contents.y or window.ContentSize.y local will_have_scrollbar_x = (size_auto_fit_after_constraint.x < size_contents_for_scrollbar_x + size_pad.x + decoration_w_without_scrollbars and bit32.band(window.Flags, ImGuiWindowFlags.NoScrollbar) == 0 and bit32.band(window.Flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0) or bit32.band(window.Flags, ImGuiWindowFlags.AlwaysHorizontalScrollbar) ~= 0 local will_have_scrollbar_y = (size_auto_fit_after_constraint.y < size_contents_for_scrollbar_y + size_pad.y + decoration_h_without_scrollbars and bit32.band(window.Flags, ImGuiWindowFlags.NoScrollbar) == 0) or bit32.band(window.Flags, ImGuiWindowFlags.AlwaysVerticalScrollbar) ~= 0 @@ -7937,7 +9716,7 @@ local function CalcResizePosSizeFromAnyCorner(window, corner_target_arg, corner_ local corner_target = ImVec2() ImVec2_Copy(corner_target, corner_target_arg) - if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then + if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then -- Clamp resizing of childs within parent local parent_window = window.ParentWindow local parent_flags = parent_window.Flags @@ -7952,8 +9731,8 @@ local function CalcResizePosSizeFromAnyCorner(window, corner_target_arg, corner_ corner_target.y = ImClamp(corner_target.y, limit_rect.Min.y, limit_rect.Max.y) end end - local pos_min = ImLerp(corner_target, window.Pos, corner_norm) - local pos_max = ImLerp(window.Pos + window.Size, corner_target, corner_norm) + local pos_min = ImLerp(corner_target, window.Pos, corner_norm) -- Expected window upper-left + local pos_max = ImLerp(window.Pos + window.Size, corner_target, corner_norm) -- Expected window lower-right local size_expected = pos_max - pos_min local size_constrained = CalcWindowSizeAfterConstraint(window, size_expected) @@ -7968,6 +9747,9 @@ local function CalcResizePosSizeFromAnyCorner(window, corner_target_arg, corner_ return out_pos, size_constrained end +-- Handle resize for: Resize Grips, Borders, Gamepad +-- Return true when using auto-fit (double-click on resize grip) +-- Returns (ret_auto_fit_mask, border_hovered, border_held) --- @param window ImGuiWindow --- @param resize_grip_count int --- @param resize_grip_col table @@ -7983,7 +9765,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c if (bit32.band(flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0 and bit32.band(window.ChildFlags, bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY)) == 0) then return 0, -1, -1 end - if window.WasActive == false then + if window.WasActive == false then -- Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window. return 0, -1, -1 end @@ -8005,7 +9787,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c -- This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it. -- - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow. -- - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold). - -- We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. + -- We only clip interaction so we overwrite window.ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup. local clip_with_viewport_rect = bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasMouseHoveredViewport) == 0 or g.IO.MouseHoveredViewport ~= window.ViewportId or bit32.band(window.Viewport.Flags, ImGuiViewportFlags.NoDecoration) == 0 if (clip_with_viewport_rect) then ImRect_Copy(window.ClipRect, window.Viewport:GetMainRect()) @@ -8026,35 +9808,41 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c local corner = ImVec2(window.Pos.x + corner_pos.x * window.Size.x, window.Pos.y + corner_pos.y * window.Size.y) + -- Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window local resize_rect = ImRect(corner - inner_dir * grip_hover_outer_size, corner + inner_dir * grip_hover_inner_size) if resize_rect.Min.x > resize_rect.Max.x then resize_rect.Min.x, resize_rect.Max.x = resize_rect.Max.x, resize_rect.Min.x end if resize_rect.Min.y > resize_rect.Max.y then resize_rect.Min.y, resize_rect.Max.y = resize_rect.Max.y, resize_rect.Min.y end - local resize_grip_id = window:GetID(resize_grip_n) + local resize_grip_id = window:GetID(resize_grip_n) -- == GetWindowResizeCornerID() ImGui.ItemAdd(resize_rect, resize_grip_id, nil, ImGuiItemFlags.NoNav) local _, hovered, held = ImGui.ButtonBehavior(resize_rect, resize_grip_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus)) + -- GetForegroundDrawList(window):AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)) if hovered or held then ImGui.SetMouseCursor((bit32.band(resize_grip_n, 1) ~= 0) and ImGuiMouseCursor.ResizeNESW or ImGuiMouseCursor.ResizeNWSE) end if held and g.IO.MouseDoubleClicked[0] then + -- Auto-fit when double-clicking local size_auto_fit = CalcWindowAutoFitSize(window, window.ContentSizeIdeal, -1) size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit) - ret_auto_fit_mask = 0x03 + ret_auto_fit_mask = 0x03 -- Both axes ImGui.ClearActiveID() elseif held then + -- Resize from any of the four corners + -- We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position local clamp_min = ImVec2((corner_pos.x == 1.0) and clamp_rect.Min.x or -FLT_MAX, (corner_pos.y == 1.0) and clamp_rect.Min.y or -FLT_MAX) local clamp_max = ImVec2((corner_pos.x == 0.0) and clamp_rect.Max.x or FLT_MAX, (corner_pos.y == 0.0) and clamp_rect.Max.y or FLT_MAX) - local corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN) + local corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN) -- Corner of the window corresponding to our corner grip corner_target = ImClamp(corner_target, clamp_min, clamp_max) pos_target, size_target = CalcResizePosSizeFromAnyCorner(window, corner_target, corner_pos) end + -- Only lower-left grip is visible before hovering/activating local resize_grip_visible = held or hovered or (resize_grip_n == 0 and bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0) if resize_grip_visible then local color @@ -8095,9 +9883,10 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c end local border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, g.WindowsBorderHoverPadding) - local border_id = window:GetID(border_n + 4) + local border_id = window:GetID(border_n + 4) -- == GetWindowResizeBorderID() ImGui.ItemAdd(border_rect, border_id, nil, ImGuiItemFlags.NoNav) local _, hovered, held = ImGui.ButtonBehavior(border_rect, border_id, bit32.bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.NoNavFocus)) + -- GetForegroundDrawList(window):AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)) if hovered and g.HoveredIdTimer <= WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER then hovered = false @@ -8117,6 +9906,9 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c end ImGui.ClearActiveID() elseif held then + -- Switch to relative resizing mode when border geometry moved (e.g. resizing a child altering parent scroll), in order to avoid resizing feedback loop. + -- Currently only using relative mode on resizable child windows, as the problem to solve is more likely noticeable for them, but could apply for all windows eventually. + -- FIXME: May want to generalize this idiom at lower-level, so more widgets can use it! local just_scrolled_manually_while_resizing = (g.WheelingWindow ~= nil and g.WheelingWindowScrolledFrame == g.FrameCount and ImGui.IsWindowChildOf(window, g.WheelingWindow, false, true)) if g.ActiveIdIsJustActivated or just_scrolled_manually_while_resizing then g.WindowResizeBorderExpectedRect = border_rect @@ -8131,7 +9923,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c local border_target_rel_mode_for_axis local border_target_abs_mode_for_axis border_target_rel_mode_for_axis = border_curr[axis] + g.IO.MouseDelta[axis] - border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding -- Match ButtonBehavior() padding above + border_target_abs_mode_for_axis = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + g.WindowsBorderHoverPadding -- Match ButtonBehavior() padding above. -- Use absolute mode position local border_target = ImVec2() @@ -8141,12 +9933,14 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c -- Use relative mode target for child window, ignore resize when moving back toward the ideal absolute position. local ignore_resize = false if g.WindowResizeRelativeMode then + -- GetForegroundDrawList():AddText(GetMainViewport().WorkPos, IM_COL32_WHITE, "Relative Mode") border_target[axis] = border_target_rel_mode_for_axis if g.IO.MouseDelta[axis] == 0.0 or ((g.IO.MouseDelta[axis] > 0.0) == (border_target_rel_mode_for_axis > border_target_abs_mode_for_axis)) then ignore_resize = true end end + -- Clamp, apply local clamp_min = ImVec2((border_n == ImGuiDir.Right) and clamp_rect.Min.x or -FLT_MAX, (border_n == ImGuiDir.Down or (border_n == ImGuiDir.Up and window_move_from_title_bar)) and clamp_rect.Min.y or -FLT_MAX) local clamp_max = ImVec2((border_n == ImGuiDir.Left) and clamp_rect.Max.x or FLT_MAX, (border_n == ImGuiDir.Up) and clamp_rect.Max.y or FLT_MAX) border_target = ImClamp(border_target, clamp_min, clamp_max) @@ -8166,8 +9960,10 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c end ImGui.PopID() + -- Restore nav layer window.DC.NavLayerCurrent = ImGuiNavLayer.Main + -- Apply back modified position/size to window if size_target.x ~= FLT_MAX and (window.Size.x ~= size_target.x or window.SizeFull.x ~= size_target.x) then window.Size.x = size_target.x window.SizeFull.x = size_target.x @@ -8186,6 +9982,7 @@ local function UpdateWindowManualResize(window, resize_grip_count, resize_grip_c window.Pos.y = ImFloor(pos_target.y) end + -- Recalculate next expected border expected coordinates if border_held ~= -1 then g.WindowResizeBorderExpectedRect = GetResizeBorderRect(window, border_held, grip_hover_inner_size, g.WindowsBorderHoverPadding) end @@ -8204,14 +10001,26 @@ function ImGui.CalcWrapWidthForPos(pos, wrap_pos_x) local g = GImGui local window = g.CurrentWindow if wrap_pos_x == 0.0 then + -- We could decide to setup a default wrapping max point for auto-resizing windows, + -- or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function? + -- if (window.Hidden and (window.Flags & ImGuiWindowFlags.AlwaysAutoResize)) + -- wrap_pos_x = ImMax(window.WorkRect.Min.x + g.FontSize * 10.0, window.WorkRect.Max.x) + -- else wrap_pos_x = window.WorkRect.Max.x elseif wrap_pos_x > 0.0 then - wrap_pos_x = wrap_pos_x + window.Pos.x - window.Scroll.x + wrap_pos_x = wrap_pos_x + window.Pos.x - window.Scroll.x -- wrap_pos_x is provided is window local space end return ImMax(wrap_pos_x - pos.x, 1.0) end +------------------------------------------------------------------------------- +-- [SECTION] RENDER HELPERS +-- Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change, +-- we need a nicer separation between low-level functions and high-level functions relying on the ImGui context. +-- Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context. +------------------------------------------------------------------------------- + --- @param text ImString --- @param text_end int? --- @return int # Exclusive upper bound @@ -8229,6 +10038,8 @@ function ImGui.FindRenderedTextEnd(text, text_end) return text_display_end end +-- Internal ImGui functions to render text +-- RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() --- @param pos ImVec2 --- @param text string --- @param text_begin int? @@ -8248,7 +10059,7 @@ function ImGui.RenderText(pos, text, text_begin, text_end, hide_text_after_hash) text_display_end = ImGui.FindRenderedTextEnd(text, text_end) else if text_end == nil then - text_end = #text + 1 + text_end = #text + 1 -- FIXME-OPT (not reached by our internal calls) end text_display_end = text_end end @@ -8270,7 +10081,7 @@ function ImGui.RenderTextWrapped(pos, text, text_end, wrap_width) local window = g.CurrentWindow if text_end == nil then - text_end = #text + 1 + text_end = #text + 1 -- FIXME-OPT (not reached by our internal calls) end if text ~= "" then @@ -8278,6 +10089,12 @@ function ImGui.RenderTextWrapped(pos, text, text_end, wrap_width) end 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, 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. +-- DOES NOT CALL LogRenderedText(), unlike RenderTextClipped!!! --- @param draw_list ImDrawList --- @param pos_min ImVec2 --- @param pos_max ImVec2 @@ -8291,6 +10108,7 @@ end function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin, text_display_end, text_size_if_known, align, clip_rect) if not align then align = ImVec2(0, 0) end + -- Perform CPU side clipping for single clipped element to avoid using scissor state local pos = ImVec2() ImVec2_Copy(pos, pos_min) @@ -8299,13 +10117,15 @@ function ImGui.RenderTextClippedEx(draw_list, pos_min, pos_max, text, text_begin local clip_min = clip_rect and clip_rect.Min or pos_min local clip_max = clip_rect and clip_rect.Max or pos_max local need_clipping = (pos.x + text_size.x >= clip_max.x) or (pos.y + text_size.y >= clip_max.y) - if (clip_rect) then + if (clip_rect) then -- If we had no explicit clipping rectangle then pos==clip_min need_clipping = need_clipping or ((pos.x < clip_min.x) or (pos.y < clip_min.y)) end + -- Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. if (align.x > 0.0) then pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x) end if (align.y > 0.0) then pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y) end + -- Render local g = GImGui if (need_clipping) then local fine_clip_rect = ImVec4(clip_min.x, clip_min.y, clip_max.x, clip_max.y) @@ -8325,6 +10145,7 @@ end function ImGui.RenderTextClipped(pos_min, pos_max, text, text_end, text_size_if_known, align, clip_rect) if not align then align = ImVec2(0, 0) end + -- Hide anything after a '##' string local text_display_end = ImGui.FindRenderedTextEnd(text, text_end) local text_len = text_display_end - 1 @@ -8359,6 +10180,8 @@ function ImGui.RenderNavCursor(bb, id, flags, rounding) return end + -- We don't early out on 'window.Flags & ImGuiWindowFlags.NoNavInputs' because it would be inconsistent with + -- other code directly checking NavCursorVisible. Instead we aim for NavCursorVisible to always be false. local window = g.CurrentWindow if window.DC.NavHideHighlightOneFrame then return @@ -8371,7 +10194,7 @@ function ImGui.RenderNavCursor(bb, id, flags, rounding) local display_rect = ImRect() ImRect_Copy(display_rect, bb) display_rect:ClipWith(window.ClipRect) - local scale_factor = ImGui.GetScale() + local scale_factor = ImGui.GetScale() -- FIXME-DPI local thickness = ImTrunc(ImMax(2.0, 1.5 * scale_factor)) if bit32.band(flags, ImGuiNavRenderCursorFlags.Compact) ~= 0 then window.DrawList:AddRect(display_rect.Min, display_rect.Max, ImGui.GetColorU32(ImGuiCol.NavCursor), rounding, thickness) @@ -8404,13 +10227,14 @@ local uv_fill = {ImVec2(), ImVec2()} --- @param col_shadow ImU32 function ImGui.RenderMouseCursor(base_pos, base_scale, mouse_cursor, col_fill, col_border, col_shadow) local g = GImGui - if mouse_cursor <= ImGuiMouseCursor.None or mouse_cursor >= ImGuiMouseCursor.COUNT then -- We intentionally accept out of bound values + if mouse_cursor <= ImGuiMouseCursor.None or mouse_cursor >= ImGuiMouseCursor.COUNT then -- We intentionally accept out of bound values. mouse_cursor = ImGuiMouseCursor.Arrow end local font_atlas = g.DrawListSharedData.FontAtlas for _, viewport in g.Viewports:iter() do repeat + -- We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor. if not ImFontAtlasGetMouseCursorTexData(font_atlas, mouse_cursor, offset, size, uv_border, uv_fill) then break end @@ -8442,9 +10266,10 @@ end end ---- Another overly complex function until we reorganize everything into a nice all-in-one helper. ---- This is made more complex because we have dissociated the layout rectangle (pos_min .. pos_max) 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. +-- 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) 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. +-- (BREAKING) On 2025/04/16 we removed the 'float clip_max_x' parameters which was preceding 'float ellipsis_max' and was the same value for 99% of users. --- @param draw_list ImDrawList --- @param pos_min ImVec2 --- @param pos_max ImVec2 @@ -8467,8 +10292,8 @@ function ImGui.RenderTextEllipsis(draw_list, pos_min, pos_max, ellipsis_max_x, t text_size = ImGui.CalcTextSize(text, text_end_full, false, 0.0) end - -- 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)) + -- draw_list:AddLineV(pos_max.x, pos_min.y - 4, pos_max.y + 6, IM_COL32(0, 0, 255, 255)) + -- draw_list:AddLineV(ellipsis_max_x, pos_min.y - 2, 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 then @@ -8504,6 +10329,7 @@ function ImGui.RenderTextEllipsis(draw_list, pos_min, pos_max, ellipsis_max_x, t end end +-- Render a rectangle shaped with optional rounding and borders --- @param p_min ImVec2 --- @param p_max ImVec2 --- @param fill_col ImU32 @@ -8572,7 +10398,7 @@ local function RenderWindowOuterBorders(window) if border_size > 0.0 and (bit32.band(window.Flags, ImGuiWindowFlags.NoBackground) == 0) then window.DrawList:AddRect(window.Pos, window.Pos + window.Size, border_col, window.WindowRounding, window.WindowBorderSize, 0) elseif border_size > 0.0 then - if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 then + if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 then -- Similar code as 'resize_border_mask' computation in UpdateWindowManualResize() but we specifically only always draw explicit child resize border. RenderWindowOuterSingleBorder(window, 1, border_col, border_size) end if bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0 then @@ -8583,7 +10409,7 @@ local function RenderWindowOuterBorders(window) if window.ResizeBorderHovered ~= -1 or window.ResizeBorderHeld ~= -1 then local border_n = (window.ResizeBorderHeld ~= -1) and window.ResizeBorderHeld or window.ResizeBorderHovered local border_col_resizing = ImGui.GetColorU32((window.ResizeBorderHeld ~= -1) and ImGuiCol.SeparatorActive or ImGuiCol.SeparatorHovered) - RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0, window.WindowBorderSize)) + RenderWindowOuterSingleBorder(window, border_n, border_col_resizing, ImMax(2.0, window.WindowBorderSize)) -- Thicker than usual end if g.Style.FrameBorderSize > 0 and (bit32.band(window.Flags, ImGuiWindowFlags.NoTitleBar) == 0) and not window.DockIsActive then @@ -8592,6 +10418,8 @@ local function RenderWindowOuterBorders(window) end end +-- Draw background and borders +-- Draw and handle scrollbars --- @param window ImGuiWindow --- @param title_bar_rect ImRect --- @param title_bar_is_highlight bool @@ -8603,10 +10431,13 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high local style = g.Style local flags = window.Flags + -- 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. local window_rounding = window.WindowRounding local window_border_size = window.WindowBorderSize if window.Collapsed then + -- Title bar only local backup_border_size = style.FrameBorderSize g.Style.FrameBorderSize = window.WindowBorderSize @@ -8617,6 +10448,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high -- Window background if bit32.band(flags, ImGuiWindowFlags.NoBackground) == 0 then local bg_col = ImGui.GetColorU32(GetWindowBgColorIdx(window)) + -- Adjust alpha. For docking local override_alpha = false local alpha = 1.0 @@ -8650,6 +10482,8 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high if window.DockIsActive then window.DockNode.IsBgDrawnThisFrame = true end -- Title bar + -- (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag, + -- in order for their pos/size to be matching their undocking state.) if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and not window.DockIsActive then local title_bar_col = ImGui.GetColorU32(title_bar_is_highlight and ImGuiCol.TitleBgActive or ImGuiCol.TitleBg) window.DrawList:AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags.RoundCornersTop) @@ -8658,7 +10492,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high -- Menu bar if bit32.band(flags, ImGuiWindowFlags.MenuBar) ~= 0 then local menu_bar_rect = window:MenuBarRect() - menu_bar_rect:ClipWith(window:Rect()) + menu_bar_rect:ClipWith(window:Rect()) -- Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. window.DrawList:AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, ImGui.GetColorU32(ImGuiCol.MenuBarBg), (bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0) and window_rounding or 0.0, ImDrawFlags.RoundCornersTop) if style.FrameBorderSize > 0.0 and menu_bar_rect.Max.y < window.Pos.y + window.Size.y then window.DrawList:AddLineH(menu_bar_rect.Min.x + window_border_size * 0.5, menu_bar_rect.Max.x - window_border_size * 0.5, menu_bar_rect.Max.y, ImGui.GetColorU32(ImGuiCol.Border), style.FrameBorderSize) @@ -8678,12 +10512,15 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high if pressed then node.WantHiddenTabBarToggle = true elseif held and ImGui.IsMouseDragging(0) then - ImGui.StartMouseMovingWindowOrNode(window, node, true) + ImGui.StartMouseMovingWindowOrNode(window, node, true) -- Undock from tab-bar triangle = same as window/collapse menu button end + + -- FIXME-DOCK: Ideally we'd use ImGuiCol.TitleBgActive/ImGuiCol.TitleBg here, but neither is guaranteed to be visible enough at this sort of size.. local col = ImGui.GetColorU32(((held and hovered) or (node.IsFocused and not hovered)) and ImGuiCol.ButtonActive or (hovered and ImGuiCol.ButtonHovered or ImGuiCol.Button)) window.DrawList:AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0), p + ImVec2(0.0, unhide_sz_draw), col) end + -- Scrollbars if window.ScrollbarX then ImGui.Scrollbar(ImGuiAxis.X) end @@ -8691,7 +10528,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high ImGui.Scrollbar(ImGuiAxis.Y) end - -- Resize grip(s) + -- Render resize grips (after their input handling so we don't have a frame of latency) if handle_borders_and_resize_grips and (bit32.band(flags, ImGuiWindowFlags.NoResize) == 0) then for resize_grip_n = 1, #ImGuiResizeGripDef do repeat @@ -8712,6 +10549,7 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end end + -- Borders (for dock node host they will be rendered over after the tab bar) if handle_borders_and_resize_grips and not window.DockNodeAsHost then RenderWindowOuterBorders(window) end @@ -8721,6 +10559,9 @@ local function RenderWindowDecorations(window, title_bar_rect, title_bar_is_high end ImGui.RenderWindowOuterBorders = RenderWindowOuterBorders +-- When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead. +-- Render title text, collapse button, close button +-- Returns the updated 'open' value (nil when there is no close button) --- @param window ImGuiWindow --- @param title_bar_rect ImRect --- @param name string @@ -8734,10 +10575,14 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) local has_close_button = (open ~= nil) local has_collapse_button = bit32.band(flags, ImGuiWindowFlags.NoCollapse) == 0 and (style.WindowMenuButtonPosition ~= ImGuiDir.None) + -- Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer) + -- FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags.NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref? local item_flags_backup = g.CurrentItemFlags g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.NoNavDefaultFocus) window.DC.NavLayerCurrent = ImGuiNavLayer.Menu + -- Layout buttons + -- FIXME: Would be nice to generalize the subtleties expressed here into reusable code. local pad_l = g.Style.FramePadding.x local pad_r = g.Style.FramePadding.x local button_sz = g.FontSize @@ -8756,12 +10601,14 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) pad_l = pad_l + button_sz + style.ItemInnerSpacing.x end + -- Collapse button (submitting first so it gets priority when choosing a navigation init fallback) if has_collapse_button then if ImGui.CollapseButton(window:GetID("#COLLAPSE"), collapse_button_pos) then window.WantCollapseToggle = true -- Defer actual collapsing to next frame as we are too far in the Begin() function end end + -- Close button if has_close_button then local backup_item_flags = g.CurrentItemFlags g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.NoFocus) @@ -8774,9 +10621,13 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) window.DC.NavLayerCurrent = ImGuiNavLayer.Main g.CurrentItemFlags = item_flags_backup + -- Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) + -- FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. local marker_size_x = (bit32.band(flags, ImGuiWindowFlags.UnsavedDocument) ~= 0) and (button_sz * 0.80) or 0.0 local text_size = ImGui.CalcTextSize(name, nil, true) + ImVec2(marker_size_x, 0.0) + -- As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button, + -- while uncentered title text will still reach edges correctly. if (pad_l > style.FramePadding.x) then pad_l = pad_l + g.Style.ItemInnerSpacing.x end @@ -8784,7 +10635,7 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) pad_r = pad_r + g.Style.ItemInnerSpacing.x end if (style.WindowTitleAlign.x > 0.0 and style.WindowTitleAlign.x < 1.0) then - local centerness = ImSaturate(1.0 - ImFabs(style.WindowTitleAlign.x - 0.5) * 2.0) + local centerness = ImSaturate(1.0 - ImFabs(style.WindowTitleAlign.x - 0.5) * 2.0) -- 0.0 on either edges, 1.0 on center local pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect:GetWidth() - pad_l - pad_r - text_size.x) pad_l = ImMax(pad_l, pad_extend * centerness) pad_r = ImMax(pad_r, pad_extend * centerness) @@ -8802,7 +10653,8 @@ local function RenderWindowTitleBarContents(window, title_bar_rect, name, open) clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - math.floor(marker_size_x * 0.5)) end end - + -- if (g.IO.KeyShift) window.DrawList:AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)) -- [DEBUG] + -- if (g.IO.KeyCtrl) window.DrawList:AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)) -- [DEBUG] ImGui.RenderTextClipped(layout_r.Min, layout_r.Max, name, nil, text_size, style.WindowTitleAlign, clip_r) return open @@ -8828,7 +10680,7 @@ function ImGui.UpdateWindowParentAndRootLinks(window, flags, parent_window) if parent_window and (bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0) then window.RootWindowPopupTree = parent_window.RootWindowPopupTree end - if parent_window and (bit32.band(flags, ImGuiWindowFlags.Modal) == 0) and (bit32.band(flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0) then + if parent_window and (bit32.band(flags, ImGuiWindowFlags.Modal) == 0) and (bit32.band(flags, bit32.bor(ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Tooltip)) ~= 0) then -- FIXME: simply use _NoTitleBar ? window.RootWindowForTitleBarHighlight = parent_window.RootWindowForTitleBarHighlight end @@ -8871,10 +10723,10 @@ function ImGui.UpdateWindowSkipRefresh(window) window.SkipItems = true end -- FIXME-IDLE: Tests for e.g. mouse clicks or keyboard while focused. - if window.Appearing then -- If currently appearing + if window.Appearing then -- If currently appearing return end - if window.Hidden then -- If was hidden (previous frame) + if window.Hidden then -- If was hidden (previous frame) return end if bit32.band(g.NextWindowData.RefreshFlagsVal, ImGuiWindowRefreshFlags.RefreshOnHover) ~= 0 and g.HoveredWindow then @@ -8937,6 +10789,11 @@ function ImGui.GcCompactTransientMiscBuffers() end end +-- Free up/compact internal window buffers, we can use this when a window becomes unused. +-- Not freed: +-- - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data) +-- This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost. +-- FIXME: Consider exposing of elaborating GC policy, e.g. being able to trim excessive ImDrawList gaps. (#9303) --- @param window ImGuiWindow function ImGui.GcCompactTransientWindowBuffers(window) window.MemoryCompacted = true @@ -8951,6 +10808,8 @@ end --- @param window ImGuiWindow function ImGui.GcAwakeTransientWindowBuffers(window) + -- We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening. + -- The other buffers tends to amortize much faster. window.MemoryCompacted = false window.DrawList.IdxBuffer:reserve(window.MemoryDrawListIdxCapacity) window.DrawList.VtxBuffer:reserve(window.MemoryDrawListVtxCapacity) @@ -8976,14 +10835,16 @@ function ImGui.SetWindowPos(window, pos, cond) end if cond == nil then cond = 0 end + -- Test condition (NB: bit 0 is always true) and clear flags for next time if (cond ~= 0) and (bit32.band(window.SetWindowPosAllowFlags, cond) == 0) then return end - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. window.SetWindowPosAllowFlags = bit32.band(window.SetWindowPosAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing))) ImVec2_Copy(window.SetWindowPosVal, ImVec2(FLT_MAX, FLT_MAX)) + -- Set local old_pos = ImVec2() ImVec2_Copy(old_pos, window.Pos) @@ -8996,9 +10857,9 @@ function ImGui.SetWindowPos(window, pos, cond) return end ImGui.MarkIniSettingsDirty(window) - - ImVec2_Copy(window.DC.CursorPos, window.DC.CursorPos + offset) - ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorMaxPos + offset) + -- FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here. + ImVec2_Copy(window.DC.CursorPos, window.DC.CursorPos + offset) -- As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor + ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorMaxPos + offset) -- And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected. ImVec2_Copy(window.DC.IdealMaxPos, window.DC.IdealMaxPos + offset) ImVec2_Copy(window.DC.CursorStartPos, window.DC.CursorStartPos + offset) end @@ -9016,13 +10877,15 @@ function ImGui.SetWindowSize(window, size, cond) end if cond == nil then cond = 0 end + -- Test condition (NB: bit 0 is always true) and clear flags for next time if ((cond ~= 0) and bit32.band(window.SetWindowSizeAllowFlags, cond) == 0) then return end - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. window.SetWindowSizeAllowFlags = bit32.band(window.SetWindowSizeAllowFlags, bit32.bnot(bit32.bor(ImGuiCond.Once, ImGuiCond.FirstUseEver, ImGuiCond.Appearing))) + -- Enable auto-fit (not done in BeginChild() path unless appearing or combined with ImGuiChildFlags.AlwaysAutoResize) if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) == 0 or window.Appearing or bit32.band(window.ChildFlags, ImGuiChildFlags.AlwaysAutoResize) ~= 0 then window.AutoFitFramesX = (size.x <= 0.0) and 2 or 0 end @@ -9030,6 +10893,7 @@ function ImGui.SetWindowSize(window, size, cond) window.AutoFitFramesY = (size.y <= 0.0) and 2 or 0 end + -- Set local old_size_x, old_size_y = window.SizeFull.x, window.SizeFull.y if size.x <= 0.0 then @@ -9056,6 +10920,7 @@ function ImGui.SetWindowCollapsed(window, collapsed, cond) window, collapsed, cond = GImGui.CurrentWindow, window, collapsed end if cond == nil then cond = 0 end + -- Test condition (NB: bit 0 is always true) and clear flags for next time if cond ~= 0 and bit32.band(window.SetWindowCollapsedAllowFlags, cond) == 0 then return end @@ -9132,7 +10997,7 @@ function ImGui.SetNextWindowPos(pos, cond, pivot) if pivot == nil then pivot = ImVec2(0, 0) end local g = GImGui - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) ImVec2_Copy(g.NextWindowData.PosVal, pos) @@ -9147,7 +11012,7 @@ function ImGui.SetNextWindowSize(size, cond) if cond == nil then cond = 0 end local g = GImGui - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ImVec2_Copy(g.NextWindowData.SizeVal, size) @@ -9186,6 +11051,9 @@ function ImGui.GetFont() return GImGui.Font end +-- 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) function ImGui.GetFontSize() return GImGui.FontSize end @@ -9234,7 +11102,7 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) child_flags = bit32.band(bit32.bor(child_flags, g.NextWindowData.ChildFlagsSet), bit32.bnot(g.NextWindowData.ChildFlagsClear)) end - -- Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument + -- Sanity check as it is likely that some user will accidentally pass ImGuiWindowFlags into the ImGuiChildFlags argument. local ImGuiChildFlags_SupportedMask_ = bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY, ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AutoResizeY, ImGuiChildFlags.AlwaysAutoResize, ImGuiChildFlags.FrameStyle, ImGuiChildFlags.NavFlattened) -- IM_UNUSED(ImGuiChildFlags_SupportedMask_) IM_ASSERT(bit32.band(child_flags, bit32.bnot(ImGuiChildFlags_SupportedMask_)) == 0, "Illegal ImGuiChildFlags value. Did you pass ImGuiWindowFlags values instead of ImGuiChildFlags?") @@ -9254,7 +11122,7 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) window_flags = bit32.bor(window_flags, ImGuiWindowFlags.ChildWindow, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoDocking) window_flags = bit32.bor(window_flags, bit32.band(parent_window.Flags, ImGuiWindowFlags.NoMove)) -- Inherit the NoMove flag if bit32.band(child_flags, bit32.bor(ImGuiChildFlags.AutoResizeX, ImGuiChildFlags.AutoResizeY, ImGuiChildFlags.AlwaysAutoResize)) ~= 0 then - window_flags = bit32.bor(window_flags, ImGuiWindowFlags.AlwaysAutoResize) + window_flags = bit32.bor(window_flags, ImGuiWindowFlags.AlwaysAutoResize) -- FIXME: Would be sane to not make single-axis flag set this. (#9355) end if bit32.band(child_flags, bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY)) == 0 then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoSavedSettings) @@ -9271,15 +11139,15 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) end -- Forward size - -- Important: Begin() has special processing to switch condition to ImGuiCond_FirstUseEver for a given axis when ImGuiChildFlags.ResizeXXX is set. + -- Important: Begin() has special processing to switch condition to ImGuiCond.FirstUseEver for a given axis when ImGuiChildFlags.ResizeXXX is set. -- (the alternative would to store conditional flags per axis, which is possible but more code) local size_avail = ImGui.GetContentRegionAvail() local size_default = ImVec2((bit32.band(child_flags, ImGuiChildFlags.AutoResizeX) ~= 0) and 0.0 or size_avail.x, (bit32.band(child_flags, ImGuiChildFlags.AutoResizeY) ~= 0) and 0.0 or size_avail.y) local size = ImGui.CalcItemSize(size_arg, size_default.x, size_default.y) -- 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. + -- (since the code in Begin() never supported SizeVal==0.0 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 bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ~= 0 and bit32.band(g.NextWindowData.SizeCond, ImGuiCond.Always) ~= 0 then if g.NextWindowData.SizeVal.x > 0.0 then size.x = g.NextWindowData.SizeVal.x @@ -9297,6 +11165,9 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) -- 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. -- e.g. "ParentName###ParentIdentifier/ChildName###ChildIdentifier" would get hashed incorrectly by ImHashStr(), trailing _%08X somehow fixes it. local temp_window_name + -- if (name and parent_window.IDStack:back() == parent_window.ID) + -- temp_window_name = ImFormatString("%s/%s", parent_window.Name, name) -- May omit ID if in root of ID stack + -- else if name then temp_window_name = ImFormatString("%s/%s_%08X", parent_window.Name, name, id) else @@ -9346,6 +11217,7 @@ function ImGui.BeginChildEx(name, id, size_arg, child_flags, window_flags) end -- Prior to v1.90 2023/10/16, the BeginChild() function took a 'bool border = false' parameter instead of 'ImGuiChildFlags child_flags = 0'. +-- ImGuiChildFlags.Borders is defined as always == 1 in order to allow old code passing 'true'. Read comments in imgui.h for details! -- `true` is accepted as ImGuiChildFlags.Borders for legacy code. --- @param str_id_or_id string|ImGuiID --- @param size_arg? ImVec2 @@ -9393,6 +11265,8 @@ function ImGui.EndChild() end else -- Not navigable into + -- - This is a bit of a fringe use case, mostly useful for undecorated, non-scrolling contents childs, or empty childs. + -- - We could later decide to not apply this path if ImGuiChildFlags.FrameStyle or ImGuiChildFlags.Borders is set. ImGui.ItemAdd(bb, child_window.ChildId, nil, ImGuiItemFlags.NoNav) -- But when flattened we directly reach items, adjust active layer mask accordingly @@ -9404,6 +11278,7 @@ function ImGui.EndChild() g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end child_window.DC.ChildItemStatusFlags = g.LastItemData.StatusFlags + -- SetLastItemDataForChildWindowItem(child_window, child_window:Rect()) -- Not needed, effectively done by ItemAdd() else ImGui.SetLastItemDataForChildWindowItem(child_window, child_window:Rect()) end @@ -9449,6 +11324,7 @@ function ImGui.SetNextWindowFlags(flags, enabled) end -- Content size = inner scrollable rectangle, padded with WindowPadding. +-- SetNextWindowContentSize(ImVec2(100,100)) + ImGuiWindowFlags.AlwaysAutoResize will always allow submitting a 100x100 item. --- @param size ImVec2 function ImGui.SetNextWindowContentSize(size) local g = GImGui @@ -9468,7 +11344,7 @@ end function ImGui.SetNextWindowCollapsed(collapsed, cond) if cond == nil then cond = 0 end local g = GImGui - IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) + IM_ASSERT(cond == 0 or ImIsPowerOfTwo(cond)) -- Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.HasFlags = bit32.bor(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasCollapsed) g.NextWindowData.CollapsedVal = collapsed g.NextWindowData.CollapsedCond = (cond ~= 0) and cond or ImGuiCond.Always @@ -9537,6 +11413,9 @@ end --- @param window ImGuiWindow function ImGui.StartMouseMovingWindow(window) + -- Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows. + -- We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward. + -- This is because we want ActiveId to be set even when the window is not permitted to move. local g = GImGui ImGui.FocusWindow(window) ImGui.SetActiveID(window.MoveId, window) @@ -9560,15 +11439,23 @@ function ImGui.StartMouseMovingWindow(window) end end +-- 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 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. function ImGui.UpdateMouseMovingWindowNewFrame() local g = GImGui if g.MovingWindow then + -- We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window). + -- We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow.MoveId for consistency. ImGui.KeepAliveID(g.ActiveId) IM_ASSERT(g.MovingWindow and g.MovingWindow.RootWindowDockTree) local moving_window = g.MovingWindow.RootWindowDockTree + -- When a window stop being submitted while being dragged, it may will its viewport until next Begin() local window_disappeared = (not moving_window.WasActive and not moving_window.Active) if g.IO.MouseDown[0] and ImGui.IsMousePosValid(g.IO.MousePos) and not window_disappeared then local pos = g.IO.MousePos - g.ActiveIdClickOffset @@ -9585,6 +11472,7 @@ function ImGui.UpdateMouseMovingWindowNewFrame() ImGui.ClearActiveID() end else + -- When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others. if (g.ActiveIdWindow and g.ActiveIdWindow.MoveId == g.ActiveId) then ImGui.KeepAliveID(g.ActiveId) @@ -9599,6 +11487,7 @@ function ImGui.GetDrawListSharedData() return GImGui.DrawListSharedData end +-- Supported flags: ImGuiPopupFlags.AnyPopupId, ImGuiPopupFlags.AnyPopupLevel --- @param id ImGuiID --- @param popup_flags ImGuiPopupFlags function ImGui.IsPopupOpen(id, popup_flags) @@ -9634,6 +11523,7 @@ function ImGui.IsPopupOpen(id, popup_flags) end end +-- Also see FindBlockingModal(nil) --- @return ImGuiWindow? function ImGui.GetTopMostPopupModal() local g = GImGui @@ -9648,6 +11538,9 @@ function ImGui.GetTopMostPopupModal() return nil end +-- Initiate focusing and moving window when clicking on empty space or title bar. +-- Initiate focusing window when clicking on a disabled item. +-- Handle left-click and right-click focus. function ImGui.UpdateMouseMovingWindowEndFrame() local g = GImGui @@ -9655,13 +11548,18 @@ function ImGui.UpdateMouseMovingWindowEndFrame() return end + -- Unless we just made a window/popup appear if g.NavWindow and g.NavWindow.Appearing then return end local hovered_window = g.HoveredWindow + -- Click on empty space to focus window and start moving + -- (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!) if ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) then + -- Handle the edge case of a popup being closed while clicking in its empty space. + -- If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more. local hovered_root if hovered_window then hovered_root = hovered_window.RootWindow @@ -9674,8 +11572,11 @@ function ImGui.UpdateMouseMovingWindowEndFrame() if hovered_window ~= nil and not is_closed_popup and not is_queued_focus_request then ImGui.StartMouseMovingWindow(hovered_window) + -- FIXME: In principle we might be able to call StopMouseMovingWindow() below. + -- Please note how StartMouseMovingWindow() and StopMouseMovingWindow() and not entirely symmetrical, at the later doesn't clear ActiveId. + -- Cancel moving if clicked outside of title bar - if bit32.band(hovered_window.BgClickFlags, ImGuiWindowBgClickFlags.Move) == 0 then -- set by io.ConfigWindowsMoveFromTitleBarOnly + if bit32.band(hovered_window.BgClickFlags, ImGuiWindowBgClickFlags.Move) == 0 then -- set by io.ConfigWindowsMoveFromTitleBarOnly if bit32.band(hovered_root.Flags, ImGuiWindowFlags.NoTitleBar) == 0 then if not hovered_root:TitleBarRect():Contains(g.IO.MouseClickedPos[0]) then g.MovingWindow = nil @@ -9690,6 +11591,7 @@ function ImGui.UpdateMouseMovingWindowEndFrame() g.ActiveIdDisabledId = g.HoveredId end elseif hovered_window == nil and g.NavWindow ~= nil then + -- Clicking on void disable focus ImGui.FocusWindow(nil, ImGuiFocusRequestFlags.UnlessBelowModal) end end @@ -9706,6 +11608,8 @@ function ImGui.UpdateMouseMovingWindowEndFrame() end end +-- This is called during NewFrame()->UpdateViewportsNewFrame() only. +-- Need to keep in sync with SetWindowPos() --- @param window ImGuiWindow --- @param delta ImVec2 function ImGui.TranslateWindow(window, delta) @@ -9736,8 +11640,13 @@ function ImGui.FindWindowByName(name) return ImGui.FindWindowByID(id) end ---- Push a new Dear ImGui window to add widgets to. ---- - Passing a non-nil `open` displays a close button on the upper-right corner of the window +-- Push a new Dear ImGui window to add widgets to. +-- - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. +-- - Begin/End can be called multiple times during the frame with the same window name to append content. +-- - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). +-- You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. +-- - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui.End() even if false is returned. +-- - Passing a non-nil 'open' displays a Close button on the upper-right corner of the window, the returned 'is_open' value will be false when the button is pressed. --- @param name string --- @param open? bool --- @param flags? ImGuiWindowFlags @@ -9749,10 +11658,11 @@ function ImGui.Begin(name, open, flags) local g = GImGui local style = g.Style - IM_ASSERT(name ~= nil and name ~= "") - IM_ASSERT(g.WithinFrameScope) - IM_ASSERT(g.FrameCountEnded ~= g.FrameCount) + IM_ASSERT(name ~= nil and name ~= "") -- Window name required + IM_ASSERT(g.WithinFrameScope) -- Forgot to call ImGui.NewFrame() + IM_ASSERT(g.FrameCountEnded ~= g.FrameCount) -- Called ImGui.Render() or ImGui.EndFrame() and haven't called ImGui.NewFrame() again yet + -- Find or create local window = ImGui.FindWindowByName(name) local window_just_created = (window == nil) if window_just_created then @@ -9772,7 +11682,8 @@ function ImGui.Begin(name, open, flags) local first_begin_of_the_frame = (window.LastFrameActive ~= current_frame) window.IsFallbackWindow = (g.CurrentWindowStack.Size == 0 and g.WithinFrameScopeWithImplicitWindow) - local window_just_activated_by_user = (window.LastFrameActive < (current_frame - 1)) + -- Update the Appearing flag (note: the BeginDocked() path may also set this to true later) + local window_just_activated_by_user = (window.LastFrameActive < (current_frame - 1)) -- Not using !WasActive because the implicit "Debug" window would always toggle off->on if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then local popup_ref = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1] window_just_activated_by_user = window_just_activated_by_user or (window.PopupId ~= popup_ref.PopupId) -- We recycle popups so treat window as activated if popup id changed @@ -9819,7 +11730,7 @@ function ImGui.Begin(name, open, flags) flags = window.Flags if window.DockIsActive then IM_ASSERT(window.DockNode ~= nil) - g.NextWindowData.HasFlags = bit32.band(g.NextWindowData.HasFlags, bit32.bnot(ImGuiNextWindowDataFlags.HasSizeConstraint)) + g.NextWindowData.HasFlags = bit32.band(g.NextWindowData.HasFlags, bit32.bnot(ImGuiNextWindowDataFlags.HasSizeConstraint)) -- Docking currently override constraints end -- Amend the Appearing flag @@ -9830,6 +11741,7 @@ function ImGui.Begin(name, open, flags) end end + -- Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack local parent_window_in_stack if window.DockIsActive and window.DockNode.HostWindow then parent_window_in_stack = window.DockNode.HostWindow @@ -9849,6 +11761,7 @@ function ImGui.Begin(name, open, flags) parent_window = window.ParentWindow end + -- We allow window memory to be compacted so recreate the base stack when needed. if window.IDStack.Size == 0 then window.IDStack:push_back(window.ID) end @@ -9869,10 +11782,14 @@ function ImGui.Begin(name, open, flags) g.BeginMenuDepth = g.BeginMenuDepth + 1 end + -- Update .RootWindow and others pointers (before any possible call to FocusWindow) if first_begin_of_the_frame then ImGui.UpdateWindowParentAndRootLinks(window, flags, parent_window) window.ParentWindowInBeginStack = parent_window_in_stack + -- Focus route + -- There's little point to expose a flag to set this: because the interesting cases won't be using parent_window_in_stack, + -- Use for e.g. linking a tool window in a standalone viewport to a document window, regardless of their Begin() stack parenting. (#6798) if window.RootWindow ~= window then window.ParentWindowForFocusRoute = parent_window_in_stack else @@ -9883,10 +11800,12 @@ function ImGui.Begin(name, open, flags) window.ParentWindowForFocusRoute = window.DockNode.HostWindow end end + -- Override with SetNextWindowClass() field or direct call to SetWindowParentWindowForFocusRoute() if window.WindowClass and window.WindowClass.FocusRouteParentWindowId ~= nil and window.WindowClass.FocusRouteParentWindowId ~= 0 then window.ParentWindowForFocusRoute = ImGui.FindWindowByID(window.WindowClass.FocusRouteParentWindowId) end + -- Inherit SetWindowFontScale() from parent until we fix this system... if parent_window then window.FontWindowScaleParents = parent_window.FontWindowScaleParents * parent_window.FontWindowScale else @@ -9894,10 +11813,11 @@ function ImGui.Begin(name, open, flags) end end + -- Add to focus scope stack ImGui.PushFocusScope((bit32.band(window.ChildFlags, ImGuiChildFlags.NavFlattened) ~= 0) and g.CurrentFocusScopeId or window.ID) window.NavRootFocusScopeId = g.CurrentFocusScopeId - -- Add to popup stacks: update OpenPopupStack data, push to BeginPopupStack + -- Add to popup stacks: update OpenPopupStack[] data, push to BeginPopupStack[] if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then local popup_ref = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1] popup_ref.Window = window @@ -9906,12 +11826,15 @@ function ImGui.Begin(name, open, flags) window.PopupId = popup_ref.PopupId end + -- Process SetNextWindow***() calls + -- (FIXME: Consider splitting the HasXXX flags into X/Y components) local window_pos_set_by_api = false local window_size_x_set_by_api = false local window_size_y_set_by_api = false if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) ~= 0 then window_pos_set_by_api = (bit32.band(window.SetWindowPosAllowFlags, g.NextWindowData.PosCond) ~= 0) if window_pos_set_by_api and ImLengthSqr(g.NextWindowData.PosPivotVal) > 1e-5 then + -- May be processed on the next frame if this is our first frame and we are measuring size -- FIXME: Look into removing the branch so everything can go through this same code path for consistency. ImVec2_Copy(window.SetWindowPosVal, g.NextWindowData.PosVal) ImVec2_Copy(window.SetWindowPosPivot, g.NextWindowData.PosPivotVal) @@ -9923,7 +11846,7 @@ function ImGui.Begin(name, open, flags) if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) ~= 0 then window_size_x_set_by_api = (bit32.band(window.SetWindowSizeAllowFlags, g.NextWindowData.SizeCond) ~= 0) and (g.NextWindowData.SizeVal.x > 0.0) window_size_y_set_by_api = (bit32.band(window.SetWindowSizeAllowFlags, g.NextWindowData.SizeCond) ~= 0) and (g.NextWindowData.SizeVal.y > 0.0) - if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then + if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeX) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then -- Axis-specific conditions for BeginChild() g.NextWindowData.SizeVal.x = window.SizeFull.x end if (bit32.band(window.ChildFlags, ImGuiChildFlags.ResizeY) ~= 0 and bit32.band(window.SetWindowSizeAllowFlags, ImGuiCond.FirstUseEver) == 0) then @@ -9962,14 +11885,18 @@ function ImGui.Begin(name, open, flags) -- [EXPERIMENTAL] Skip Refresh mode ImGui.UpdateWindowSkipRefresh(window) + -- Nested root windows (typically tooltips) override disabled state if window_stack_data.DisabledOverrideReenable and window.RootWindow == window then ImGui.BeginDisabledOverrideReenable() end + -- We intentionally set g.CurrentWindow to nil to prevent usage until when the viewport is set, then will call SetCurrentWindow() g.CurrentWindow = nil + -- When reusing window again multiple times a frame, just append content (don't need to setup again) if first_begin_of_the_frame and not window.SkipRefresh then - local window_is_child_tooltip = (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0) + -- Initialize + local window_is_child_tooltip = (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Tooltip) ~= 0) -- FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) local window_just_appearing_after_hidden_for_resize = (window.HiddenFramesCannotSkipItems > 0) window.Active = true @@ -9982,16 +11909,22 @@ function ImGui.Begin(name, open, flags) window.DC.CurrentTableIdx = -1 if bit32.band(flags, ImGuiWindowFlags.DockNodeHost) ~= 0 then window.DrawList:ChannelsSplit(2) - window.DrawList:ChannelsSetCurrent(1) -- DOCKING_HOST_DRAW_CHANNEL_FG: render decorations on channel 1, backgrounds rendered manually later + window.DrawList:ChannelsSetCurrent(1) -- DOCKING_HOST_DRAW_CHANNEL_FG: Render decorations on channel 1 as we will render the backgrounds manually later end + -- Restore buffer capacity when woken from a compacted state, to avoid if window.MemoryCompacted then ImGui.GcAwakeTransientWindowBuffers(window) end -- UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS + -- Update contents size from last frame for auto-fitting (or use explicit size) CalcWindowContentSizes(window, window.ContentSize, window.ContentSizeIdeal) + + -- FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors + -- for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because + -- it has a single usage before this code block and may be set below before it is finally checked. if window.HiddenFramesCanSkipItems > 0 then window.HiddenFramesCanSkipItems = window.HiddenFramesCanSkipItems - 1 end @@ -10026,11 +11959,16 @@ function ImGui.Begin(name, open, flags) end -- SELECT VIEWPORT + -- We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes. + ImGui.WindowSelectViewport(window) ImGui.SetCurrentViewport(window, window.Viewport) SetCurrentWindow(window) flags = window.Flags + -- LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies) + -- We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style. + if not window.DockIsActive and bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then window.WindowBorderSize = style.ChildBorderSize else @@ -10063,25 +12001,29 @@ function ImGui.Begin(name, open, flags) window.TitleBarHeight = (bit32.band(flags, ImGuiWindowFlags.NoTitleBar) ~= 0) and 0 or g.FontSize + g.Style.FramePadding.y * 2 - window.FontRefSize = g.FontSize -- Lock this to discourage calling window:CalcFontSize() outside of current window. + 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. local use_current_size_for_scrollbar_x = window_just_created local use_current_size_for_scrollbar_y = window_just_created if window_size_x_set_by_api and window.ContentSizeExplicit.x ~= 0.0 then use_current_size_for_scrollbar_x = true end - if window_size_y_set_by_api and window.ContentSizeExplicit.y ~= 0.0 then + if window_size_y_set_by_api and window.ContentSizeExplicit.y ~= 0.0 then -- #7252 use_current_size_for_scrollbar_y = true end -- Collapse window by double-clicking on title bar -- At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and bit32.band(flags, ImGuiWindowFlags.NoCollapse) == 0 and not window.DockIsActive then + -- We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), + -- so verify that we don't have items over the title bar. local title_bar_rect = window:TitleBarRect() if g.HoveredWindow == window and g.HoveredId == 0 and g.HoveredIdPreviousFrame == 0 and g.ActiveId == 0 and ImGui.IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) then if g.IO.MouseClickedCount[0] == 2 and ImGui.GetKeyOwner(ImGuiKey.MouseLeft) == ImGuiKeyOwner_NoOwner then window.WantCollapseToggle = true - ImGui.SetKeyOwner(ImGuiKey.MouseLeft, window.MoveId) + ImGui.SetKeyOwner(ImGuiKey.MouseLeft, window.MoveId) -- Claim input the same way ButtonBehavior() does. Prevent a same-frame move from triggering other items. (#9439) end end if window.WantCollapseToggle then @@ -10096,6 +12038,10 @@ function ImGui.Begin(name, open, flags) end window.WantCollapseToggle = false + -- SIZE + + -- Outer Decoration Sizes + -- (we need to clear ScrollbarSize immediately as CalcWindowAutoFitSize() needs it and can be called from other locations). local scrollbar_sizes_from_last_frame = ImVec2() ImVec2_Copy(scrollbar_sizes_from_last_frame, window.ScrollbarSizes) @@ -10156,6 +12102,7 @@ function ImGui.Begin(name, open, flags) end end + -- Apply minimum/maximum window size constraints and final size ImVec2_Copy(window.SizeFull, CalcWindowSizeAfterConstraint(window, window.SizeFull)) ImVec2_Copy(window.Size, (window.Collapsed and bit32.band(flags, ImGuiWindowFlags.ChildWindow) == 0) and window:TitleBarRect():GetSize() or window.SizeFull) @@ -10169,6 +12116,7 @@ function ImGui.Begin(name, open, flags) end end + -- Position child window if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then IM_ASSERT(parent_window and parent_window.Active) window.BeginOrderWithinParent = parent_window.DC.ChildWindows.Size @@ -10207,12 +12155,16 @@ function ImGui.Begin(name, open, flags) ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) end + -- Calculate the range of allowed position for that window (to be movable and visible past safe area padding) + -- When clamping to stay visible, we will enforce that window.Pos stays inside of visibility_rect. local viewport_rect = window.Viewport:GetMainRect() local viewport_work_rect = window.Viewport:GetWorkRect() local visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding) local visibility_rect = ImRect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding) -- Clamp position/size so window stays visible within its viewport or monitor + -- Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + -- FIXME: Similar to code in GetWindowAllowedExtentRect() if not window_pos_set_by_api and bit32.band(flags, ImGuiWindowFlags.ChildWindow) == 0 then if not window.ViewportOwned and viewport_rect:GetWidth() > 0 and viewport_rect:GetHeight() > 0.0 then local size_for_clamping_y = window.Size.y @@ -10225,6 +12177,7 @@ function ImGui.Begin(name, open, flags) end window.Pos.x = ImTrunc(window.Pos.x) window.Pos.y = ImTrunc(window.Pos.y) + -- Apply window focus (new and reactivated windows are moved to front) local want_focus = false if (window_just_activated_by_user and bit32.band(flags, ImGuiWindowFlags.NoFocusOnAppearing) == 0) then if bit32.band(flags, ImGuiWindowFlags.Popup) ~= 0 then @@ -10234,6 +12187,8 @@ function ImGui.Begin(name, open, flags) end end + -- Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) + -- Large values tend to lead to variety of artifacts and are not recommended. if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and not window.DockIsActive then window.WindowRounding = style.ChildRounding elseif window.RootWindowDockTree.ViewportOwned then @@ -10246,11 +12201,16 @@ function ImGui.Begin(name, open, flags) end end + -- Decide if we are going to handle borders and resize grips + -- '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. local handle_borders_and_resize_grips = (window.DockNodeAsHost ~= nil or not window.DockIsActive) if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and window.ParentWindow.SkipItems then handle_borders_and_resize_grips = false end + -- Handle manual resize: Resize Grips, Borders, Gamepad + -- Child windows can only be resized when they have the flags set. The resize grip allows resizing in both directions, so it should appear only if both flags are set. local border_hovered, border_held = -1, -1 local resize_grip_col = {0, 0, 0, 0} @@ -10262,7 +12222,7 @@ function ImGui.Begin(name, open, flags) resize_grip_count = 0 end else - resize_grip_count = g.IO.ConfigWindowsResizeFromEdges and 2 or 1 -- Allow resize from lower-left if we have the mouse cursor feedback for it. + resize_grip_count = g.IO.ConfigWindowsResizeFromEdges and 2 or 1 -- Allow resize from lower-left if we have the mouse cursor feedback for it. end local resize_grip_draw_size = ImTrunc(ImMax(g.FontSize * 1.10, g.Style.WindowRounding + 1.0 + g.FontSize * 0.2)) @@ -10296,12 +12256,13 @@ function ImGui.Begin(name, open, flags) -- Save last known viewport position within the window itself (so it can be saved in .ini file and restored) ImVec2_Copy(window.ViewportPos, window.Viewport.Pos) - --- SCROLLBAR VISIBILITY - -- Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size) + -- SCROLLBAR VISIBILITY + + -- Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size). if not window.Collapsed then -- When reading the current size we need to read it after size constraints have been applied. -- Intentionally use previous frame values for InnerRect and ScrollbarSizes. - -- And when we use window.DecoOuterSizeY1 here it doesn't have ScrollbarSizes.y applied yet. + -- And when we use window.DecorationUp here it doesn't have ScrollbarSizes.y applied yet. local avail_size_from_current_frame = ImVec2(window.SizeFull.x, window.SizeFull.y - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2)) local avail_size_from_last_frame = window.InnerRect:GetSize() + scrollbar_sizes_from_last_frame local needed_size_from_last_frame = window_just_created and ImVec2(0, 0) or window.ContentSize + window.WindowPadding * 2.0 @@ -10339,11 +12300,20 @@ function ImGui.Begin(name, open, flags) window.ScrollbarSizes = ImVec2(window.ScrollbarY and style.ScrollbarSize or 0.0, window.ScrollbarX and style.ScrollbarSize or 0.0) - -- Amend the partially filled window.DecoOuterSizeX2 values. + -- Amend the partially filled window.DecorationXXX values. window.DecoOuterSizeX2 = window.DecoOuterSizeX2 + window.ScrollbarSizes.x window.DecoOuterSizeY2 = window.DecoOuterSizeY2 + window.ScrollbarSizes.y end + -- UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING) + -- Update various regions. Variables they depend on should be set above in this function. + -- We set this up after processing the resize grip so that our rectangles doesn't lag by a frame. + + -- Outer rectangle + -- Not affected by window border size. Used by: + -- - FindHoveredWindow() (w/ extra padding when border resize is enabled) + -- - Begin() initial clipping rect for drawing window background and borders. + -- - Begin() clipping whole child local host_rect if (bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(flags, ImGuiWindowFlags.Popup) == 0 and not window_is_child_tooltip) then host_rect = parent_window.ClipRect @@ -10358,20 +12328,39 @@ function ImGui.Begin(name, open, flags) end window.OuterRectClipped:ClipWith(host_rect) + -- Inner rectangle + -- Not affected by window border size. Used by: + -- - InnerClipRect + -- - ScrollToRectEx() + -- - NavUpdatePageUpPageDown() + -- - Scrollbar() window.InnerRect.Min.x = window.Pos.x + window.DecoOuterSizeX1 window.InnerRect.Min.y = window.Pos.y + window.DecoOuterSizeY1 window.InnerRect.Max.x = window.Pos.x + window.Size.x - window.DecoOuterSizeX2 window.InnerRect.Max.y = window.Pos.y + window.Size.y - window.DecoOuterSizeY2 + -- Inner clipping rectangle. + -- - Extend a outside of normal work region up to borders. + -- - This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. + -- - It also makes clipped items be more noticeable. + -- - And is consistent on both axis (prior to 2024/05/03 ClipRect used WindowPadding.x * 0.5 on left and right edge), see #3312 + -- - Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + -- Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. + -- Affected by window/frame border size. Used by: + -- - Begin() initial clip rect local top_border_size = ((bit32.band(flags, ImGuiWindowFlags.MenuBar) ~= 0 or bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0) and style.FrameBorderSize or window.WindowBorderSize) + -- Try to match the fact that our border is drawn centered over the window rectangle, rather than inner. + -- This is why we do a *0.5 here. We don't currently even technically support large values for WindowBorderSize, + -- see e.g #7887 #7888, but may do after we move the window border to become an inner border (and then we can remove the 0.5 here). window.InnerClipRect.Min.x = ImFloor(0.5 + window.InnerRect.Min.x + window.WindowBorderSize * 0.5) window.InnerClipRect.Min.y = ImFloor(0.5 + window.InnerRect.Min.y + top_border_size * 0.5) window.InnerClipRect.Max.x = ImFloor(window.InnerRect.Max.x - window.WindowBorderSize * 0.5) window.InnerClipRect.Max.y = ImFloor(window.InnerRect.Max.y - window.WindowBorderSize * 0.5) window.InnerClipRect:ClipWithFull(host_rect) - --- Scrolling + -- SCROLLING + -- Lock down maximum scrolling -- The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate -- for right/bottom aligned items without creating a scrollbar. @@ -10383,10 +12372,16 @@ function ImGui.Begin(name, open, flags) ImVec2_CopyV(window.ScrollTarget, FLT_MAX, FLT_MAX) window.DecoInnerSizeX1 = 0.0; window.DecoInnerSizeY1 = 0.0 + -- DRAWING + + -- Setup draw list and outer clipping rectangle IM_ASSERT(window.DrawList.CmdBuffer.Size == 1 and window.DrawList.CmdBuffer.Data[1].ElemCount == 0) window.DrawList:PushTexture(g.Font.OwnerAtlas.TexRef) ImGui.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) + -- When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order. + -- FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493) local is_undocked_or_docked_visible = not window.DockIsActive or window.DockTabIsVisible if is_undocked_or_docked_visible then local render_decorations_in_parent = false @@ -10415,6 +12410,7 @@ function ImGui.Begin(name, open, flags) window.DrawList = parent_window.DrawList end + -- Handle title bar, scrollbar, resize grips and resize borders local window_to_highlight = g.NavWindowingTarget or g.NavWindow local title_bar_is_highlight = want_focus or (window_to_highlight ~= nil and (window.RootWindowForTitleBarHighlight == window_to_highlight.RootWindowForTitleBarHighlight or (window.DockNode ~= nil and window.DockNode == window_to_highlight.DockNode))) @@ -10425,6 +12421,13 @@ function ImGui.Begin(name, open, flags) end end + -- UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING) + + -- Work rectangle. + -- Affected by window padding and border size. Used by: + -- - Columns() for right-most edge + -- - TreeNode(), CollapsingHeader() for right-most edge + -- - BeginTabBar() for right-most edge local allow_scrollbar_x = (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) == 0) and (bit32.band(flags, ImGuiWindowFlags.HorizontalScrollbar) ~= 0) local allow_scrollbar_y = (bit32.band(flags, ImGuiWindowFlags.NoScrollbar) == 0) @@ -10453,7 +12456,7 @@ function ImGui.Begin(name, open, flags) window.ParentWorkRect = window.WorkRect -- [LEGACY] Content Region - -- FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. + -- FIXME-OBSOLETE: window.ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. -- Unless explicit content size is specified by user, this currently represent the region leading to no scrolling. -- Used by: -- - Mouse wheel scrolling + many other things @@ -10463,7 +12466,7 @@ function ImGui.Begin(name, open, flags) window.ContentRegionRect.Max.y = window.ContentRegionRect.Min.y + (window.ContentSizeExplicit.y ~= 0.0 and window.ContentSizeExplicit.y or (window.Size.y - window.WindowPadding.y * 2.0 - (window.DecoOuterSizeY1 + window.DecoOuterSizeY2))) -- Setup drawing context - -- (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) + -- (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window. and window.DC. is dubious.) window.DC.Indent.x = window.DecoOuterSizeX1 + window.WindowPadding.x - window.Scroll.x window.DC.GroupOffset.x = 0.0 window.DC.ColumnsOffset.x = 0.0 @@ -10519,7 +12522,7 @@ function ImGui.Begin(name, open, flags) end window.DC.ItemWidth = window.DC.ItemWidthDefault window.DC.ItemWidthStack:resize(0) - window.DC.TextWrapPos = -1.0 + window.DC.TextWrapPos = -1.0 -- Disabled window.DC.TextWrapPosStack:resize(0) if bit32.band(flags, ImGuiWindowFlags.Modal) ~= 0 then window.DC.ModalDimBgColor = ImGui.ColorConvertFloat4ToU32(ImGui.GetStyleColorVec4(ImGuiCol.ModalWindowDimBg)) @@ -10532,22 +12535,30 @@ function ImGui.Begin(name, open, flags) window.AutoFitFramesY = window.AutoFitFramesY - 1 end + -- Clear SetNextWindowXXX data (can aim to move this higher in the function) g.NextWindowData:ClearFlags() + -- Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) + -- We ImGuiFocusRequestFlags.UnlessBelowModal to: + -- - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed. + -- - Position window behind the modal that is not a begin-parent of this window. if want_focus then ImGui.FocusWindow(window, ImGuiFocusRequestFlags.UnlessBelowModal) end if want_focus and window == g.NavWindow then - ImGui.NavInitWindow(window, false) + ImGui.NavInitWindow(window, false) -- <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls end -- 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 then if g.NavWindow and g.NavWindow.RootWindow == window and g.ActiveId == 0 and ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.C)) then ImGui.LogToClipboard(0) end end + -- Title bar if bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and not window.DockIsActive then open = 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, open) elseif bit32.band(flags, ImGuiWindowFlags.NoTitleBar) == 0 and window.DockIsActive then @@ -10563,7 +12574,7 @@ function ImGui.Begin(name, open, flags) if bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.DockingEnable) ~= 0 then -- Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source. - -- We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it. + -- We need to do this _before_ we overwrite window.DC.LastItemId below because BeginDockableDragDropSource() also overwrites it. if g.MovingWindow == window and bit32.band(window.RootWindowDockTree.Flags, ImGuiWindowFlags.NoDocking) == 0 then ImGui.BeginDockableDragDropSource(window) end @@ -10578,12 +12589,17 @@ function ImGui.Begin(name, open, flags) end end + -- Set default BgClickFlags + -- This is set at the end of this function, so UpdateWindowManualResize()/ClampWindowPos() may use last-frame value if overridden by user code. + -- FIXME: The general intent is that we will later expose config options to default to enable scrolling + select scrolling mouse button. if bit32.band(flags, ImGuiWindowFlags.ChildWindow) ~= 0 then window.BgClickFlags = parent_window.BgClickFlags else window.BgClickFlags = g.IO.ConfigWindowsMoveFromTitleBarOnly and ImGuiWindowBgClickFlags.None or ImGuiWindowBgClickFlags.Move end + -- 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 if ImGui.IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) then @@ -10591,10 +12607,12 @@ function ImGui.Begin(name, open, flags) end ImGui.SetLastItemDataForWindow(window, title_bar_rect) else + -- Skip refresh always mark active if (window.SkipRefresh) then SetWindowActiveForSkipRefresh(window) end + -- Append ImGui.SetCurrentViewport(window, window.Viewport) SetCurrentWindow(window) g.NextWindowData:ClearFlags() @@ -10609,12 +12627,17 @@ function ImGui.Begin(name, open, flags) dl._ScrollOriginX, dl._ScrollOriginY = window.Pos.x - window.Scroll.x, window.Pos.y - window.Scroll.y end + -- Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) window.WriteAccessed = false window.BeginCount = window.BeginCount + 1 g.NextWindowData:ClearFlags() + -- Update visibility if first_begin_of_the_frame and not window.SkipRefresh then -- When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems. + -- This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents. + -- This is analogous to regular windows being hidden from one frame. + -- It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed. if window.DockIsActive and not window.DockTabIsVisible then if window.LastFrameJustFocused == g.FrameCount then window.HiddenFramesCannotSkipItems = 1 @@ -10649,10 +12672,12 @@ function ImGui.Begin(name, open, flags) end end + -- Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) if style.Alpha <= 0.0 then window.HiddenFramesCanSkipItems = 1 end + -- Update the Hidden flag local hidden_regular = (window.HiddenFramesCanSkipItems > 0) or (window.HiddenFramesCannotSkipItems > 0) window.Hidden = hidden_regular or (window.HiddenFramesForRenderOnly > 0) @@ -10676,6 +12701,7 @@ function ImGui.Begin(name, open, flags) window.DC.NavLayersActiveMaskNext = window.DC.NavLayersActiveMask end elseif first_begin_of_the_frame then + -- Skip refresh mode window.SkipItems = true end @@ -10687,6 +12713,7 @@ function ImGui.End() local g = GImGui local window = g.CurrentWindow + -- Error checking: verify that user hasn't called End() too many times! if (g.CurrentWindowStack.Size <= 1 and g.WithinFrameScopeWithImplicitWindow) then IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!") @@ -10694,6 +12721,7 @@ function ImGui.End() end local window_stack_data = g.CurrentWindowStack:back() + -- Error checking: verify that user doesn't directly call End() on a child window. if bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then IM_ASSERT_USER_ERROR(g.WithinEndPopupID == window.ID, "Must call EndPopup() and not End()!") end @@ -10701,10 +12729,11 @@ function ImGui.End() IM_ASSERT_USER_ERROR(g.WithinEndChildID == window.ID, "Must call EndChild() and not End()!") end + -- Close anything that is open if window.DC.CurrentColumns then ImGui.EndColumns() end - if bit32.band(window.Flags, ImGuiWindowFlags.DockNodeHost) == 0 and not window.SkipRefresh then + if bit32.band(window.Flags, ImGuiWindowFlags.DockNodeHost) == 0 and not window.SkipRefresh then -- Pop inner window clip rectangle ImGui.PopClipRect() end ImGui.PopFocusScope() @@ -10733,7 +12762,7 @@ function ImGui.End() -- Docking: report contents sizes to parent to allow for auto-resize if window.DockNode and window.DockTabIsVisible then - local host_window = window.DockNode.HostWindow + local host_window = window.DockNode.HostWindow -- FIXME-DOCK if host_window then ImVec2_Copy(host_window.DC.CursorMaxPos, window.DC.CursorMaxPos + window.WindowPadding - host_window.WindowPadding) end @@ -10791,6 +12820,13 @@ function ImGui.PopItemFlag() g.CurrentItemFlags = g.ItemFlagsStack:back() end +-- BeginDisabled()/EndDisabled() +-- - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled) +-- - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently. +-- - Feedback welcome at https://github.com/ocornut/imgui/issues/211 +-- - BeginDisabled(false)/EndDisabled() essentially does nothing but is provided to facilitate use of boolean expressions. +-- (as a micro-optimization: if you have tens of thousands of BeginDisabled(false)/EndDisabled() pairs, you might want to reformulate your code to avoid making those calls) +-- - Note: mixing up BeginDisabled() and PushItemFlag(ImGuiItemFlags.Disabled) is currently NOT SUPPORTED. --- @param disabled? bool function ImGui.BeginDisabled(disabled) if disabled == nil then disabled = true end @@ -10799,12 +12835,12 @@ function ImGui.BeginDisabled(disabled) local was_disabled = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0 if not was_disabled and disabled then g.DisabledAlphaBackup = g.Style.Alpha - g.Style.Alpha = g.Style.Alpha * g.Style.DisabledAlpha + g.Style.Alpha = g.Style.Alpha * g.Style.DisabledAlpha -- PushStyleVar(ImGuiStyleVar.Alpha, g.Style.Alpha * g.Style.DisabledAlpha) end if was_disabled or disabled then g.CurrentItemFlags = bit32.bor(g.CurrentItemFlags, ImGuiItemFlags.Disabled) end - g.ItemFlagsStack:push_back(g.CurrentItemFlags) + g.ItemFlagsStack:push_back(g.CurrentItemFlags) -- FIXME-OPT: can we simply skip this and use DisabledStackSize? g.DisabledStackSize = g.DisabledStackSize + 1 end @@ -10813,13 +12849,17 @@ function ImGui.EndDisabled() IM_ASSERT_USER_ERROR_RET(g.DisabledStackSize > 0, "Calling EndDisabled() too many times!") g.DisabledStackSize = g.DisabledStackSize - 1 local was_disabled = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0 + -- PopItemFlag() g.ItemFlagsStack:pop_back() g.CurrentItemFlags = g.ItemFlagsStack:back() if was_disabled and bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) == 0 then - g.Style.Alpha = g.DisabledAlphaBackup + g.Style.Alpha = g.DisabledAlphaBackup -- PopStyleVar() end end +-- Could have been called BeginDisabledDisable() but it didn't want to be award nominated for most awkward function name. +-- Ideally we would use a shared e.g. BeginDisabled()->BeginDisabledEx() but earlier needs to be optimal. +-- The whole code for this is awkward, will reevaluate if we find a way to implement SetNextItemDisabled(). function ImGui.BeginDisabledOverrideReenable() local g = GImGui IM_ASSERT(bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0) @@ -10840,6 +12880,12 @@ function ImGui.EndDisabledOverrideReenable() g.Style.Alpha = g.CurrentWindowStack:back().DisabledOverrideReenableAlphaBackup end +-- Find window given position, search front-to-back +-- - Typically write output back to g.HoveredWindow and g.HoveredWindowUnderMovingWindow. +-- - FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically +-- with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is +-- called, aka before the next Begin(). Moving window isn't affected. +-- - The 'find_first_and_in_any_viewport = true' mode is only used by TestEngine. It is simpler to maintain here. --- @param pos ImVec2 --- @param find_first_and_in_any_viewport bool --- @return ImGuiWindow, ImGuiWindow? @@ -10878,6 +12924,8 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) if (window.Viewport ~= g.MouseViewport) then break end + + -- Using the clipped AABB, a child window will typically be clipped by its parent (not always) local hit_padding if bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.NoResize, ImGuiWindowFlags.AlwaysAutoResize)) ~= 0 then hit_padding = padding_regular @@ -10888,6 +12936,8 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) break end + -- Support for one rectangular hole in any given window + -- FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512) if window.HitTestHoleSize.x ~= 0 then local hx, hy = window.Pos.x + window.HitTestHoleOffset.x, window.Pos.y + window.HitTestHoleOffset.y if pos.x >= hx and pos.y >= hy and pos.x < hx + window.HitTestHoleSize.x and pos.y < hy + window.HitTestHoleSize.y then @@ -10924,26 +12974,37 @@ local function FindHoveredWindowEx(pos, find_first_and_in_any_viewport) end -- TODO: +-- 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) function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) local g = GImGui local 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.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. local clear_hovered_windows = false g.HoveredWindow, g.HoveredWindowUnderMovingWindow = FindHoveredWindowEx(mouse_pos, false) IM_ASSERT(g.HoveredWindow == nil or g.HoveredWindow == g.MovingWindow or g.HoveredWindow.Viewport == g.MouseViewport) g.HoveredWindowBeforeClear = g.HoveredWindow + -- Modal windows prevents mouse from hovering behind them. local modal_window = ImGui.GetTopMostPopupModal() - if modal_window and g.HoveredWindow and not ImGui.IsWindowWithinBeginStackOf(g.HoveredWindow.RootWindow, modal_window) then + if modal_window and g.HoveredWindow and not ImGui.IsWindowWithinBeginStackOf(g.HoveredWindow.RootWindow, modal_window) then -- FIXME-MERGE: RootWindowDockTree ? clear_hovered_windows = true end + -- Disabled mouse hovering (we don't currently clear MousePos, we could) if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoMouse) ~= 0 then clear_hovered_windows = true end + -- We track click ownership. When clicked outside of a window the click is owned by the application and + -- won't report hovering nor request capture even while dragging over our windows afterward. local has_open_popup = (g.OpenPopupStack.Size > 0) local has_open_modal = (modal_window ~= nil) local mouse_earliest_down = -1 @@ -10956,7 +13017,7 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) end mouse_any_down = mouse_any_down or io.MouseDown[i] - if (io.MouseDown[i] or io.MouseReleased[i]) then + if (io.MouseDown[i] or io.MouseReleased[i]) then -- Increase release frame for our evaluation of earliest button (#1392) if (mouse_earliest_down == -1 or (io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])) then mouse_earliest_down = i end @@ -10966,6 +13027,8 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) local mouse_avail = (mouse_earliest_down == -1) or io.MouseDownOwned[mouse_earliest_down] local mouse_avail_unless_popup_close = (mouse_earliest_down == -1) or io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down] + -- If mouse was first clicked outside of ImGui bounds we also cancel out hovering. + -- FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) local mouse_dragging_extern_payload = g.DragDropActive and bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceExtern) ~= 0 if not mouse_avail and not mouse_dragging_extern_payload then clear_hovered_windows = true @@ -10976,6 +13039,8 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) g.HoveredWindowUnderMovingWindow = nil end + -- Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app) + -- Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag if (g.WantCaptureMouseNextFrame ~= -1) then io.WantCaptureMouse = (g.WantCaptureMouseNextFrame ~= 0) io.WantCaptureMouseUnlessPopupClose = io.WantCaptureMouse @@ -10984,6 +13049,7 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close and (g.HoveredWindow ~= nil or mouse_any_down)) or has_open_modal end + -- Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app) io.WantCaptureKeyboard = false if bit32.band(io.ConfigFlags, ImGuiConfigFlags.NoKeyboard) == 0 then if (g.ActiveId ~= 0) or (modal_window ~= nil) then @@ -10992,10 +13058,11 @@ function ImGui.UpdateHoveredWindowAndCaptureFlags(mouse_pos) io.WantCaptureKeyboard = true end end - if g.WantCaptureKeyboardNextFrame ~= -1 then + if g.WantCaptureKeyboardNextFrame ~= -1 then -- Manual override io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame ~= 0) end + -- Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible io.WantTextInput = (g.WantTextInputNextFrame ~= -1) and (g.WantTextInputNextFrame ~= 0) or false end @@ -11009,8 +13076,10 @@ function ImGui.UpdateAliasKey(key, v, analog_value) key_data.AnalogValue = analog_value end +-- [Internal] Do not use directly function ImGui.GetMergedModsFromKeys() local g = GImGui + -- Bypass IsKeyDown() for the unlikely case where user used a ImGuiInputFlags.LockXXXX on those. local mods = 0 if ImGui.GetKeyData(g, ImGuiMod_Ctrl).Down then mods = bit32.bor(mods, ImGuiMod_Ctrl) end @@ -11029,13 +13098,17 @@ function ImGui.UpdateKeyboardInputs() io:ClearInputKeys() end + -- Update aliases for n = 0, 2 do -- TODO: ImGuiMouseButton.COUNT - 1 ImGui.UpdateAliasKey(ImGui.MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] and 1.0 or 0.0) end ImGui.UpdateAliasKey(ImGuiKey.MouseWheelX, io.MouseWheelH ~= 0.0, io.MouseWheelH) ImGui.UpdateAliasKey(ImGuiKey.MouseWheelY, io.MouseWheel ~= 0.0, io.MouseWheel) - -- Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values + -- Synchronize io.KeyMods and io.KeyCtrl/io.KeyShift/etc. values. + -- - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) -> -> (here) deriving io.KeyMods + io.KeyXXX from key array. + -- - Legacy backends: set io.KeyXXX bools -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array. + -- So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing. local prev_key_mods = io.KeyMods io.KeyMods = ImGui.GetMergedModsFromKeys() io.KeyCtrl = bit32.band(io.KeyMods, ImGuiMod_Ctrl) ~= 0 @@ -11091,6 +13164,7 @@ function ImGui.UpdateKeyboardInputs() owner_data.LockUntilRelease = owner_data.LockUntilRelease and key_data.Down -- Clear LockUntilRelease when key is not Down anymore end + -- Update key routing (for e.g. shortcuts) ImGui.UpdateKeyRoutingTable(g.KeysRoutingTable) end @@ -11100,7 +13174,9 @@ function ImGui.UpdateMouseInputs() -- Mouse Wheel swapping flag -- As a standard behavior holding Shift while using Vertical Mouse Wheel triggers Horizontal scroll instead - -- - We avoid doing it on OSX as it the OS input layer handles this already + -- - We avoid doing it on OSX as it the OS input layer handles this already. + -- - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature. + -- - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source. io.MouseWheelRequestAxisSwap = io.KeyShift and not io.ConfigMacOSXBehaviors -- Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well) @@ -11119,13 +13195,14 @@ function ImGui.UpdateMouseInputs() io.MouseDelta = ImVec2(0.0, 0.0) end - -- Update stationary timer - -- FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates - local mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource.Mouse) and 2.0 or 3.0 + -- Update stationary timer. + -- FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates. + local mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource.Mouse) and 2.0 or 3.0 -- Slightly higher threshold for ImGuiMouseSource.TouchScreen/ImGuiMouseSource.Pen, may need rework. local mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold) g.MouseStationaryTimer = mouse_stationary and (g.MouseStationaryTimer + io.DeltaTime) or 0.0 + -- IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer) - -- If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0 threshold but would need to reset in everywhere we set this to true. + -- If mouse moved we re-enable mouse hovering in case it was disabled by keyboard/gamepad. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true. if io.MouseDelta.x ~= 0.0 or io.MouseDelta.y ~= 0.0 then g.NavHighlightItemUnderNav = false end @@ -11187,8 +13264,10 @@ function ImGui.UpdateMouseInputs() io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, (delta_from_click_pos.y < 0.0) and -delta_from_click_pos.y or delta_from_click_pos.y) end + -- We provide io.MouseDoubleClicked[] as a legacy service io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2) + -- Clicking any mouse button reactivate mouse hovering which may have been deactivated by keyboard/gamepad navigation if (io.MouseClicked[i]) then g.NavHighlightItemUnderNav = false end @@ -11219,6 +13298,7 @@ end --- @param wheel ImVec2 --- @return ImGuiWindow? local function FindBestWheelingWindow(wheel) + -- For each axis, find window in the hierarchy that may want to use scrolling local g = GImGui local windows = {nil, nil} for axis = ImGuiAxis.X, ImGuiAxis.Y do @@ -11226,10 +13306,15 @@ local function FindBestWheelingWindow(wheel) windows[axis] = g.HoveredWindow local window = g.HoveredWindow while bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 do + -- Bubble up into parent window if: + -- - a child window doesn't allow any scrolling. + -- - a child window has the ImGuiWindowFlags.NoScrollWithMouse flag. + -- -- - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP) local has_scrolling = (window.ScrollMax[axis] ~= 0.0) local inputs_disabled = (bit32.band(window.Flags, ImGuiWindowFlags.NoScrollWithMouse) ~= 0) and not (bit32.band(window.Flags, ImGuiWindowFlags.NoMouseInputs) ~= 0) + -- local scrolling_past_limits = (wheel_v < 0.0) and (window.Scroll[axis] <= 0.0) or (window.Scroll[axis] >= window.ScrollMax[axis]) - if has_scrolling and not inputs_disabled then + if has_scrolling and not inputs_disabled then -- and not scrolling_past_limits break -- select this window end @@ -11242,10 +13327,14 @@ local function FindBestWheelingWindow(wheel) return nil end + -- If there's only one window or only one axis then there's no ambiguity if (windows[1] == windows[2] or windows[1] == nil or windows[2] == nil) then return windows[2] and windows[2] or windows[1] end + -- If candidate are different windows we need to decide which one to prioritize + -- - First frame: only find a winner if one axis is zero. + -- - Subsequent frames: only find a winner when one is more than the other. if (g.WheelingWindowStartFrame == -1) then g.WheelingWindowStartFrame = g.FrameCount end @@ -11257,7 +13346,10 @@ local function FindBestWheelingWindow(wheel) return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) and windows[1] or windows[2] end +-- Called by NewFrame() function ImGui.UpdateMouseWheel() + -- Reset the locked window if we move the mouse or after the timer elapses. + -- FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795) local g = GImGui if g.WheelingWindow ~= nil then g.WheelingWindowReleaseTimer = g.WheelingWindowReleaseTimer - g.IO.DeltaTime @@ -11279,13 +13371,14 @@ function ImGui.UpdateMouseWheel() local wheel = ImVec2() wheel.x = ImGui.TestKeyOwner(ImGuiKey.MouseWheelX, owner_id) and g.IO.MouseWheelH or 0.0 wheel.y = ImGui.TestKeyOwner(ImGuiKey.MouseWheelY, owner_id) and g.IO.MouseWheel or 0.0 + -- IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y) if g.WheelingWindow ~= nil then ImGui.SetKeyOwner(ImGuiKey.MouseWheelX, owner_id) ImGui.SetKeyOwner(ImGuiKey.MouseWheelY, owner_id) end -- Zoom / Scale window - -- FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned + -- FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. if wheel.y ~= 0.0 and g.IO.KeyCtrl and g.IO.FontAllowUserScaling then LockWheelingWindow(mouse_window, wheel.y) local window = mouse_window @@ -11304,6 +13397,7 @@ function ImGui.UpdateMouseWheel() end -- Mouse wheel scrolling + -- Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs() if (g.IO.MouseWheelRequestAxisSwap) then wheel = ImVec2(wheel.y, 0.0) end @@ -11313,7 +13407,7 @@ function ImGui.UpdateMouseWheel() g.WheelingAxisAvg.x = ImStd.ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30) g.WheelingAxisAvg.y = ImStd.ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30) - -- In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now + -- In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now. wheel = wheel + g.WheelingWindowWheelRemainder g.WheelingWindowWheelRemainder = ImVec2(0.0, 0.0) if (wheel.x == 0.0 and wheel.y == 0.0) then @@ -11356,6 +13450,8 @@ function ImGui.UpdateMouseWheel() end end +-- Called once a frame. Followed by SetCurrentFont() which sets up the remaining data. +-- FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal! local function SetupDrawListSharedData() local g = GImGui local virtual_space = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX) @@ -11386,7 +13482,7 @@ local function InitViewportDrawData(viewport) local g = GImGui local draw_data = viewport.DrawDataP - viewport.DrawData = draw_data + viewport.DrawData = draw_data -- Make publicly accessible viewport.DrawDataBuilder.Layers[1] = draw_data.CmdLists viewport.DrawDataBuilder.Layers[2] = viewport.DrawDataBuilder.LayerData1 viewport.DrawDataBuilder.Layers[1]:resize(0) @@ -11419,7 +13515,7 @@ local function InitViewportDrawData(viewport) draw_data.Textures = g.PlatformIO.Textures end --- FIXME-DPI: +-- FIXME-DPI: PLEASE DO NOT USE. I don't want to formalize this just yet. Because reasons. function ImGui.GetScale() local g = GImGui return g.Style._MainScale @@ -11439,6 +13535,14 @@ function ImGui.GetCurrentWindow() return g.CurrentWindow end +-- Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering. +-- - When using this function it is sane to ensure that float are perfectly rounded to integer values, +-- so that e.g. (int)(max.x-min.x) in user's render produce correct result. +-- - 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 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. --- @param clip_rect_min ImVec2 --- @param clip_rect_max ImVec2 --- @param intersect_with_current_clip_rect? bool @@ -11460,6 +13564,7 @@ end --- @param drawlist_name string --- @return ImDrawList local function GetViewportBgFgDrawList(viewport, drawlist_no, drawlist_name) + -- Create the draw list on demand, because they are not frequently used for all viewports local g = GImGui IM_ASSERT(drawlist_no <= 2) -- IM_COUNTOF(viewport->BgFgDrawLists) local draw_list = viewport.BgFgDrawLists[drawlist_no] @@ -11469,6 +13574,7 @@ local function GetViewportBgFgDrawList(viewport, drawlist_no, drawlist_name) viewport.BgFgDrawLists[drawlist_no] = draw_list end + -- Our ImDrawList system requires that there is always a command if viewport.BgFgDrawListsLastTimeActive[drawlist_no] ~= g.Time then draw_list:_ResetForNewFrame() draw_list:PushTexture(g.IO.Fonts.TexRef) @@ -11503,7 +13609,7 @@ function ImGui.GetForegroundDrawList(viewport) return GetViewportBgFgDrawList(viewport, 2, "##Foreground") end --- FIXME: Add a more explicit sort order in the window structure +-- FIXME: Add a more explicit sort order in the window structure. --- @param lhs ImGuiWindow --- @param rhs ImGuiWindow local function ChildWindowComparer(lhs, rhs) @@ -11540,7 +13646,7 @@ local function AddWindowToDrawData(window, layer) local viewport = window.Viewport g.IO.MetricsRenderWindows = g.IO.MetricsRenderWindows + 1 if window.DrawList._Splitter._Count > 1 then - window.DrawList:ChannelsMerge() -- Merge if user forgot to merge back. Also required for DockNodeHost windows. + window.DrawList:ChannelsMerge() -- Merge if user forgot to merge back. Also required in Docking branch for ImGuiWindowFlags.DockNodeHost windows. end ImGui.AddDrawListToDrawDataEx(viewport.DrawDataP, viewport.DrawDataBuilder.Layers[layer], window.DrawList) for _, child in window.DC.ChildWindows:iter() do @@ -11555,6 +13661,7 @@ local function GetWindowDisplayLayer(window) return (bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0) and 2 or 1 end +-- Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu) --- @param window ImGuiWindow local function AddRootWindowToDrawData(window) AddWindowToDrawData(window, GetWindowDisplayLayer(window)) @@ -11602,6 +13709,7 @@ function ImGui.NewFrame() g.WindowsActiveCount = 0 g.MenusIdSubmittedThisFrame:resize(0) + -- Calculate frame-rate for the user, as a purely luxurious feature -- FIXME: are lines below correct and necessary g.FramerateSecPerFrameAccum = g.FramerateSecPerFrameAccum + (g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]) g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime @@ -11613,12 +13721,16 @@ function ImGui.NewFrame() g.IO.Framerate = FLT_MAX end + -- Process input queue (trickle as many events as possible), turn events into writes to IO structure ImGui.UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue) + -- Update viewports (after processing input queue, so io.MouseHoveredViewport is set) ImGui.UpdateViewportsNewFrame() + -- Update texture list (collect destroyed textures, etc.) ImGui.UpdateTexturesNewFrame() + -- Setup current font and draw list shared data SetupDrawListSharedData() ImGui.UpdateFontsNewFrame() @@ -11630,11 +13742,13 @@ function ImGui.NewFrame() viewport.DrawDataP.Valid = false end + -- Drag and drop keep the source ID alive so even if the source disappear our state is consistent if g.DragDropActive and g.DragDropPayload.SourceId == g.ActiveId then ImGui.KeepAliveID(g.DragDropPayload.SourceId) end - if not g.IO.ConfigDebugHighlightIdConflicts or not g.IO.KeyCtrl then + -- [DEBUG] + if not g.IO.ConfigDebugHighlightIdConflicts or not g.IO.KeyCtrl then -- Count is locked while holding Ctrl g.DebugDrawIdConflictsId = 0 end if g.IO.ConfigDebugHighlightIdConflicts and g.HoveredIdPreviousFrameItemCount > 1 then @@ -11660,6 +13774,9 @@ function ImGui.NewFrame() g.HoveredIdAllowOverlap = false g.HoveredIdIsDisabled = false + -- Clear ActiveID if the item is not alive anymore. + -- In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd(). + -- As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves. if (g.ActiveId ~= 0 and g.ActiveIdIsAlive ~= g.ActiveId and g.ActiveIdPreviousFrame == g.ActiveId) then IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() 0x%08X because it isn't marked alive anymore!", g.ActiveId) @@ -11729,8 +13846,18 @@ function ImGui.NewFrame() end end + -- Close popups on focus lost (currently wip/opt-in) + -- if (g.IO.AppFocusLost) + -- ClosePopupsExceptModals(); + + -- Update keyboard input state ImGui.UpdateKeyboardInputs() + -- IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl)); + -- IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift)); + -- IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt)); + -- IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper)); + -- Drag and drop g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr g.DragDropAcceptIdCurr = 0 @@ -11741,6 +13868,10 @@ function ImGui.NewFrame() g.DragDropWithinTarget = false g.DragDropHoldJustPressedId = 0 if g.DragDropActive then + -- Also works when g.ActiveId==0 (aka leftover payload in progress, no active id) + -- You may disable this externally by hijacking the input route: + -- 'if (GetDragDropPayload() ~= nil) then Shortcut(ImGuiKey.Escape, ImGuiInputFlags.RouteGlobal | ImGuiInputFlags.RouteOverActive) end + -- but you will not get a return value from Shortcut() due to ActiveIdUsingAllKeyboardKeys logic. You can however poll IsKeyPressed(ImGuiKey.Escape) afterwards. local owner_id = (g.ActiveId ~= 0) and g.ActiveId or ImHashStr("##DragDropCancelHandler") if ImGui.Shortcut(ImGuiKey.Escape, ImGuiInputFlags.RouteGlobal, owner_id) then ImGui.ClearActiveID() @@ -11749,14 +13880,17 @@ function ImGui.NewFrame() end g.TooltipPreviousWindow = nil + -- Update keyboard/gamepad navigation ImGui.NavUpdate() + -- Update mouse input state ImGui.UpdateMouseInputs() -- Undocking -- (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame) ImGui.DockContextNewFrameUpdateUndocking(g) + -- Mark all windows as not visible and compact unused memory. IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size) local gc_all = g.GcCompactAll or g.IO.ConfigMemoryCompactTimer < 0.0 local memory_compact_start_time = gc_all and FLT_MAX or (g.Time - g.IO.ConfigMemoryCompactTimer) @@ -11768,13 +13902,18 @@ function ImGui.NewFrame() window.BeginCountPreviousFrame = window.BeginCount window.BeginCount = 0 + -- Garbage collect transient buffers of recently unused windows if (not window.WasActive or gc_all) and not window.MemoryCompacted and window.LastTimeActive < memory_compact_start_time then ImGui.GcCompactTransientWindowBuffers(window) end end + -- 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) ImGui.UpdateHoveredWindowAndCaptureFlags(g.IO.MousePos) + -- Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) ImGui.UpdateMouseMovingWindowNewFrame() -- Background darkening/whitening @@ -11794,6 +13933,7 @@ function ImGui.NewFrame() g.PlatformImeData.WantVisible = false g.PlatformImeData.WantTextInput = false + -- Mouse wheel scrolling, scale ImGui.UpdateMouseWheel() -- Garbage collect transient buffers of recently unused tables @@ -11813,14 +13953,17 @@ function ImGui.NewFrame() end g.GcCompactAll = false + -- Closing the focused window restore focus to the first active root window in descending z-order if (g.NavWindow and not g.NavWindow.WasActive) then ImGui.FocusTopMostWindowUnderOne(nil, nil, nil, ImGuiFocusRequestFlags.RestoreFocusedChild) end + -- No window should be open at the beginning of the frame. + -- But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack:resize(0) g.BeginPopupStack:resize(0) g.ItemFlagsStack:resize(0) - g.ItemFlagsStack:push_back(ImGuiItemFlags.Default_) + g.ItemFlagsStack:push_back(ImGuiItemFlags.Default_) -- Default flags g.CurrentItemFlags = g.ItemFlagsStack:back() g.GroupStack:resize(0) @@ -11830,6 +13973,9 @@ function ImGui.NewFrame() -- Docking ImGui.DockContextNewFrameUpdateDocking(g) + -- Create implicit/fallback window - which we will only render it if the user has added something to it. + -- We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. + -- This fallback is particularly important as it prevents ImGui:: calls from crashing. g.WithinFrameScopeWithImplicitWindow = true ImGui.SetNextWindowSize(ImVec2(400, 400), ImGuiCond.FirstUseEver) ImGui.Begin("Debug##Default") @@ -11841,10 +13987,12 @@ function ImGui.NewFrame() ImGui.ErrorRecoveryStoreState(g.StackSizesInNewFrame) end +-- This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. function ImGui.EndFrame() local g = GImGui IM_ASSERT(g.Initialized) + -- Don't process EndFrame() multiple times. if g.FrameCountEnded == g.FrameCount then return end @@ -11856,7 +14004,7 @@ function ImGui.EndFrame() end ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() - -- Notify Platform when our Input Method Editor cursor has moved + -- Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) local ime_data = g.PlatformImeData if g.PlatformIO.Platform_SetImeDataFn ~= nil and not ImGuiPlatformImeData_Compare(ime_data, g.PlatformImeDataPrev) then local viewport = ImGui.FindViewportByID(ime_data.ViewportId) @@ -11868,6 +14016,7 @@ function ImGui.EndFrame() end g.WantTextInputNextFrame = ime_data.WantTextInput + -- Hide implicit/fallback "Debug" window if it hasn't been used g.WithinFrameScopeWithImplicitWindow = false if (g.CurrentWindow and g.CurrentWindow.IsFallbackWindow and g.CurrentWindow.WriteAccessed == false) then g.CurrentWindow.Active = false @@ -11900,14 +14049,19 @@ function ImGui.EndFrame() g.DragDropWithinSource = false end + -- End frame g.WithinFrameScope = false g.FrameCountEnded = g.FrameCount ImGui.UpdateFontsEndFrame() + -- Initiate moving window + handle left-click and right-click focus ImGui.UpdateMouseMovingWindowEndFrame() + -- Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) ImGui.UpdateViewportsEndFrame() + -- Sort the window list so that all child windows are after their parent + -- We cannot do that on FocusWindow() because children may not exist yet g.WindowsTempSortBuffer:resize(0) g.WindowsTempSortBuffer:reserve(g.Windows.Size) for _, window in g.Windows:iter() do @@ -11921,16 +14075,19 @@ function ImGui.EndFrame() until true end + -- This usually assert if there is a mismatch between the ImGuiWindowFlags.ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong. IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size) g.Windows:swap(g.WindowsTempSortBuffer) g.IO.MetricsActiveWindows = g.WindowsActiveCount ImGui.UpdateTexturesEndFrame() + -- Unlock font atlas for _, atlas in g.FontAtlases:iter() do atlas.Locked = false end + -- Clear Input data for next frame ImVec2_Copy(g.IO.MousePosPrev, g.IO.MousePos) g.IO.AppFocusLost = false g.IO.MouseWheel = 0.0 @@ -11939,6 +14096,9 @@ function ImGui.EndFrame() end -- TODO: +-- Prepare the data for rendering so you can call GetDrawData() +-- (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) function ImGui.Render() local g = GImGui IM_ASSERT(g.Initialized) @@ -11951,6 +14111,7 @@ function ImGui.Render() g.IO.MetricsRenderWindows = 0 + -- Add background ImDrawList (for each active viewport) for _, viewport in g.Viewports:iter() do InitViewportDrawData(viewport) if viewport.BgFgDrawLists[1] ~= nil and viewport.BgFgDrawListsLastTimeActive[1] == g.Time then @@ -11958,8 +14119,10 @@ function ImGui.Render() end end + -- Draw modal/window whitening backgrounds ImGui.RenderDimmedBackgrounds() + -- Add ImDrawList to render local windows_to_render_top_most = {nil, nil} windows_to_render_top_most[1] = (g.NavWindowingTarget and (bit32.band(g.NavWindowingTarget.Flags, ImGuiWindowFlags.NoBringToFrontOnFocus) == 0)) and g.NavWindowingTarget.RootWindowDockTree or nil windows_to_render_top_most[2] = g.NavWindowingTarget and g.NavWindowingListWindow or nil @@ -11979,15 +14142,18 @@ function ImGui.Render() ImGui.RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48)) end + -- Setup ImDrawData structures for end-user g.IO.MetricsRenderVertices = 0 g.IO.MetricsRenderIndices = 0 for _, viewport in g.Viewports:iter() do FlattenDrawDataIntoSingleLayer(viewport.DrawDataBuilder) + -- Add foreground ImDrawList (for each active viewport) if viewport.BgFgDrawLists[2] ~= nil and viewport.BgFgDrawListsLastTimeActive[2] == g.Time then ImGui.AddDrawListToDrawDataEx(viewport.DrawDataP, viewport.DrawDataBuilder.Layers[1], ImGui.GetForegroundDrawList(viewport)) end + -- We call _PopUnusedDrawCmd() last thing, as RenderDimmedBackgrounds() rely on a valid command being there (especially in docking branch). local draw_data = viewport.DrawDataP for _, draw_list in draw_data.CmdLists:iter() do draw_list:_PopUnusedDrawCmd() @@ -11998,6 +14164,8 @@ function ImGui.Render() end end +-- Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. +-- CalcTextSize("") should return ImVec2(0.0, g.FontSize) --- @param text ImString --- @param text_end? int # Exclusive upper bound --- @param hide_text_after_double_hash? bool @@ -12023,7 +14191,7 @@ function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double local text_display_end if hide_text_after_double_hash then - text_display_end = ImGui.FindRenderedTextEnd(text, text_end) + text_display_end = ImGui.FindRenderedTextEnd(text, text_end) -- Hide anything after a '##' string else text_display_end = text_end end @@ -12035,11 +14203,15 @@ function ImGui.CalcTextSizeEx(text, text_begin, text_end, hide_text_after_double end local text_size = font:CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_begin, text_display_end, nil) + -- Round + -- (see 7b0bf230, 4622fa4b6, #791 for details about this.) + -- FIXME: Add a way to disable this. text_size.x = ImCeilFast(text_size.x) return text_size end +-- Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame() function ImGui.GetDrawData() local g = GImGui local viewport = g.Viewports[1] @@ -12050,6 +14222,7 @@ function ImGui.GetTime() return GImGui.Time end +-- This function is merely here to free heap allocations. function ImGui.Shutdown() local g = GImGui IM_ASSERT_USER_ERROR(g.IO.BackendPlatformUserData == nil, "Forgot to shutdown Platform backend?") @@ -12059,6 +14232,7 @@ function ImGui.Shutdown() IM_ASSERT_USER_ERROR(viewport.RendererUserData == nil and viewport.PlatformUserData == nil and viewport.PlatformHandle == nil, "Backend or app forgot to call DestroyPlatformWindows()?") end + -- 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) for _, atlas in g.FontAtlases:iter() do ImGui.UnregisterFontAtlas(atlas) if atlas.OwnerContext == g then @@ -12070,16 +14244,20 @@ function ImGui.Shutdown() end g.DrawListSharedData.TempBuffer:clear() + -- Shutdown extensions ImGui.DockContextShutdown(g) + -- Cleanup of other data are conditional on actually having initialized Dear ImGui. if not g.Initialized then return end -- TODO: + -- Clear everything else g.MenusIdSubmittedThisFrame:clear() end +-- A conformant backend should return nil on failure (e.g. clipboard data is not text). --- @return string? function ImGui.GetClipboardText() local g = GImGui @@ -12102,17 +14280,29 @@ function ImGui.GetPlatformIO() return GImGui.PlatformIO end +-- Get desired mouse cursor shape. +-- Important: this is meant to be used by a platform backend, it is reset in ImGui.NewFrame(), +-- updated during the frame, and locked in EndFrame()/Render(). +-- If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you function ImGui.GetMouseCursor() local g = GImGui return g.MouseCursor end +-- We intentionally accept values of ImGuiMouseCursor that are outside our bounds, in case users needs to hack-in a custom cursor value. +-- Custom cursors may be handled by custom backends. If you are using a standard backend and want to hack in a custom cursor, you may +-- handle it before the backend _NewFrame() call and temporarily set ImGuiConfigFlags.NoMouseCursorChange during the backend _NewFrame() call. --- @param cursor_type ImGuiMouseCursor function ImGui.SetMouseCursor(cursor_type) local g = GImGui g.MouseCursor = cursor_type end +------------------------------------------------------------------------------- +-- [SECTION] MISC HELPERS/UTILITIES (Color functions) +-- Note: The Convert functions are early design which are not consistent with other API. +------------------------------------------------------------------------------- + --- @param col_a ImU32 --- @param col_b ImU32 --- @return ImU32 @@ -12150,6 +14340,8 @@ function ImGui.ColorConvertFloat4ToU32(in_col) return bit32.bor(F32ToU8Sat(in_col.x), bit32.lshift(F32ToU8Sat(in_col.y), 8), bit32.lshift(F32ToU8Sat(in_col.z), 16), bit32.lshift(F32ToU8Sat(in_col.w), 24)) end +-- Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 +-- Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv --- @param r float --- @param g float --- @param b float @@ -12173,6 +14365,8 @@ function ImGui.ColorConvertRGBtoHSV(r, g, b) return out_h, out_s, out_v end +-- Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 +-- also http://en.wikipedia.org/wiki/HSL_and_HSV --- @param h float --- @param s float --- @param v float @@ -12206,6 +14400,7 @@ function ImGui.ColorConvertHSVtoRGB(h, s, v) end end +-- Generic helper, equivalent to old ImGui.CalcListClipping() but stateless --- @param clip_rect ImRect --- @param pos ImVec2 --- @param items_height float @@ -12215,9 +14410,9 @@ function ImGui.CalcClipRectVisibleItemsY(clip_rect, pos, items_height) return visible_start + 1, visible_end + 1 end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] STYLING ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.GetStyle() IM_ASSERT(GImGui ~= nil, "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?") @@ -12262,6 +14457,7 @@ end end +-- FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32 --- @param idx ImGuiCol --- @param col ImU32|ImVec4 function ImGui.PushStyleColor(idx, col) @@ -12296,57 +14492,57 @@ function ImGui.PopStyleColor(count) end local GStyleVarsInfo = { - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "Alpha"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DisabledAlpha"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowPadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowMinSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowTitleAlign"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "FramePadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemSpacing"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemInnerSpacing"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "IndentSpacing"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "CellPadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarPadding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabMinSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthBase"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthShrink"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarBorderSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarOverlineSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TableAngledHeadersAngle"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "TableAngledHeadersTextAlign"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "MenuItemRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SelectableRounding"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DragDropTargetRounding"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ButtonTextAlign"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SelectableTextAlign"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorSize"), - ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorTextBorderSize"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextAlign"), - ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextPadding") + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "Alpha"), -- ImGuiStyleVar.Alpha + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DisabledAlpha"), -- ImGuiStyleVar.DisabledAlpha + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowPadding"), -- ImGuiStyleVar.WindowPadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowRounding"), -- ImGuiStyleVar.WindowRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "WindowBorderSize"), -- ImGuiStyleVar.WindowBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowMinSize"), -- ImGuiStyleVar.WindowMinSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "WindowTitleAlign"), -- ImGuiStyleVar.WindowTitleAlign + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildRounding"), -- ImGuiStyleVar.ChildRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ChildBorderSize"), -- ImGuiStyleVar.ChildBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupRounding"), -- ImGuiStyleVar.PopupRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "PopupBorderSize"), -- ImGuiStyleVar.PopupBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "FramePadding"), -- ImGuiStyleVar.FramePadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameRounding"), -- ImGuiStyleVar.FrameRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "FrameBorderSize"), -- ImGuiStyleVar.FrameBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemSpacing"), -- ImGuiStyleVar.ItemSpacing + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ItemInnerSpacing"), -- ImGuiStyleVar.ItemInnerSpacing + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "IndentSpacing"), -- ImGuiStyleVar.IndentSpacing + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "CellPadding"), -- ImGuiStyleVar.CellPadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarSize"), -- ImGuiStyleVar.ScrollbarSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarRounding"), -- ImGuiStyleVar.ScrollbarRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ScrollbarPadding"), -- ImGuiStyleVar.ScrollbarPadding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabMinSize"), -- ImGuiStyleVar.GrabMinSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "GrabRounding"), -- ImGuiStyleVar.GrabRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageRounding"), -- ImGuiStyleVar.ImageRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "ImageBorderSize"), -- ImGuiStyleVar.ImageBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabRounding"), -- ImGuiStyleVar.TabRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBorderSize"), -- ImGuiStyleVar.TabBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthBase"), -- ImGuiStyleVar.TabMinWidthBase + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabMinWidthShrink"), -- ImGuiStyleVar.TabMinWidthShrink + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarBorderSize"), -- ImGuiStyleVar.TabBarBorderSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TabBarOverlineSize"), -- ImGuiStyleVar.TabBarOverlineSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TableAngledHeadersAngle"), -- ImGuiStyleVar.TableAngledHeadersAngle + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "TableAngledHeadersTextAlign"), -- ImGuiStyleVar.TableAngledHeadersTextAlign + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesSize"), -- ImGuiStyleVar.TreeLinesSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "TreeLinesRounding"), -- ImGuiStyleVar.TreeLinesRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "MenuItemRounding"), -- ImGuiStyleVar.MenuItemRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SelectableRounding"), -- ImGuiStyleVar.SelectableRounding + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "DragDropTargetRounding"), -- ImGuiStyleVar.DragDropTargetRounding + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "ButtonTextAlign"), -- ImGuiStyleVar.ButtonTextAlign + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SelectableTextAlign"), -- ImGuiStyleVar.SelectableTextAlign + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorSize"), -- ImGuiStyleVar.SeparatorSize + ImGuiStyleVarInfo(1, ImGuiDataType.Float, "SeparatorTextBorderSize"), -- ImGuiStyleVar.SeparatorTextBorderSize + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextAlign"), -- ImGuiStyleVar.SeparatorTextAlign + ImGuiStyleVarInfo(2, ImGuiDataType.Float, "SeparatorTextPadding") -- ImGuiStyleVar.SeparatorTextPadding } --- @param idx ImGuiStyleVar --- @return ImGuiStyleVarInfo function ImGui.GetStyleVarInfo(idx) IM_ASSERT(idx >= 0 and idx < ImGuiStyleVar.COUNT) - -- IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar_COUNT) + -- IM_STATIC_ASSERT(IM_COUNTOF(GStyleVarsInfo) == ImGuiStyleVar.COUNT) return GStyleVarsInfo[idx + 1] end @@ -12414,8 +14610,9 @@ function ImGui.PopStyleVar(count) end end +-- ATTENTION THIS IS IN LEGACY LOCAL SPACE. --- @param wrap_local_pos_x float -function ImGui.PushTextWrapPos(wrap_local_pos_x) -- ATTENTION: THIS IS IN LEGACY LOCAL SPACE. +function ImGui.PushTextWrapPos(wrap_local_pos_x) local g = GImGui local window = g.CurrentWindow window.DC.TextWrapPosStack:push_back(window.DC.TextWrapPos) @@ -12505,7 +14702,7 @@ end function ImGui.IsWindowAbove(potential_above, potential_below) local g = GImGui - -- It would be saner to ensure that display layer is always reflected in the g.Windows order, which would likely requires altering all manipulations of that array + -- It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array local display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below) if display_layer_delta ~= 0 then return display_layer_delta > 0 @@ -12524,6 +14721,9 @@ function ImGui.IsWindowAbove(potential_above, potential_below) end -- Is current window hovered and hoverable (e.g. not blocked by a popup/modal)? See ImGuiHoveredFlags for options. +-- IMPORTANT: If you are trying to check whether your mouse should be dispatched to Dear ImGui or to your underlying app, +-- you should not use this function! Use the 'io.WantCaptureMouse' boolean for that! +-- Refer to FAQ entry "How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?" for details. --- @param flags? ImGuiHoveredFlags function ImGui.IsWindowHovered(flags) if flags == nil then flags = 0 end @@ -12564,6 +14764,11 @@ function ImGui.IsWindowHovered(flags) end end + -- When changing hovered window we requires a bit of stationary delay before activating hover timer. + -- FIXME: We don't support delay other than stationary one for now, other delay would need a way + -- to fulfill the possibility that multiple IsWindowHovered() with varying flag could return true + -- for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache. + -- We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow. if bit32.band(flags, ImGuiHoveredFlags.ForTooltip) ~= 0 then flags = ApplyHoverFlagsForTooltip(flags, g.Style.HoverFlagsForTooltipMouse) end @@ -12613,11 +14818,12 @@ local function ScaleWindow(window, scale) ImVec2_Copy(window.ContentSize, ImTrunc(window.ContentSize * scale)) end +-- Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!) --- @param viewport ImGuiViewportP --- @param scale float function ImGui.ScaleWindowsInViewport(viewport, scale) local g = GImGui - -- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X", viewport.ID) + -- IMGUI_DEBUG_LOG_VIEWPORT("[viewport] ScaleWindowsInViewport 0x%08X\n", viewport.ID) if viewport.Window then ScaleWindow(viewport.Window, scale) @@ -12630,10 +14836,14 @@ function ImGui.ScaleWindowsInViewport(viewport, scale) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] SCROLLING ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Helper to snap on edges when aiming at an item very close to the edge, +-- So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling. +-- When we refactor the scrolling API this may be configurable with a flag? +-- Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default. --- @param target float --- @param snap_min float --- @param snap_max float @@ -12677,6 +14887,7 @@ function CalcNextScrollFromScrollTargetAndClamp(window) return scroll end +-- Scroll to keep newly navigated item fully into view --- @param window ImGuiWindow --- @param item_rect ImRect --- @param flags? ImGuiScrollFlags @@ -12687,10 +14898,14 @@ function ImGui.ScrollToRectEx(window, item_rect, flags) local scroll_rect = ImRect(window.InnerRect.Min - ImVec2(1, 1), window.InnerRect.Max + ImVec2(1, 1)) scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window.DecoInnerSizeX1, scroll_rect.Max.x) scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window.DecoInnerSizeY1, scroll_rect.Max.y) + -- GetForegroundDrawList(window):AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0, 0, 5.0) -- [DEBUG] + -- GetForegroundDrawList(window):AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE) -- [DEBUG] + -- Check that only one behavior is selected per axis IM_ASSERT(bit32.band(flags, ImGuiScrollFlags.MaskX_) == 0 or ImIsPowerOfTwo(bit32.band(flags, ImGuiScrollFlags.MaskX_))) IM_ASSERT(bit32.band(flags, ImGuiScrollFlags.MaskY_) == 0 or ImIsPowerOfTwo(bit32.band(flags, ImGuiScrollFlags.MaskY_))) + -- Defaults local in_flags = flags if bit32.band(flags, ImGuiScrollFlags.MaskX_) == 0 and window.ScrollbarX then flags = bit32.bor(flags, ImGuiScrollFlags.KeepVisibleEdgeX) @@ -12735,7 +14950,9 @@ function ImGui.ScrollToRectEx(window, item_rect, flags) local next_scroll = CalcNextScrollFromScrollTargetAndClamp(window) local delta_scroll = next_scroll - window.Scroll + -- Also scroll parent window to keep us into view if necessary if bit32.band(flags, ImGuiScrollFlags.NoScrollParent) == 0 and bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then + -- FIXME-SCROLL: May be an option? if bit32.band(in_flags, bit32.bor(ImGuiScrollFlags.AlwaysCenterX, ImGuiScrollFlags.KeepVisibleCenterX)) ~= 0 then in_flags = bit32.bor(bit32.band(in_flags, bit32.bnot(ImGuiScrollFlags.MaskX_)), ImGuiScrollFlags.KeepVisibleEdgeX) end @@ -12780,6 +14997,7 @@ function ImGui.ScrollToRect(window, item_rect, flags) ImGui.ScrollToRectEx(window, item_rect, flags or 0) end +-- center_x_ratio: 0.0 left of last item, 0.5 horizontal center of last item, 1.0 right of last item. --- @param center_x_ratio? float function ImGui.SetScrollHereX(center_x_ratio) if center_x_ratio == nil then center_x_ratio = 0.5 end @@ -12787,10 +15005,13 @@ function ImGui.SetScrollHereX(center_x_ratio) local window = g.CurrentWindow local spacing_x = ImMax(window.WindowPadding.x, g.Style.ItemSpacing.x) local target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio) - ImGui.SetScrollFromPosX(window, target_pos_x - window.Pos.x, center_x_ratio) + ImGui.SetScrollFromPosX(window, target_pos_x - window.Pos.x, center_x_ratio) -- Convert from absolute to local pos + + -- Tweak: snap on edges when aiming at an item very close to the edge window.ScrollTargetEdgeSnapDist.x = ImMax(0.0, window.WindowPadding.x - spacing_x) end +-- center_y_ratio: 0.0 top of last item, 0.5 vertical center of last item, 1.0 bottom of last item. --- @param center_y_ratio? float function ImGui.SetScrollHereY(center_y_ratio) if center_y_ratio == nil then center_y_ratio = 0.5 end @@ -12798,7 +15019,9 @@ function ImGui.SetScrollHereY(center_y_ratio) local window = g.CurrentWindow local spacing_y = ImMax(window.WindowPadding.y, g.Style.ItemSpacing.y) local target_pos_y = ImLerp(window.DC.CursorPosPrevLine.y - spacing_y, window.DC.CursorPosPrevLine.y + window.DC.PrevLineSize.y + spacing_y, center_y_ratio) - ImGui.SetScrollFromPosY(window, target_pos_y - window.Pos.y, center_y_ratio) + ImGui.SetScrollFromPosY(window, target_pos_y - window.Pos.y, center_y_ratio) -- Convert from absolute to local pos + + -- Tweak: snap on edges when aiming at an item very close to the edge window.ScrollTargetEdgeSnapDist.y = ImMax(0.0, window.WindowPadding.y - spacing_y) end @@ -12821,6 +15044,16 @@ function ImGui.SetScrollY(window, scroll_y) window.ScrollTargetEdgeSnapDist.y = 0.0 end +-- Note that a local position will vary depending on initial scroll value, +-- This is a little bit confusing so bear with us: +-- - local_pos = (absolution_pos - window.Pos) +-- - So local_x/local_y are 0.0 for a position at the upper-left corner of a window, +-- and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area. +-- - They mostly exist because of legacy API. +-- Following the rules above, when trying to work with scrolling code, consider that: +-- - SetScrollFromPosY(0.0) == SetScrollY(0.0 + scroll.y) == has no effect! +-- - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0) == reset scroll. Of course writing SetScrollY(0.0) directly then makes more sense +-- We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size --- @param window ImGuiWindow --- @param local_x float --- @param center_x_ratio float @@ -12828,7 +15061,7 @@ function ImGui.SetScrollFromPosX(window, local_x, center_x_ratio) if type(window) == "number" then window, local_x, center_x_ratio = GImGui.CurrentWindow, window, local_x end if center_x_ratio == nil then center_x_ratio = 0.5 end IM_ASSERT(center_x_ratio >= 0.0 and center_x_ratio <= 1.0) - window.ScrollTarget.x = IM_TRUNC(local_x - window.DecoOuterSizeX1 - window.DecoInnerSizeX1 + window.Scroll.x) + window.ScrollTarget.x = IM_TRUNC(local_x - window.DecoOuterSizeX1 - window.DecoInnerSizeX1 + window.Scroll.x) -- Convert local position to scroll offset window.ScrollTargetCenterRatio.x = center_x_ratio window.ScrollTargetEdgeSnapDist.x = 0.0 end @@ -12840,14 +15073,14 @@ function ImGui.SetScrollFromPosY(window, local_y, center_y_ratio) if type(window) == "number" then window, local_y, center_y_ratio = GImGui.CurrentWindow, window, local_y end if center_y_ratio == nil then center_y_ratio = 0.5 end IM_ASSERT(center_y_ratio >= 0.0 and center_y_ratio <= 1.0) - window.ScrollTarget.y = IM_TRUNC(local_y - window.DecoOuterSizeY1 - window.DecoInnerSizeY1 + window.Scroll.y) + window.ScrollTarget.y = IM_TRUNC(local_y - window.DecoOuterSizeY1 - window.DecoInnerSizeY1 + window.Scroll.y) -- Convert local position to scroll offset window.ScrollTargetCenterRatio.y = center_y_ratio window.ScrollTargetEdgeSnapDist.y = 0.0 end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] TOOLTIPS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- @param tooltip_flags ImGuiTooltipFlags --- @param extra_window_flags ImGuiWindowFlags @@ -12856,6 +15089,12 @@ function ImGui.BeginTooltipEx(tooltip_flags, extra_window_flags) local is_dragdrop_tooltip = g.DragDropWithinSource or g.DragDropWithinTarget if is_dragdrop_tooltip then + -- Drag and Drop tooltips are positioning differently than other tooltips: + -- - 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 positioning logic of other tooltips (not drag and drop ones). + -- local tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding local is_touchscreen = (g.IO.MouseSource == ImGuiMouseSource.TouchScreen) if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) == 0 then @@ -12872,10 +15111,12 @@ function ImGui.BeginTooltipEx(tooltip_flags, extra_window_flags) local bg_alpha = g.Style.Colors[ImGuiCol.PopupBg].w * 0.60 ImGui.SetNextWindowBgAlpha(bg_alpha) + -- PushStyleVar(ImGuiStyleVar.Alpha, g.Style.Alpha * 0.60) -- This would be nice but e.g ColorButton with checkerboard has issue with transparent colors :( tooltip_flags = bit32.bor(tooltip_flags, ImGuiTooltipFlags.OverridePrevious) end + -- Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. if (bit32.band(tooltip_flags, ImGuiTooltipFlags.OverridePrevious) ~= 0) and g.TooltipPreviousWindow ~= nil and g.TooltipPreviousWindow.Active and not ImGui.IsWindowInBeginStack(g.TooltipPreviousWindow) then -- IMGUI_DEBUG_LOG("[tooltip] '%s' already active, using +1 for this frame\n", window_name) ImGui.SetWindowHiddenAndSkipItemsForCurrentFrame(g.TooltipPreviousWindow) @@ -12888,7 +15129,11 @@ function ImGui.BeginTooltipEx(tooltip_flags, extra_window_flags) local flags = bit32.bor(ImGuiWindowFlags.Tooltip, ImGuiWindowFlags.NoInputs, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.AlwaysAutoResize) ImGui.Begin(window_name, nil, bit32.bor(flags, extra_window_flags)) - + -- 2023-03-09: Added bool return value to the API, but currently always returning true. + -- If this ever returns false we need to update BeginDragDropSource() accordingly. + -- if (!ret) + -- End(); + -- return ret; return true end @@ -12918,6 +15163,8 @@ function ImGui.SetTooltip(fmt, ...) ImGui.EndTooltip() end +-- Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'. +-- Defaults to == ImGuiHoveredFlags.Stationary | ImGuiHoveredFlags.DelayShort when using the mouse. --- @param fmt string --- @param ... any function ImGui.SetItemTooltip(fmt, ...) @@ -12926,10 +15173,23 @@ function ImGui.SetItemTooltip(fmt, ...) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] POPUPS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- 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 nil +-- Notes: +-- - FindBlockingModal(nil) == nil is generally equivalent to GetTopMostPopupModal() == nil. +-- Only difference is here we check for .Active/WasActive but it may be unnecessary. --- @param window? ImGuiWindow function ImGui.FindBlockingModal(window) local g = GImGui @@ -12937,6 +15197,7 @@ function ImGui.FindBlockingModal(window) return nil end + -- Find a modal that has common parent with specified window. Specified window should be positioned behind that modal. for i = 1, g.OpenPopupStack.Size do repeat local popup_data = g.OpenPopupStack.Data[i] @@ -12944,17 +15205,17 @@ function ImGui.FindBlockingModal(window) if popup_window == nil or bit32.band(popup_window.Flags, ImGuiWindowFlags.Modal) == 0 then break end - if not popup_window.Active and not popup_window.WasActive then + if not popup_window.Active and not popup_window.WasActive then -- Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows. break end - if window == nil then + if window == nil then -- FindBlockingModal(nil) test for if FocusWindow(nil) is naturally possible via a mouse click. return popup_window end - if ImGui.IsWindowWithinBeginStackOf(window, popup_window) then + if ImGui.IsWindowWithinBeginStackOf(window, popup_window) then -- Window may be over modal break end - do return popup_window end + do return popup_window end -- Place window right below first block modal until true end @@ -12976,6 +15237,12 @@ function ImGui.OpenPopup(id, popup_flags) end end +-- Mark popup as open (toggle toward open state). +-- - Return true when the popup is toggled open, which allows you to capture local state if needed. +-- You may also call IsWindowAppearing() inside the later BeginPopup() scope if you need to prepare/compute data for the popup. +-- - Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. +-- - Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). +-- - One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to nil). --- @param id ImGuiID --- @param popup_flags ImGuiPopupFlags function ImGui.OpenPopupEx(id, popup_flags) @@ -12989,7 +15256,7 @@ function ImGui.OpenPopupEx(id, popup_flags) end end - local popup_ref = ImGuiPopupData() + local popup_ref = ImGuiPopupData() -- Tagged as new ref as Window will be set back to nil if we write this into OpenPopupStack. popup_ref.PopupId = id popup_ref.Window = nil popup_ref.RestoreNavWindow = g.NavWindow -- When popup closes focus may be restored to NavWindow (depend on window type). @@ -13002,7 +15269,7 @@ function ImGui.OpenPopupEx(id, popup_flags) ImVec2_Copy(popup_ref.OpenMousePos, popup_ref.OpenPopupPos) end - -- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)", id) + -- IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id) if g.OpenPopupStack.Size < current_stack_size + 1 then g.OpenPopupStack:push_back(popup_ref) return true @@ -13048,7 +15315,7 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p end -- Don't close our own child popup windows. - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d", ref_window and ref_window.Name or "", restore_focus_to_window_under_popup) + -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\") restore_under=%d\n", ref_window and ref_window.Name or "", restore_focus_to_window_under_popup) local popup_count_to_keep = 0 if ref_window then -- Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow) @@ -13068,12 +15335,13 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p -- Window -> Popup1 -> Window2(Ref) -- - Clicking/focusing Popup1 will close Popup2 and Popup3: -- Window -> Popup1(Ref) -> Popup2 -> Popup3 - -- - Each popups may contain child windows, which is why we compare ->RootWindow! + -- - Each popups may contain child windows, which is why we compare .RootWindowDockTree! -- Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child -- We step through every popup from bottom to top to validate their position relative to reference window. ref_window_is_descendent_of_popup = false for n = popup_count_to_keep, g.OpenPopupStack.Size - 1 do local popup_window = g.OpenPopupStack.Data[n + 1].Window + -- if (popup_window.RootWindowDockTree == ref_window.RootWindowDockTree) -- FIXME-MERGE if popup_window and ImGui.IsWindowWithinBeginStackOf(ref_window, popup_window) then ref_window_is_descendent_of_popup = true break @@ -13091,7 +15359,7 @@ function ImGui.ClosePopupsOverWindow(ref_window, restore_focus_to_window_under_p end end if popup_count_to_keep < g.OpenPopupStack.Size then -- This test is not required but it allows to set a convenient breakpoint on the statement below - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")", ref_window and ref_window.Name or "") + -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window and ref_window.Name or "") ImGui.ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup) end end @@ -13100,7 +15368,7 @@ end --- @param restore_focus_to_window_under_popup bool function ImGui.ClosePopupToLevel(remaining, restore_focus_to_window_under_popup) local g = GImGui - -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d", remaining, restore_focus_to_window_under_popup) + -- IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_under=%d\n", remaining, restore_focus_to_window_under_popup) IM_ASSERT(remaining >= 0 and remaining < g.OpenPopupStack.Size) -- if bit32.band(g.DebugLogFlags, ImGuiDebugLogFlags.EventPopup) ~= 0 then -- for n = remaining + 1, g.OpenPopupStack.Size do @@ -13133,7 +15401,7 @@ function ImGui.ClosePopupToLevel(remaining, restore_focus_to_window_under_popup) end end --- Close the popup we have Begin-ed into +-- Close the popup we have begin-ed into. function ImGui.CloseCurrentPopup() local g = GImGui local popup_idx = g.BeginPopupStack.Size @@ -13171,12 +15439,13 @@ function ImGui.CloseCurrentPopup() end end +-- Attention! BeginPopup() adds default flags when calling BeginPopupEx()! --- @param id ImGuiID --- @param extra_window_flags ImGuiWindowFlags function ImGui.BeginPopupEx(id, extra_window_flags) local g = GImGui if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values return false end @@ -13199,21 +15468,24 @@ end function ImGui.BeginPopupMenuEx(id, label, extra_window_flags) local g = GImGui if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values return false end + -- As we bypass BeginChild(), set ImGuiChildFlags.AlwaysAutoResize as it is checked independently from ImGuiWindowFlags.AlwaysAutoResize for now (see #9355) + -- Ideally we should remove setting ImGuiWindowFlags.AlwaysAutoResize in BeginChild(). if bit32.band(extra_window_flags, ImGuiWindowFlags.ChildWindow) ~= 0 and bit32.band(extra_window_flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0 then ImGui.SetNextWindowChildFlags(ImGuiChildFlags.AlwaysAutoResize, true) end IM_ASSERT(bit32.band(extra_window_flags, ImGuiWindowFlags.ChildMenu) ~= 0) - local name = ImFormatString("%s###Menu_%02d", label, g.BeginMenuDepth) + local name = ImFormatString("%s###Menu_%02d", label, g.BeginMenuDepth) -- Recycle windows based on depth local is_open _, is_open = ImGui.Begin(name, nil, bit32.bor(extra_window_flags, ImGuiWindowFlags.Popup)) - if not is_open then + if not is_open then -- NB: Begin can return false when the popup is completely clipped (e.g. zero size display) ImGui.EndPopup() end + -- g.CurrentWindow.FocusRouteParentWindow = g.CurrentWindow.ParentWindowInBeginStack return is_open end @@ -13255,6 +15527,11 @@ function ImGui.EndPopup() g.WithinEndChildID = backup_within_end_child_id end +-- r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) +-- r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it. +-- (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor +-- information are available, it may represent the entire platform monitor from the frame of reference of the current viewport. +-- this allows us to have tooltips/popups displayed out of the parent viewport.) --- @param ref_pos ImVec2 --- @param size ImVec2 --- @param last_dir ImGuiDir @@ -13306,7 +15583,7 @@ function ImGui.FindBestWindowPosForPopupEx(ref_pos, size, last_dir, r_outer, r_a repeat local dir = (n == 0) and last_dir or dir_preferred_order[n] - if n ~= 0 and dir == last_dir then + if n ~= 0 and dir == last_dir then -- Already tried this direction? break end @@ -13353,6 +15630,7 @@ function ImGui.FindBestWindowPosForPopupEx(ref_pos, size, last_dir, r_outer, r_a return pos, last_dir end +-- Note that this is used for popups, which can overlap the non work-area of individual viewports. --- @param window ImGuiWindow --- @return ImRect --- @nodiscard @@ -13433,6 +15711,7 @@ function ImGui.FindBestWindowPosForPopup(window) 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. end + -- ImGui.GetForegroundDrawList():AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255)) local pos pos, window.AutoPosLastDirection = ImGui.FindBestWindowPosForPopupEx(tooltip_pos, window.Size, window.AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy.Tooltip) @@ -13448,7 +15727,6 @@ end --- @return ImGuiMouseButton function ImGui.GetMouseButtonFromPopupFlags(flags) IM_ASSERT(bit32.band(flags, ImGuiPopupFlags.InvalidMask_) == 0) - if bit32.band(flags, ImGuiPopupFlags.MouseButtonMask_) ~= 0 then return bit32.rshift(bit32.band(flags, ImGuiPopupFlags.MouseButtonMask_), ImGuiPopupFlags.MouseButtonShift_) - 1 end @@ -13471,6 +15749,8 @@ function ImGui.IsPopupOpenRequestForItem(popup_flags, id) return false end +-- Helper to open a popup if mouse button is released over the item +-- - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup() --- @param str_id? string --- @param popup_flags? ImGuiPopupFlags @native @@ -13481,14 +15761,30 @@ function ImGui.OpenPopupOnItemClick(str_id, popup_flags) if ImGui.IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID) then local window = g.CurrentWindow local id - if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end - IM_ASSERT(id ~= 0) + if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end -- If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! + IM_ASSERT(id ~= 0) -- You cannot pass a nil str_id if the last item has no identifier (e.g. a Text() item) return ImGui.OpenPopupEx(id, popup_flags) end return false end +-- This is a helper to handle the simplest case of associating one named popup to one given widget. +-- - To create a popup associated to the last item, you generally want to pass a nil value to str_id. +-- - To create a popup with a specific identifier, pass it in str_id. +-- - This is useful when using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call. +-- - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id. +-- - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). +-- This is essentially the same as: +-- id = str_id ? GetID(str_id) : GetItemID(); +-- OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight); +-- return BeginPopup(id); +-- Which is essentially the same as: +-- id = str_id ? GetID(str_id) : GetItemID(); +-- if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right)) +-- OpenPopup(id); +-- return BeginPopup(id); +-- The main difference being that this is tweaked to avoid computing the ID twice. --- @param str_id? string --- @param popup_flags? ImGuiPopupFlags --- @return bool @@ -13501,17 +15797,21 @@ function ImGui.BeginPopupContextItem(str_id, popup_flags) return false end local id - if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end - IM_ASSERT(id ~= 0) + if str_id then id = window:GetID(str_id) else id = g.LastItemData.ID end -- If user hasn't passed an ID, we can use the LastItem ID. Using LastItem ID as a Popup ID won't conflict! + IM_ASSERT(id ~= 0) -- You cannot pass a nil str_id if the last item has no identifier (e.g. a Text() item) if ImGui.IsPopupOpenRequestForItem(popup_flags, g.LastItemData.ID) then ImGui.OpenPopupEx(id, popup_flags) end return ImGui.BeginPopupEx(id, bit32.bor(ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoSavedSettings)) end ---------------------------------------------------------------------------------------- --- [SECTION] NAVIGATION ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] KEYBOARD/GAMEPAD NAVIGATION +------------------------------------------------------------------------------- + +-- FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked. +-- In our terminology those should be interchangeable, yet right now this is super confusing. +-- Those two functions are merely a legacy artifact, so at minimum naming should be clarified. --- @param id ImGuiID function ImGui.PushFocusScope(id) @@ -13552,13 +15852,15 @@ end function ImGui.SetNavFocusScope(focus_scope_id) local g = GImGui g.NavFocusScopeId = focus_scope_id - g.NavFocusRoute:resize(0) + g.NavFocusRoute:resize(0) -- Invalidate if focus_scope_id == 0 then return end IM_ASSERT(g.NavWindow ~= nil) + -- Store current path (in reverse order) if focus_scope_id == g.CurrentFocusScopeId then + -- Top of focus stack contains local focus scopes inside current window for n = g.FocusScopeStack.Size, 1, -1 do local data = g.FocusScopeStack.Data[n] if data.WindowID ~= g.CurrentWindow.ID then @@ -13575,6 +15877,7 @@ function ImGui.SetNavFocusScope(focus_scope_id) return end + -- Then follow on manually set ParentWindowForFocusRoute field (#6798) local window = g.NavWindow.ParentWindowForFocusRoute while window ~= nil do local data = ImGuiFocusScopeData() @@ -13583,7 +15886,7 @@ function ImGui.SetNavFocusScope(focus_scope_id) g.NavFocusRoute:push_back(data) window = window.ParentWindowForFocusRoute end - IM_ASSERT(g.NavFocusRoute.Size < 100) + IM_ASSERT(g.NavFocusRoute.Size < 100) -- Maximum depth is technically 251 as per CalcRoutingScore(): 254 - 3 end function ImGui.SetItemDefaultFocus() @@ -13600,11 +15903,13 @@ function ImGui.SetItemDefaultFocus() ImGui.NavApplyItemToResult(g.NavInitResult) ImGui.NavUpdateAnyRequestFlag() + -- Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll) if not window.ClipRect:Contains(g.LastItemData.Rect) then ImGui.ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags.None) end end +-- (was called NavRestoreHighlightAfterMove() before 1.91.4) function ImGui.SetNavCursorVisibleAfterMove() local g = GImGui if g.NavWindow and (bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) ~= 0) then @@ -13654,10 +15959,13 @@ function ImGui.SetNavID(id, nav_layer, focus_scope_id, rect_rel) g.NavWindow.NavLastIds[nav_layer] = id ImRect_Copy(g.NavWindow.NavRectRel[nav_layer], rect_rel) + -- Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y) end +-- FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0). +-- This way we could find the last focused window among our children. It would be much less confusing this way? --- @param nav_window ImGuiWindow function ImGui.NavSaveLastChildNavWindowIntoParent(nav_window) local parent = nav_window @@ -13669,6 +15977,8 @@ function ImGui.NavSaveLastChildNavWindowIntoParent(nav_window) end end +-- Restore the last focused child. +-- Call when we are expected to land on the Main Layer (0) after FocusWindow() --- @param window ImGuiWindow function ImGui.NavRestoreLastChildNavWindow(window) if window.NavLastChildNavWindow and window.NavLastChildNavWindow.WasActive then @@ -13682,8 +15992,9 @@ function ImGui.NavRestoreLayer(layer) local g = GImGui if layer == ImGuiNavLayer.Main then local prev_nav_window = g.NavWindow - g.NavWindow = ImGui.NavRestoreLastChildNavWindow(g.NavWindow) + g.NavWindow = ImGui.NavRestoreLastChildNavWindow(g.NavWindow) -- FIXME-NAV: Should clear ongoing nav requests? g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid + -- if (prev_nav_window) IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name) end local window = g.NavWindow if window.NavLastIds[layer] ~= 0 then @@ -13709,9 +16020,11 @@ function ImGui.NavUpdateAnyRequestFlag() end end +-- This needs to be called before we submit any widget (aka in or before Begin) --- @param window ImGuiWindow --- @param force_reinit bool function ImGui.NavInitWindow(window, force_reinit) + -- FIXME: ChildWindow test here is wrong for docking local g = GImGui IM_ASSERT(window == g.NavWindow) @@ -13738,6 +16051,8 @@ function ImGui.NavInitWindow(window, force_reinit) end end +-- Positioning logic altered slightly for remote activation: for Popup we want to use item rect, for Tooltip we leave things alone. (#9138) +-- When calling for ImGuiWindowFlags.Popup we use LastItemData. --- @param window_type ImGuiWindowFlags --- @return ImGuiInputSource function ImGui.NavCalcPreferredRefPosSource(window_type) @@ -13841,7 +16156,7 @@ function ImGui.NavUpdateWindowingTarget(focus_change_dir) if window_target == nil then window_target = ImGui.FindWindowNavFocusable((focus_change_dir < 0) and g.WindowsFocusOrder.Size or 1, i_current, focus_change_dir) end - if window_target then + if window_target then -- Don't reset windowing target if there's a single window in the list g.NavWindowingTarget = window_target g.NavWindowingTargetAnim = window_target ImVec2_CopyV(g.NavWindowingAccumDeltaPos, 0.0, 0.0) @@ -13850,8 +16165,11 @@ function ImGui.NavUpdateWindowingTarget(focus_change_dir) g.NavWindowingToggleLayer = false end +-- Apply focus and close overlay --- @param apply_focus_window ImGuiWindow function ImGui.NavUpdateWindowingApplyFocus(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() local g = GImGui if g.NavWindow == nil or apply_focus_window ~= g.NavWindow.RootWindow then local previous_viewport = g.NavWindow and g.NavWindow.Viewport or nil @@ -13861,14 +16179,22 @@ function ImGui.NavUpdateWindowingApplyFocus(apply_focus_window) ImGui.FocusWindow(apply_focus_window, ImGuiFocusRequestFlags.RestoreFocusedChild) IM_ASSERT(g.NavWindow ~= nil) apply_focus_window = g.NavWindow - if apply_focus_window.NavLastIds[ImGuiNavLayer.Main] == 0 then + if apply_focus_window.NavLastIds[ImGuiNavLayer.Main] == 0 then -- FIXME: This is the equivalent of the 'if (g.NavId == 0) { NavInitWindow() }' in DockNodeUpdateTabBar(). ImGui.NavInitWindow(apply_focus_window, false) end + -- 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 == bit32.lshift(1, ImGuiNavLayer.Menu) then g.NavLayer = ImGuiNavLayer.Menu end + -- Request OS level focus if apply_focus_window.Viewport ~= previous_viewport and g.PlatformIO.Platform_SetWindowFocus then g.PlatformIO.Platform_SetWindowFocus(apply_focus_window.Viewport) end @@ -13876,6 +16202,9 @@ function ImGui.NavUpdateWindowingApplyFocus(apply_focus_window) g.NavWindowingTarget = nil end +-- 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) function ImGui.NavUpdateWindowing() local g = GImGui local io = g.IO @@ -13884,11 +16213,12 @@ function ImGui.NavUpdateWindowing() local apply_toggle_layer = false local modal_window = ImGui.GetTopMostPopupModal() - local allow_windowing = (modal_window == nil) + local allow_windowing = (modal_window == nil) -- FIXME: This prevent Ctrl+Tab from being usable with windows that are inside the Begin-stack of that modal. if not allow_windowing then g.NavWindowingTarget = nil end + -- Fade out if g.NavWindowingTargetAnim and g.NavWindowingTarget == nil then g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0, 0.0) if g.DimBgRatio <= 0.0 and g.NavWindowingHighlightAlpha <= 0.0 then @@ -13896,6 +16226,8 @@ function ImGui.NavUpdateWindowing() end end + -- 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) local owner_id = ImHashStr("##NavUpdateWindowing") local nav_gamepad_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0 local nav_keyboard_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 @@ -13903,10 +16235,10 @@ function ImGui.NavUpdateWindowing() local keyboard_prev_window = allow_windowing and g.ConfigNavWindowingKeyPrev ~= 0 and ImGui.Shortcut(g.ConfigNavWindowingKeyPrev, bit32.bor(ImGuiInputFlags.Repeat, ImGuiInputFlags.RouteAlways), owner_id) local start_toggling_with_gamepad = nav_gamepad_active and g.NavWindowingTarget == nil and ImGui.Shortcut(ImGuiKey.NavGamepadMenu, ImGuiInputFlags.RouteAlways, owner_id) local start_windowing_with_gamepad = allow_windowing and start_toggling_with_gamepad - local start_windowing_with_keyboard = allow_windowing and g.NavWindowingTarget == nil and (keyboard_next_window or keyboard_prev_window) + local start_windowing_with_keyboard = allow_windowing and g.NavWindowingTarget == nil and (keyboard_next_window or keyboard_prev_window) -- Note: enabled even without NavEnableKeyboard! local just_started_windowing_from_null_focus = false if start_toggling_with_gamepad then - g.NavWindowingToggleLayer = true + g.NavWindowingToggleLayer = true -- Gamepad starts toggling layer g.NavWindowingToggleKey = ImGuiKey.NavGamepadMenu g.NavWindowingInputSource = ImGuiInputSource.Gamepad g.NavInputSource = ImGuiInputSource.Gamepad @@ -13916,7 +16248,7 @@ function ImGui.NavUpdateWindowing() if window then if start_windowing_with_keyboard or g.ConfigNavWindowingWithGamepad then g.NavWindowingTarget = window.RootWindow - g.NavWindowingTargetAnim = window.RootWindow + g.NavWindowingTargetAnim = window.RootWindow -- Current location end g.NavWindowingTimer = 0.0 g.NavWindowingHighlightAlpha = 0.0 @@ -13928,17 +16260,22 @@ function ImGui.NavUpdateWindowing() just_started_windowing_from_null_focus = true end + -- Manually register ownership of our mods. Using a global route in the Shortcut() calls instead would probably be correct but may have more side-effects. if keyboard_next_window or keyboard_prev_window then ImGui.SetKeyOwnersForKeyChord(bit32.band(bit32.bor(g.ConfigNavWindowingKeyNext, g.ConfigNavWindowingKeyPrev), ImGuiMod_Mask_), owner_id) end end end + -- Gamepad update if (g.NavWindowingTarget or g.NavWindowingToggleLayer) and g.NavWindowingInputSource == ImGuiInputSource.Gamepad then if g.NavWindowingTarget ~= nil then + -- 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 = g.NavWindowingTimer + io.DeltaTime g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05)) + -- Select window to focus local focus_change_dir = (ImGui.IsKeyPressedEx(ImGuiKey.GamepadL1, ImGuiInputFlags.None, ImGuiKeyOwner_Any) and 1 or 0) - (ImGui.IsKeyPressedEx(ImGuiKey.GamepadR1, ImGuiInputFlags.None, ImGuiKeyOwner_Any) and 1 or 0) if focus_change_dir ~= 0 and not just_started_windowing_from_null_focus then ImGui.NavUpdateWindowingTarget(focus_change_dir) @@ -13946,8 +16283,9 @@ function ImGui.NavUpdateWindowing() end end + -- Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most) if not ImGui.IsKeyDown(ImGuiKey.NavGamepadMenu) then - g.NavWindowingToggleLayer = g.NavWindowingToggleLayer and (g.NavWindowingHighlightAlpha < 1.0) + g.NavWindowingToggleLayer = g.NavWindowingToggleLayer and (g.NavWindowingHighlightAlpha < 1.0) -- Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. if g.NavWindowingToggleLayer and g.NavWindow then apply_toggle_layer = true elseif not g.NavWindowingToggleLayer then @@ -13958,13 +16296,15 @@ function ImGui.NavUpdateWindowing() end end + -- Keyboard: Focus if g.NavWindowingTarget and g.NavWindowingInputSource == ImGuiInputSource.Keyboard then + -- Visuals only appears after a brief time after pressing TAB the first time, so that a fast Ctrl+Tab doesn't add visual noise local shared_mods = bit32.band( bit32.band((g.ConfigNavWindowingKeyNext ~= 0) and g.ConfigNavWindowingKeyNext or ImGuiMod_Mask_, (g.ConfigNavWindowingKeyPrev ~= 0) and g.ConfigNavWindowingKeyPrev or ImGuiMod_Mask_), ImGuiMod_Mask_) - IM_ASSERT(shared_mods ~= 0) + 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 = g.NavWindowingTimer + io.DeltaTime - g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05)) + g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05)) -- 1.0f if (keyboard_next_window or keyboard_prev_window) and not just_started_windowing_from_null_focus then ImGui.NavUpdateWindowingTarget(keyboard_next_window and -1 or 1) elseif bit32.band(io.KeyMods, shared_mods) ~= shared_mods then @@ -13972,6 +16312,7 @@ function ImGui.NavUpdateWindowing() end end + -- Keyboard: Press and Release Alt to toggle menu layer local windowing_toggle_keys = { ImGuiKey.LeftAlt, ImGuiKey.RightAlt } local windowing_toggle_layer_start = false if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 then @@ -13987,6 +16328,10 @@ function ImGui.NavUpdateWindowing() end end if g.NavWindowingToggleLayer and g.NavWindowingInputSource == ImGuiInputSource.Keyboard then + -- 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) + -- - AltGR is Alt+Ctrl on some layout but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). + -- We cancel toggling nav layer if an owner has claimed the key. if io.InputQueueCharacters.Size > 0 or io.KeyCtrl or io.KeyShift or io.KeySuper then g.NavWindowingToggleLayer = false elseif windowing_toggle_layer_start == false and g.LastKeyboardKeyPressTime == g.Time then @@ -13995,6 +16340,8 @@ function ImGui.NavUpdateWindowing() g.NavWindowingToggleLayer = false end + -- Apply layer toggle on Alt release + -- Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss. if ImGui.IsKeyReleased(g.NavWindowingToggleKey) and g.NavWindowingToggleLayer then if g.ActiveId == 0 or g.ActiveIdAllowOverlap then if ImGui.IsMousePosValid(io.MousePos) == ImGui.IsMousePosValid(io.MousePosPrev) then @@ -14007,6 +16354,7 @@ function ImGui.NavUpdateWindowing() end end + -- Move window if g.NavWindowingTarget and bit32.band(g.NavWindowingTarget.Flags, ImGuiWindowFlags.NoMove) == 0 then local nav_move_dir if g.NavInputSource == ImGuiInputSource.Keyboard and not io.KeyShift then @@ -14029,13 +16377,16 @@ function ImGui.NavUpdateWindowing() end end + -- Apply final focus if apply_focus_window then ImGui.NavUpdateWindowingApplyFocus(apply_focus_window) end + -- Apply menu/layer toggle if apply_toggle_layer and g.NavWindow then ImGui.ClearActiveID() + -- Move to parent menu if necessary local new_nav_window = g.NavWindow while new_nav_window.ParentWindow and bit32.band(new_nav_window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) == 0 @@ -14049,8 +16400,10 @@ function ImGui.NavUpdateWindowing() new_nav_window.NavLastChildNavWindow = old_nav_window end + -- Toggle layer local new_nav_layer = (bit32.band(g.NavWindow.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Menu)) ~= 0) and bit32.bxor(g.NavLayer, 1) or ImGuiNavLayer.Main if new_nav_layer ~= g.NavLayer then + -- Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?) local preserve_layer_1_nav_id = (new_nav_window.DockNodeAsHost ~= nil) if new_nav_layer == ImGuiNavLayer.Menu and not preserve_layer_1_nav_id then g.NavWindow.NavLastIds[new_nav_layer] = 0 @@ -14082,6 +16435,7 @@ function ImGui.NavUpdateContextMenuRequest() g.NavOpenContextMenuItemId = g.NavId g.NavOpenContextMenuWindowId = g.NavWindow.ID + -- Allow triggering for Begin()..BeginPopupContextItem(). A possible alternative would be to use g.NavLayer == ImGuiNavLayer.Menu. if g.NavId == g.NavWindow:GetID("#CLOSE") or g.NavId == g.NavWindow:GetID("#COLLAPSE") then g.NavOpenContextMenuItemId = g.NavWindow.MoveId end @@ -14090,6 +16444,7 @@ function ImGui.NavUpdateContextMenuRequest() ImGui.SetNavCursorVisibleAfterMove() end +-- FIXME: ScoringRect is not set --- @param move_dir ImGuiDir --- @param clip_dir ImGuiDir --- @param move_flags ImGuiNavMoveFlags @@ -14097,6 +16452,8 @@ end function ImGui.NavMoveRequestSubmit(move_dir, clip_dir, move_flags, scroll_flags) local g = GImGui IM_ASSERT(g.NavWindow ~= nil) + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestSubmit: dir %c, window \"%s\"\n", "-WENS"[move_dir + 1], g.NavWindow->Name) + if bit32.band(move_flags, ImGuiNavMoveFlags.IsTabbing) ~= 0 then move_flags = bit32.bor(move_flags, ImGuiNavMoveFlags.AllowCurrentNavId) end @@ -14116,13 +16473,19 @@ function ImGui.NavMoveRequestSubmit(move_dir, clip_dir, move_flags, scroll_flags ImGui.NavUpdateAnyRequestFlag() end +-- Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position --- @param r ImRect --- @param preferred_pos_rel ImVec2 --- @param move_dir ImGuiDir --- @param move_flags ImGuiNavMoveFlags function ImGui.NavBiasScoringRect(r, preferred_pos_rel, move_dir, move_flags) + -- Bias initial rect local g = GImGui local rel_to_abs_offset = g.NavWindow.DC.CursorStartPos + + -- Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias. + -- - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column. + -- - But each successful move sets new bias on one axis, only cleared when using mouse. if bit32.band(move_flags, ImGuiNavMoveFlags.Forwarded) == 0 then if preferred_pos_rel.x == FLT_MAX then preferred_pos_rel.x = ImMin(r.Min.x + 1.0, r.Max.x) - rel_to_abs_offset.x @@ -14131,6 +16494,8 @@ function ImGui.NavBiasScoringRect(r, preferred_pos_rel, move_dir, move_flags) preferred_pos_rel.y = r:GetCenter().y - rel_to_abs_offset.y end end + + -- Apply general bias on the other axis if (move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and preferred_pos_rel.x ~= FLT_MAX then local new_x = preferred_pos_rel.x + rel_to_abs_offset.x r.Min.x = new_x; r.Max.x = new_x @@ -14140,6 +16505,10 @@ function ImGui.NavBiasScoringRect(r, preferred_pos_rel, move_dir, move_flags) end end +-- Handle PageUp/PageDown/Home/End keys +-- Called from NavUpdateCreateMoveRequest() which will use our output to create a move request +-- FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference +-- FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid? --- @return float function ImGui.NavUpdatePageUpPageDown() local g = GImGui @@ -14152,7 +16521,7 @@ function ImGui.NavUpdatePageUpPageDown() local page_down_held = ImGui.IsKeyDown(ImGuiKey.PageDown, ImGuiKeyOwner_NoOwner) local home_pressed = ImGui.IsKeyPressedEx(ImGuiKey.Home, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) local end_pressed = ImGui.IsKeyPressedEx(ImGuiKey.End, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) - if page_up_held == page_down_held and home_pressed == end_pressed then + if page_up_held == page_down_held and home_pressed == end_pressed then -- Proceed if either (not both) are pressed, otherwise early out return 0.0 end @@ -14161,6 +16530,7 @@ function ImGui.NavUpdatePageUpPageDown() end if bit32.band(window.DC.NavLayersActiveMask, bit32.lshift(1, ImGuiNavLayer.Main)) == 0 and window.DC.NavWindowHasScrollY then + -- Fallback manual-scroll when window has no navigable item if ImGui.IsKeyPressedEx(ImGuiKey.PageUp, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then ImGui.SetScrollY(window, window.Scroll.y - window.InnerRect:GetHeight()) elseif ImGui.IsKeyPressedEx(ImGuiKey.PageDown, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then @@ -14176,21 +16546,25 @@ function ImGui.NavUpdatePageUpPageDown() local nav_scoring_rect_offset_y = 0.0 if ImGui.IsKeyPressedEx(ImGuiKey.PageUp, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then nav_scoring_rect_offset_y = -page_offset_y - g.NavMoveDir = ImGuiDir.Down + g.NavMoveDir = ImGuiDir.Down -- Because our scoring rect is offset up, we request the down direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir.Up - g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) + g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) -- ImGuiNavMoveFlags.AlsoScoreVisibleSet may be added later elseif ImGui.IsKeyPressedEx(ImGuiKey.PageDown, ImGuiInputFlags.Repeat, ImGuiKeyOwner_NoOwner) then nav_scoring_rect_offset_y = page_offset_y - g.NavMoveDir = ImGuiDir.Up + g.NavMoveDir = ImGuiDir.Up -- Because our scoring rect is offset down, we request the up direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir.Down - g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) + g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.IsPageMove) -- ImGuiNavMoveFlags.AlsoScoreVisibleSet may be added later elseif home_pressed then + -- FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y + -- Scrolling will be handled via the ImGuiNavMoveFlags.ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result. + -- Preserve current horizontal position if we have any. nav_rect_rel.Min.y = 0.0; nav_rect_rel.Max.y = 0.0 if nav_rect_rel:IsInverted() then nav_rect_rel.Min.x = 0.0; nav_rect_rel.Max.x = 0.0 end g.NavMoveDir = ImGuiDir.Down g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.ScrollToEdgeY) + -- FIXME-NAV: MoveClipDir left to _None, intentional? elseif end_pressed then nav_rect_rel.Min.y = window.ContentSize.y; nav_rect_rel.Max.y = window.ContentSize.y if nav_rect_rel:IsInverted() then @@ -14198,6 +16572,7 @@ function ImGui.NavUpdatePageUpPageDown() end g.NavMoveDir = ImGuiDir.Up g.NavMoveFlags = bit32.bor(ImGuiNavMoveFlags.AllowCurrentNavId, ImGuiNavMoveFlags.ScrollToEdgeY) + -- FIXME-NAV: MoveClipDir left to _None, intentional? end return nav_scoring_rect_offset_y end @@ -14212,9 +16587,13 @@ function ImGui.NavUpdateCreateMoveRequest() local nav_keyboard_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 if g.NavMoveForwardToNextFrame and window ~= nil then + -- Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window) + -- (preserve most state, which were already set by the NavMoveRequestForward() function) IM_ASSERT(g.NavMoveDir ~= ImGuiDir.None and g.NavMoveClipDir ~= ImGuiDir.None) IM_ASSERT(bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) ~= 0) + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir) else + -- Initiate directional inputs request g.NavMoveDir = ImGuiDir.None g.NavMoveFlags = ImGuiNavMoveFlags.None g.NavMoveScrollFlags = ImGuiScrollFlags.None @@ -14229,33 +16608,46 @@ function ImGui.NavUpdateCreateMoveRequest() ImRect_Copy(g.NavScoringNoClipRect, ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX)) end + -- Update PageUp/PageDown/Home/End scroll + -- FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags.NavEnableKeyboard flag? local scoring_page_offset_y = 0.0 if window and g.NavMoveDir == ImGuiDir.None and nav_keyboard_active then scoring_page_offset_y = ImGui.NavUpdatePageUpPageDown() end + -- Submit g.NavMoveForwardToNextFrame = false if g.NavMoveDir ~= ImGuiDir.None then ImGui.NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags) end + -- Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match) if g.NavMoveSubmitted and g.NavId == 0 then + -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "", g.NavLayer) g.NavInitRequest = true; g.NavInitRequestFromMove = true g.NavInitResult.ID = 0 - if g.IO.ConfigNavCursorVisibleAuto then + if g.IO.ConfigNavCursorVisibleAuto then -- NO check for _NoNavInputs here as we assume MoveRequests cannot be created. g.NavCursorVisible = true end end - if g.NavMoveSubmitted and g.NavInputSource == ImGuiInputSource.Gamepad and g.NavLayer == ImGuiNavLayer.Main and window ~= nil then + -- When using gamepad, we project the reference nav bounding box into window visible area. + -- This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, + -- since with gamepad all movements are relative (can't focus a visible object like we can with the mouse). + if g.NavMoveSubmitted and g.NavInputSource == ImGuiInputSource.Gamepad and g.NavLayer == ImGuiNavLayer.Main and window ~= nil then -- and (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded)) local clamp_x = bit32.band(g.NavMoveFlags, bit32.bor(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.WrapX)) == 0 local clamp_y = bit32.band(g.NavMoveFlags, bit32.bor(ImGuiNavMoveFlags.LoopY, ImGuiNavMoveFlags.WrapY)) == 0 local inner_rect_rel = ImGui.WindowRectAbsToRel(window, ImRect(ImVec2(window.InnerRect.Min.x - 1, window.InnerRect.Min.y - 1), ImVec2(window.InnerRect.Max.x + 1, window.InnerRect.Max.y + 1))) + + -- Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171) + -- Otherwise 'inner_rect_rel' would be off on the move result frame. local next_scroll = CalcNextScrollFromScrollTargetAndClamp(window) inner_rect_rel:Translate(ImVec2(next_scroll.x - window.Scroll.x, next_scroll.y - window.Scroll.y)) + if (clamp_x or clamp_y) and not inner_rect_rel:Contains(window.NavRectRel[g.NavLayer]) then + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n") local pad_x = ImMin(inner_rect_rel:GetWidth(), window.FontRefSize * 0.5) - local pad_y = ImMin(inner_rect_rel:GetHeight(), window.FontRefSize * 0.5) + local pad_y = ImMin(inner_rect_rel:GetHeight(), window.FontRefSize * 0.5) -- Terrible approximation for the intent of starting navigation from first fully visible item inner_rect_rel.Min.x = clamp_x and (inner_rect_rel.Min.x + pad_x) or -FLT_MAX inner_rect_rel.Max.x = clamp_x and (inner_rect_rel.Max.x - pad_x) or FLT_MAX inner_rect_rel.Min.y = clamp_y and (inner_rect_rel.Min.y + pad_y) or -FLT_MAX @@ -14265,6 +16657,8 @@ function ImGui.NavUpdateCreateMoveRequest() end end + -- 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) local scoring_rect = ImRect() if window ~= nil then local nav_rect_rel = ImRect() @@ -14274,6 +16668,7 @@ function ImGui.NavUpdateCreateMoveRequest() scoring_rect = ImGui.WindowRectRelToAbs(window, nav_rect_rel) if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsPageMove) ~= 0 then + -- When we start from a visible location, score visible items and prioritize this result. if window.InnerRect:Contains(scoring_rect) then g.NavMoveFlags = bit32.bor(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) end @@ -14282,12 +16677,16 @@ function ImGui.NavUpdateCreateMoveRequest() g.NavScoringNoClipRect:Add(scoring_rect) end + -- ImGui.GetForegroundDrawList():AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)) -- [DEBUG] Pre-bias if g.NavMoveSubmitted then ImGui.NavBiasScoringRect(scoring_rect, window.RootWindowForNav.NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags) end - IM_ASSERT(not scoring_rect:IsInverted()) + IM_ASSERT(not scoring_rect:IsInverted()) -- Ensure we have a non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem(). + -- ImGui.GetForegroundDrawList():AddRectFilled(scoring_rect.Min - ImVec2(1, 1), scoring_rect.Max + ImVec2(1, 1), IM_COL32(255, 100, 0, 80)) -- [DEBUG] Post-bias + -- if not g.NavScoringNoClipRect:IsInverted() then ImGui.GetForegroundDrawList():AddRectFilled(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(100, 255, 0, 80)) end -- [DEBUG] end ImRect_Copy(g.NavScoringRect, scoring_rect) + -- g.NavScoringNoClipRect:Add(scoring_rect) end function ImGui.NavUpdateCreateTabbingRequest() @@ -14303,6 +16702,9 @@ function ImGui.NavUpdateCreateTabbingRequest() return end + -- Initiate tabbing request + -- (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags.NavEnableKeyboard flag!) + -- See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping. local nav_keyboard_active = bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 if nav_keyboard_active then g.NavTabbingDir = g.IO.KeyShift and -1 or ((g.NavCursorVisible == false and g.ActiveId == 0) and 0 or 1) @@ -14312,7 +16714,7 @@ function ImGui.NavUpdateCreateTabbingRequest() local move_flags = bit32.bor(ImGuiNavMoveFlags.IsTabbing, ImGuiNavMoveFlags.Activate) local scroll_flags = window.Appearing and bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.AlwaysCenterY) or bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleEdgeY) local clip_dir = (g.NavTabbingDir < 0) and ImGuiDir.Up or ImGuiDir.Down - ImGui.NavMoveRequestSubmit(ImGuiDir.None, clip_dir, move_flags, scroll_flags) + ImGui.NavMoveRequestSubmit(ImGuiDir.None, clip_dir, move_flags, scroll_flags) -- FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable. g.NavTabbingCounter = -1 end @@ -14321,7 +16723,10 @@ function ImGui.NavUpdate() local io = g.IO io.WantSetMousePos = false + -- if g.NavScoringDebugCount > 0 then IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest) end + -- Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard) + -- FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource? local nav_gamepad_active = bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0 if nav_gamepad_active and g.NavInputSource ~= ImGuiInputSource.Gamepad then for _, key in ipairs(nav_gamepad_keys_to_change_source) do @@ -14340,6 +16745,7 @@ function ImGui.NavUpdate() end end + -- Process navigation init request (select first/default focus) g.NavJustMovedToId = 0 g.NavJustMovedToFocusScopeId = 0 g.NavJustMovedFromFocusScopeId = 0 @@ -14350,6 +16756,7 @@ function ImGui.NavUpdate() g.NavInitRequestFromMove = false g.NavInitResult.ID = 0 + -- Process navigation move request if g.NavMoveSubmitted then ImGui.NavMoveRequestApplyResult() end @@ -14363,6 +16770,7 @@ function ImGui.NavUpdate() end end + -- Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling) local set_mouse_pos = false if g.NavMousePosDirty and g.NavIdIsAlive then if g.NavCursorVisible and g.NavHighlightItemUnderNav and g.NavWindow then @@ -14372,6 +16780,7 @@ function ImGui.NavUpdate() g.NavMousePosDirty = false IM_ASSERT(g.NavLayer == ImGuiNavLayer.Main or g.NavLayer == ImGuiNavLayer.Menu) + -- Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0 if g.NavWindow then ImGui.NavSaveLastChildNavWindowIntoParent(g.NavWindow) end @@ -14379,14 +16788,18 @@ function ImGui.NavUpdate() g.NavWindow.NavLastChildNavWindow = nil end + -- Update Ctrl+Tab and Windowing features (hold Square to move/resize/etc.) ImGui.NavUpdateWindowing() + -- Set output flags for user application io.NavActive = (nav_keyboard_active or nav_gamepad_active) and g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 io.NavVisible = (io.NavActive and g.NavId ~= 0 and g.NavCursorVisible) or (g.NavWindowingTarget ~= nil) + -- Process NavCancel input (to close a popup, get back to parent, clear focus) ImGui.NavUpdateCancelRequest() ImGui.NavUpdateContextMenuRequest() + -- Process manual activation request g.NavActivateId = 0 g.NavActivateDownId = 0 g.NavActivatePressedId = 0 @@ -14397,7 +16810,7 @@ function ImGui.NavUpdate() local activate_pressed = activate_down and ((nav_keyboard_active and ImGui.IsKeyPressedEx(ImGuiKey.Space, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner)) or (nav_gamepad_active and ImGui.IsKeyPressedEx(ImGuiKey.NavGamepadActivate, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner))) local input_pressed_keyboard = nav_keyboard_active and (ImGui.IsKeyPressedEx(ImGuiKey.Enter, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner) or ImGui.IsKeyPressedEx(ImGuiKey.KeypadEnter, ImGuiInputFlags.None, ImGuiKeyOwner_NoOwner)) local input_pressed_gamepad = false - if activate_down and nav_gamepad_active and ImGui.IsKeyDown(ImGuiKey.NavGamepadActivate, ImGuiKeyOwner_NoOwner) and bit32.band(g.NavIdItemFlags, ImGuiItemFlags.Inputable) ~= 0 then + if activate_down and nav_gamepad_active and ImGui.IsKeyDown(ImGuiKey.NavGamepadActivate, ImGuiKeyOwner_NoOwner) and bit32.band(g.NavIdItemFlags, ImGuiItemFlags.Inputable) ~= 0 then -- requires ImGuiItemFlags.Inputable to avoid retriggering regular buttons. if ImGui.GetKeyData(g, ImGuiKey.NavGamepadActivate).DownDurationPrev < NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY and ImGui.GetKeyData(g, ImGuiKey.NavGamepadActivate).DownDuration >= NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY then input_pressed_gamepad = true end @@ -14411,7 +16824,7 @@ function ImGui.NavUpdate() g.NavActivateId = g.NavId g.NavActivateFlags = ImGuiActivateFlags.PreferInput end - if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_down or input_pressed_keyboard or input_pressed_gamepad) then + if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_down or input_pressed_keyboard or input_pressed_gamepad) then -- FIXME-NAV: Unsure why input_pressed_xxx (migrated from input_down which was already dubious) g.NavActivateDownId = g.NavId end if (g.ActiveId == 0 or g.ActiveId == g.NavId) and (activate_pressed or input_pressed_keyboard or input_pressed_gamepad) then @@ -14428,6 +16841,7 @@ function ImGui.NavUpdate() IM_ASSERT(g.NavActivateDownId == g.NavActivateId) end + -- Highlight if g.NavHighlightActivatedTimer > 0.0 then g.NavHighlightActivatedTimer = ImMax(0.0, g.NavHighlightActivatedTimer - io.DeltaTime) end @@ -14435,6 +16849,8 @@ function ImGui.NavUpdate() g.NavHighlightActivatedId = 0 end + -- Process programmatic activation request + -- FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others) if g.NavNextActivateId ~= 0 then g.NavActivateId = g.NavNextActivateId g.NavActivateDownId = g.NavNextActivateId @@ -14443,6 +16859,7 @@ function ImGui.NavUpdate() end g.NavNextActivateId = 0 + -- Process move requests ImGui.NavUpdateCreateMoveRequest() if g.NavMoveDir == ImGuiDir.None then ImGui.NavUpdateCreateTabbingRequest() @@ -14450,9 +16867,11 @@ function ImGui.NavUpdate() ImGui.NavUpdateAnyRequestFlag() g.NavIdIsAlive = false + -- Scrolling if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.NoNavInputs) == 0 and not g.NavWindowingTarget then + -- *Fallback* manual-scroll with Nav directional keys when window has no navigable item local window = g.NavWindow - local scroll_speed = IM_ROUND(window.FontRefSize * 100 * io.DeltaTime) + local scroll_speed = IM_ROUND(window.FontRefSize * 100 * io.DeltaTime) -- We need round the scrolling speed because sub-pixel scroll isn't reliably supported. local move_dir = g.NavMoveDir if window.DC.NavLayersActiveMask == 0x00 and window.DC.NavWindowHasScrollY and move_dir ~= ImGuiDir.None then if move_dir == ImGuiDir.Left or move_dir == ImGuiDir.Right then @@ -14465,6 +16884,8 @@ function ImGui.NavUpdate() end end + -- *Normal* Manual scroll with LStick + -- Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. if nav_gamepad_active then local scroll_dir = ImGui.GetKeyMagnitude2d(ImGuiKey.GamepadLStickLeft, ImGuiKey.GamepadLStickRight, ImGuiKey.GamepadLStickUp, ImGuiKey.GamepadLStickDown) local tweak_factor = 1.0 @@ -14482,21 +16903,29 @@ function ImGui.NavUpdate() end end + -- Always prioritize mouse highlight if navigation is disabled if not nav_keyboard_active and not nav_gamepad_active then g.NavCursorVisible = false g.NavHighlightItemUnderNav = false set_mouse_pos = false end + -- Update mouse position if requested + -- (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied) if set_mouse_pos and io.ConfigNavMoveSetMousePos and bit32.band(io.BackendFlags, ImGuiBackendFlags.HasSetMousePos) ~= 0 then ImGui.TeleportMousePos(ImGui.NavCalcPreferredRefPos(ImGuiWindowFlags.Popup)) end + -- [DEBUG] g.NavScoringDebugCount = 0 end end +-- Process Escape/NavCancel input (to close a popup, get back to parent, clear focus) +-- FIXME: In order to support e.g. Escape to clear a selection we'll need: +-- - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it. +-- - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept function ImGui.NavUpdateCancelRequest() local g = GImGui local nav_gamepad_active = bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0 and bit32.band(g.IO.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0 @@ -14509,9 +16938,11 @@ function ImGui.NavUpdateCancelRequest() if g.ActiveId ~= 0 then ImGui.ClearActiveID() elseif g.NavLayer ~= ImGuiNavLayer.Main then + -- Leave the "menu" layer ImGui.NavRestoreLayer(ImGuiNavLayer.Main) ImGui.SetNavCursorVisibleAfterMove() elseif g.NavWindow and g.NavWindow ~= g.NavWindow.RootWindow and bit32.band(g.NavWindow.RootWindowForNav.Flags, ImGuiWindowFlags.Popup) == 0 and g.NavWindow.RootWindowForNav.ParentWindow then + -- Exit child window local child_window = g.NavWindow.RootWindowForNav local parent_window = child_window.ParentWindow IM_ASSERT(child_window.ChildId ~= 0) @@ -14519,13 +16950,18 @@ function ImGui.NavUpdateCancelRequest() ImGui.SetNavID(child_window.ChildId, ImGuiNavLayer.Main, 0, ImGui.WindowRectAbsToRel(parent_window, child_window:Rect())) ImGui.SetNavCursorVisibleAfterMove() elseif g.OpenPopupStack.Size > 0 and g.OpenPopupStack:back().Window ~= nil and bit32.band(g.OpenPopupStack:back().Window.Flags, ImGuiWindowFlags.Modal) == 0 then + -- Close open popup/menu ImGui.ClosePopupToLevel(g.OpenPopupStack.Size - 1, true) else + -- Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were + -- FIXME-NAV: This should happen on window appearing. if g.IO.ConfigNavEscapeClearFocusItem or g.IO.ConfigNavEscapeClearFocusWindow then - if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.Popup) ~= 0 then + if g.NavWindow and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.Popup) ~= 0 then -- or not (g.NavWindow.Flags & ImGuiWindowFlags.ChildWindow) g.NavWindow.NavLastIds[0] = 0 end end + + -- Clear nav focus if g.IO.ConfigNavEscapeClearFocusItem or g.IO.ConfigNavEscapeClearFocusWindow then g.NavId = 0 end @@ -14557,6 +16993,7 @@ local function NavScoreItemDistInterval(cand_min, cand_max, curr_min, curr_max) return 0.0 end +-- Scoring function for keyboard/gamepad directional navigation. Based on https://gist.github.com/rygorous/6981057 --- @param result ImGuiNavItemData --- @param nav_bb ImRect --- @return bool @@ -14567,70 +17004,93 @@ function ImGui.NavScoreItem(result, nav_bb) return false end + -- FIXME: Those are not good variables names local cand = ImRect() - ImRect_Copy(cand, nav_bb) - local curr = g.NavScoringRect + ImRect_Copy(cand, nav_bb) -- Current item nav rectangle + local 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 = g.NavScoringDebugCount + 1 + -- When entering through a NavFlattened border, we consider child window items as fully clipped for scoring if window.ParentWindow == g.NavWindow then IM_ASSERT(bit32.band(bit32.bor(window.ChildFlags, g.NavWindow.ChildFlags), ImGuiChildFlags.NavFlattened) ~= 0) if not window.ClipRect:Overlaps(cand) then return false end - cand:ClipWithFull(window.ClipRect) + cand:ClipWithFull(window.ClipRect) -- This allows the scored item to not overlap other candidates in the parent window end + -- Compute distance between boxes + -- FIXME-NAV: Introducing biases for vertical navigation, needs to be removed. local dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x) - local dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2), ImLerp(cand.Min.y, cand.Max.y, 0.8), ImLerp(curr.Min.y, curr.Max.y, 0.2), ImLerp(curr.Min.y, curr.Max.y, 0.8)) + local dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2), ImLerp(cand.Min.y, cand.Max.y, 0.8), ImLerp(curr.Min.y, curr.Max.y, 0.2), ImLerp(curr.Min.y, curr.Max.y, 0.8)) -- Scale down on Y to keep using box-distance for vertically touching items if dby ~= 0.0 and dbx ~= 0.0 then dbx = (dbx / 1000.0) + ((dbx > 0.0) and 1.0 or -1.0) end local dist_box = ImFabs(dbx) + ImFabs(dby) + -- Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) local dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x) local dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y) - local dist_center = ImFabs(dcx) + ImFabs(dcy) + local dist_center = ImFabs(dcx) + ImFabs(dcy) -- L1 metric (need this for our connectedness guarantee) + -- Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance local quadrant local dax = 0.0 local day = 0.0 local dist_axial = 0.0 if dbx ~= 0.0 or dby ~= 0.0 then + -- For non-overlapping boxes, use distance between boxes + -- FIXME-NAV: Quadrant may be incorrect because of (1) dbx bias and (2) curr.Max.y bias applied by NavBiasScoringRect() where typically curr.Max.y==curr.Min.y + -- One typical case where this happens, with style.WindowMenuButtonPosition == ImGuiDir.Right, pressing Left to navigate from Close to Collapse tends to fail. + -- Also see #6344. Calling ImGetDirQuadrantFromDelta() with unbiased values may be good but side-effects are plenty. dax = dbx day = dby dist_axial = dist_box quadrant = ImGetDirQuadrantFromDelta(dbx, dby) elseif dcx ~= 0.0 or dcy ~= 0.0 then + -- For overlapping boxes with different centers, use distance between centers dax = dcx day = dcy dist_axial = dist_center quadrant = ImGetDirQuadrantFromDelta(dcx, dcy) else + -- Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter) quadrant = (g.LastItemData.ID < g.NavId) and ImGuiDir.Left or ImGuiDir.Right end local move_dir = g.NavMoveDir + -- Is it in the quadrant we're interested in moving to? local new_best = false if quadrant == move_dir then + -- Does it beat the current best candidate? if dist_box < result.DistBox then result.DistBox = dist_box result.DistCenter = dist_center return true end if dist_box == result.DistBox then + -- Try using distance between center points to break ties if dist_center < result.DistCenter then result.DistCenter = dist_center new_best = true elseif dist_center == result.DistCenter then - if (((move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and dby) or dbx) < 0.0 then + -- Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items + -- (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index), + -- this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis. + if (((move_dir == ImGuiDir.Up or move_dir == ImGuiDir.Down) and dby) or dbx) < 0.0 then -- moving bj to the right/down decreases distance new_best = true end end end end - if result.DistBox == FLT_MAX and dist_axial < result.DistAxial then + -- Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches + -- are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness) + -- This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too. + -- 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward. + -- Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option? + if result.DistBox == FLT_MAX and dist_axial < result.DistAxial then -- Check axial match if g.NavLayer == ImGuiNavLayer.Menu and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.ChildMenu) == 0 then if (move_dir == ImGuiDir.Left and dax < 0.0) or (move_dir == ImGuiDir.Right and dax > 0.0) or (move_dir == ImGuiDir.Up and day < 0.0) or (move_dir == ImGuiDir.Down and day > 0.0) then result.DistAxial = dist_axial @@ -14653,18 +17113,25 @@ function ImGui.NavApplyItemToResult(result) ImRect_Copy(result.RectRel, ImGui.WindowRectAbsToRel(window, g.LastItemData.NavRect)) if bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 then IM_ASSERT(g.NextItemData.SelectionUserData ~= ImGuiSelectionUserData_Invalid) - result.SelectionUserData = g.NextItemData.SelectionUserData + result.SelectionUserData = g.NextItemData.SelectionUserData -- INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData. end end --- @param result ImGuiNavItemData function ImGui.NavMoveRequestResolveWithLastItem(result) local g = GImGui - g.NavMoveScoringItems = false + g.NavMoveScoringItems = false -- Ensure request doesn't need more processing ImGui.NavApplyItemToResult(result) ImGui.NavUpdateAnyRequestFlag() end +-- Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest(). +-- Note that SetKeyboardFocusHere() API calls are considered tabbing requests! +-- - Case 1: no nav/active id: set result to first eligible item, stop storing. +-- - Case 2: tab forward: on ref id set counter, on counter elapse store result +-- - Case 3: tab forward wrap: set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. -- FIXME-TABBING: Could be done as a next-frame forwarded request +-- - Case 4: tab backward: store all results, on ref id pick prev, stop storing +-- - Case 5: tab backward wrap: store all results, on ref id if no result keep storing until last -- FIXME-TABBING: Could be done as next-frame forwarded requested --- @param id ImGuiID --- @param item_flags ImGuiItemFlags --- @param move_flags ImGuiNavMoveFlags @@ -14680,6 +17147,9 @@ function ImGui.NavProcessItemForTabbingRequest(id, item_flags, move_flags) end end + -- - Can always land on an item when using API call. + -- - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item. + -- - Tabbing without _NavEnableKeyboard: goes through inputable items only. local can_stop if bit32.band(move_flags, ImGuiNavMoveFlags.FocusApi) ~= 0 then can_stop = true @@ -14687,8 +17157,10 @@ function ImGui.NavProcessItemForTabbingRequest(id, item_flags, move_flags) can_stop = bit32.band(item_flags, ImGuiItemFlags.NoTabStop) == 0 and (bit32.band(g.IO.ConfigFlags, ImGuiConfigFlags.NavEnableKeyboard) ~= 0 or bit32.band(item_flags, ImGuiItemFlags.Inputable) ~= 0) end + -- Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows) local result = g.NavMoveResultLocal if g.NavTabbingDir == 1 then + -- Tab Forward or SetKeyboardFocusHere() with >= 0 if can_stop and g.NavTabbingResultFirst.ID == 0 then ImGui.NavApplyItemToResult(g.NavTabbingResultFirst) end @@ -14701,30 +17173,35 @@ function ImGui.NavProcessItemForTabbingRequest(id, item_flags, move_flags) g.NavTabbingCounter = 1 end elseif g.NavTabbingDir == -1 then + -- Tab Backward if g.NavId == id then if result.ID ~= 0 then g.NavMoveScoringItems = false ImGui.NavUpdateAnyRequestFlag() end elseif can_stop then + -- Keep applying until reaching NavId ImGui.NavApplyItemToResult(result) end elseif g.NavTabbingDir == 0 then if can_stop and g.NavId == id then ImGui.NavMoveRequestResolveWithLastItem(result) end - if can_stop and g.NavTabbingResultFirst.ID == 0 then + if can_stop and g.NavTabbingResultFirst.ID == 0 then -- Tab init ImGui.NavApplyItemToResult(g.NavTabbingResultFirst) end end end +-- We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above) +-- This is called after LastItemData is set, but NextItemData is also still valid. function ImGui.NavProcessItem() local g = GImGui local window = g.CurrentWindow local id = g.LastItemData.ID local item_flags = g.LastItemData.ItemFlags + -- When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221, #8816, #7994) local nav_bb = ImRect() ImRect_Copy(nav_bb, g.LastItemData.NavRect) if window.DC.NavIsScrollPushableX == false then @@ -14732,17 +17209,21 @@ function ImGui.NavProcessItem() nav_bb.Max.x = ImClamp(nav_bb.Max.x, window.ClipRect.Min.x, window.ClipRect.Max.x) end + -- Process Init Request if g.NavInitRequest and g.NavLayer == window.DC.NavLayerCurrent and bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then + -- Even if 'ImGuiItemFlags.NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback local candidate_for_nav_default_focus = bit32.band(item_flags, ImGuiItemFlags.NoNavDefaultFocus) == 0 if candidate_for_nav_default_focus or g.NavInitResult.ID == 0 then ImGui.NavApplyItemToResult(g.NavInitResult) end if candidate_for_nav_default_focus then - g.NavInitRequest = false + g.NavInitRequest = false -- Found a match, clear request ImGui.NavUpdateAnyRequestFlag() end end + -- Process Move Request (scoring for navigation) + -- FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy) if g.NavMoveScoringItems and bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.FocusApi) ~= 0 or bit32.band(window.Flags, ImGuiWindowFlags.NoNavInputs) == 0 then local is_tabbing = bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 @@ -14754,9 +17235,10 @@ function ImGui.NavProcessItem() ImGui.NavApplyItemToResult(result) end + -- Features like PageUp/PageDown need to maintain a separate score for the visible set of items. local VISIBLE_RATIO = 0.70 if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) ~= 0 then - local r = window.InnerRect + local r = window.InnerRect -- window.ClipRect if r:Overlaps(nav_bb) then if ImClamp(nav_bb.Max.y, r.Min.y, r.Max.y) - ImClamp(nav_bb.Min.y, r.Min.y, r.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO then if ImGui.NavScoreItem(g.NavMoveResultLocalVisible, nav_bb) then @@ -14769,24 +17251,26 @@ function ImGui.NavProcessItem() end end + -- Update information for currently focused/navigated item if g.NavId == id then if g.NavWindow ~= window then - ImGui.SetNavWindow(window) + ImGui.SetNavWindow(window) -- Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window. end g.NavLayer = window.DC.NavLayerCurrent - ImGui.SetNavFocusScope(g.CurrentFocusScopeId) + ImGui.SetNavFocusScope(g.CurrentFocusScopeId) -- Will set g.NavFocusScopeId AND store g.NavFocusScopePath g.NavFocusScopeId = g.CurrentFocusScopeId g.NavIdIsAlive = true g.NavIdItemFlags = item_flags if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 then IM_ASSERT(g.NextItemData.SelectionUserData ~= ImGuiSelectionUserData_Invalid) - g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData + g.NavLastValidSelectionUserData = g.NextItemData.SelectionUserData -- INTENTIONAL: At this point this field is not cleared in NextItemData. Avoid unnecessary copy to LastItemData. end - window.NavRectRel[window.DC.NavLayerCurrent] = ImGui.WindowRectAbsToRel(window, nav_bb) + window.NavRectRel[window.DC.NavLayerCurrent] = ImGui.WindowRectAbsToRel(window, nav_bb) -- Store item bounding box (relative to window position) end end function ImGui.NavInitRequestApplyResult() + -- In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void) local g = GImGui if not g.NavWindow then return @@ -14802,8 +17286,11 @@ function ImGui.NavInitRequestApplyResult() g.NavJustMovedToHasSelectionData = bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 end + -- Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) + -- FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently. + -- IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) ImGui.SetNavID(result.ID, g.NavLayer, result.FocusScopeId, result.RectRel) - g.NavIdIsAlive = true + g.NavIdIsAlive = true -- Mark as alive from previous frame as we got a result if result.SelectionUserData ~= ImGuiSelectionUserData_Invalid then g.NavLastValidSelectionUserData = result.SelectionUserData end @@ -14812,9 +17299,11 @@ function ImGui.NavInitRequestApplyResult() end end +-- Apply result from previous frame navigation directional move request. Always called from NavUpdate() function ImGui.NavMoveRequestApplyResult() local g = GImGui + -- Select which result to use local result if g.NavMoveResultLocal.ID ~= 0 then result = g.NavMoveResultLocal @@ -14824,12 +17313,14 @@ function ImGui.NavMoveRequestApplyResult() result = nil end + -- Tabbing forward wrap if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 and result == nil then if (g.NavTabbingCounter == 1 or g.NavTabbingDir == 0) and g.NavTabbingResultFirst.ID ~= 0 then result = g.NavTabbingResultFirst end end + -- In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result) local axis = (g.NavMoveDir == ImGuiDir.Up or g.NavMoveDir == ImGuiDir.Down) and ImGuiAxis.Y or ImGuiAxis.X if result == nil then if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 then @@ -14838,15 +17329,18 @@ function ImGui.NavMoveRequestApplyResult() if g.NavId ~= 0 and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSetNavCursorVisible) == 0 then ImGui.SetNavCursorVisibleAfterMove() end - ImGui.NavClearPreferredPosForAxis(axis) + ImGui.NavClearPreferredPosForAxis(axis) -- On a failed move, clear preferred pos for this axis. + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n") return end + -- PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page. if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.AlsoScoreVisibleSet) ~= 0 and g.NavMoveResultLocalVisible.ID ~= 0 and g.NavMoveResultLocalVisible.ID ~= g.NavId then result = g.NavMoveResultLocalVisible end + -- Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules. if result ~= g.NavMoveResultOther and g.NavMoveResultOther.ID ~= 0 and g.NavMoveResultOther.Window.ParentWindow == g.NavWindow then if g.NavMoveResultOther.DistBox < result.DistBox or (g.NavMoveResultOther.DistBox == result.DistBox and g.NavMoveResultOther.DistCenter < result.DistCenter) then @@ -14855,24 +17349,33 @@ function ImGui.NavMoveRequestApplyResult() end IM_ASSERT(g.NavWindow and result.Window) + -- Scroll to keep newly navigated item fully into view. if g.NavLayer == ImGuiNavLayer.Main then local rect_abs = ImGui.WindowRectRelToAbs(result.Window, result.RectRel) ImGui.ScrollToRectEx(result.Window, rect_abs, g.NavMoveScrollFlags) + if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.ScrollToEdgeY) ~= 0 then + -- FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge? local scroll_target = (g.NavMoveDir == ImGuiDir.Up) and result.Window.ScrollMax.y or 0.0 ImGui.SetScrollY(result.Window, scroll_target) end end if g.NavWindow ~= result.Window then + -- IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name) g.NavWindow = result.Window g.NavLastValidSelectionUserData = ImGuiSelectionUserData_Invalid end + -- Clear active id unless requested not to + -- FIXME: ImGuiNavMoveFlags.NoClearActiveId is currently unused as we don't have a clear strategy to preserve active id after interaction, + -- so this is mostly provided as a gateway for further experiments (see #1418, #2890) if g.ActiveId ~= result.ID and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoClearActiveId) == 0 then ImGui.ClearActiveID() end + -- Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags.AllowCurrentNavId) + -- PageUp/PageDown however sets always set NavJustMovedTo (vs Home/End which doesn't) mimicking Windows behavior. if (g.NavId ~= result.ID or bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsPageMove) ~= 0) and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSelect) == 0 then g.NavJustMovedFromFocusScopeId = g.NavFocusScopeId @@ -14881,8 +17384,11 @@ function ImGui.NavMoveRequestApplyResult() g.NavJustMovedToKeyMods = g.NavMoveKeyMods g.NavJustMovedToIsTabbing = bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 g.NavJustMovedToHasSelectionData = bit32.band(result.ItemFlags, ImGuiItemFlags.HasSelectionUserData) ~= 0 + -- IMGUI_DEBUG_LOG_NAV("[nav] NavJustMovedFromFocusScopeId = 0x%08X, NavJustMovedToFocusScopeId = 0x%08X\n", g.NavJustMovedFromFocusScopeId, g.NavJustMovedToFocusScopeId) end + -- Apply new NavID/Focus + -- IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name) local root_for_nav = g.NavWindow.RootWindowForNav local preferred_scoring_pos_rel = ImVec2() ImVec2_Copy(preferred_scoring_pos_rel, root_for_nav.NavPreferredScoringPosRel[g.NavLayer]) @@ -14891,16 +17397,20 @@ function ImGui.NavMoveRequestApplyResult() g.NavLastValidSelectionUserData = result.SelectionUserData end + -- Restore last preferred position for current axis + -- (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..) if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) == 0 then preferred_scoring_pos_rel[axis] = result.RectRel:GetCenter()[axis] ImVec2_Copy(root_for_nav.NavPreferredScoringPosRel[g.NavLayer], preferred_scoring_pos_rel) end + -- Tabbing: Activates Inputable, otherwise only Focus if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.IsTabbing) ~= 0 and bit32.band(result.ItemFlags, ImGuiItemFlags.Inputable) == 0 then g.NavMoveFlags = bit32.band(g.NavMoveFlags, bit32.bnot(ImGuiNavMoveFlags.Activate)) end + -- Activate if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Activate) ~= 0 then g.NavNextActivateId = result.ID g.NavNextActivateFlags = ImGuiActivateFlags.None @@ -14912,26 +17422,30 @@ function ImGui.NavMoveRequestApplyResult() end end + -- Make nav cursor visible if bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.NoSetNavCursorVisible) == 0 then ImGui.SetNavCursorVisibleAfterMove() end end +-- True when current work location may be scrolled horizontally when moving left / right. +-- This is generally always true UNLESS within a column. We don't have a vertical equivalent. function ImGui.NavUpdateCurrentWindowIsScrollPushableX() local g = GImGui local window = g.CurrentWindow window.DC.NavIsScrollPushableX = (g.CurrentTable == nil and window.DC.CurrentColumns == nil) end +-- Called by TreePop() to implement ImGuiTreeNodeFlags.NavLeftJumpsToParent --- @param result ImGuiNavItemData --- @param tree_node_data ImGuiTreeNodeStackData function ImGui.NavMoveRequestResolveWithPastTreeNode(result, tree_node_data) local g = GImGui g.NavMoveScoringItems = false g.LastItemData.ID = tree_node_data.ID - g.LastItemData.ItemFlags = bit32.band(tree_node_data.ItemFlags, bit32.bnot(ImGuiItemFlags.HasSelectionUserData)) + g.LastItemData.ItemFlags = bit32.band(tree_node_data.ItemFlags, bit32.bnot(ImGuiItemFlags.HasSelectionUserData)) -- Losing SelectionUserData, recovered next-frame (cheaper). ImRect_Copy(g.LastItemData.NavRect, tree_node_data.NavRect) - ImGui.NavApplyItemToResult(result) + ImGui.NavApplyItemToResult(result) -- Result this instead of implementing a NavApplyPastTreeNodeToResult() ImGui.NavClearPreferredPosForAxis(ImGuiAxis.Y) ImGui.NavUpdateAnyRequestFlag() end @@ -14943,6 +17457,7 @@ function ImGui.NavMoveRequestCancel() ImGui.NavUpdateAnyRequestFlag() end +-- Forward will reuse the move request again on the next frame (generally with modifications done to it) --- @param move_dir ImGuiDir --- @param clip_dir ImGuiDir --- @param move_flags ImGuiNavMoveFlags @@ -14958,29 +17473,33 @@ function ImGui.NavMoveRequestForward(move_dir, clip_dir, move_flags, scroll_flag g.NavMoveScrollFlags = scroll_flags end +-- Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire +-- popup is assembled and in case of appended popups it is not clear which EndPopup() call is final. --- @param window ImGuiWindow --- @param wrap_flags ImGuiNavMoveFlags function ImGui.NavMoveRequestTryWrapping(window, wrap_flags) local g = GImGui - IM_ASSERT(bit32.band(wrap_flags, ImGuiNavMoveFlags.WrapMask_) ~= 0 and bit32.band(wrap_flags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)) == 0) + IM_ASSERT(bit32.band(wrap_flags, ImGuiNavMoveFlags.WrapMask_) ~= 0 and bit32.band(wrap_flags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)) == 0) -- Call with _WrapX, _WrapY, _LoopX, _LoopY + -- In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it: + -- as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest(). if g.NavWindow == window and g.NavMoveScoringItems and g.NavLayer == window.DC.NavLayerCurrent then g.NavMoveFlags = bit32.bor(bit32.band(g.NavMoveFlags, bit32.bnot(ImGuiNavMoveFlags.WrapMask_)), wrap_flags) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] DRAG AND DROP ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.IsDragDropPayloadBeingAccepted() local g = GImGui return g.DragDropActive and g.DragDropAcceptIdPrev ~= 0 end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] LOCALIZATION ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- @param entries ImGuiLocEntry[] --- @param count int @@ -14991,9 +17510,32 @@ function ImGui.LocalizeRegisterEntries(entries, count) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] VIEWPORTS, PLATFORM WINDOWS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - GetMainViewport() +-- - FindViewportByID() +-- - SetCurrentViewport() [Internal] +-- - SetWindowViewport() [Internal] +-- - GetWindowAlwaysWantOwnViewport() [Internal] +-- - UpdateTryMergeWindowIntoHostViewport() [Internal] +-- - UpdateTryMergeWindowIntoHostViewports() [Internal] +-- - TranslateWindowsInViewport() [Internal] +-- - ScaleWindowsInViewport() [Internal] +-- - FindHoveredViewportFromPlatformWindowStack() [Internal] +-- - UpdateViewportsNewFrame() [Internal] +-- - UpdateViewportsEndFrame() [Internal] +-- - AddUpdateViewport() [Internal] +-- - WindowSelectViewport() [Internal] +-- - WindowSyncOwnedViewport() [Internal] +-- - UpdatePlatformWindows() +-- - RenderPlatformWindowsDefault() +-- - FindPlatformMonitorForPos() [Internal] +-- - FindPlatformMonitorForRect() [Internal] +-- - UpdateViewportPlatformMonitor() [Internal] +-- - DestroyPlatformWindow() [Internal] +-- - DestroyPlatformWindows() +------------------------------------------------------------------------------- function MT.ImGuiViewport:GetDebugName() local viewport = self @@ -15029,6 +17571,7 @@ function ImGui.GetMainViewport() return g.Viewports[1] end +-- FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236) --- @param viewport_id ImGuiID --- @return ImGuiViewport? function ImGui.FindViewportByID(viewport_id) @@ -15101,8 +17644,8 @@ function ImGui.GetWindowAlwaysWantOwnViewport(window) return false end ---- Heuristic, see #8948: depends on how backends handle OS-level parenting. ---- Due to how parent viewport stack is layed out, note that IsViewportAbove(a,b) isn't always the same as !IsViewportAbove(b,a). +-- Heuristic, see #8948: depends on how backends handle OS-level parenting. +-- Due to how parent viewport stack is layed out, note that IsViewportAbove(a,b) isn't always the same as !IsViewportAbove(b,a). --- @param potential_above ImGuiViewportP --- @param potential_below ImGuiViewportP --- @return bool @@ -15196,8 +17739,8 @@ function ImGui.UpdateTryMergeWindowIntoHostViewports(window) return ImGui.UpdateTryMergeWindowIntoHostViewport(window, g.Viewports.Data[1]) end ---- Translate Dear ImGui windows when a Host Viewport has been moved ---- (This additionally keeps windows at the same place when ImGuiConfigFlags.ViewportsEnable is toggled!) +-- Translate Dear ImGui windows when a Host Viewport has been moved +-- (This additionally keeps windows at the same place when ImGuiConfigFlags.ViewportsEnable is toggled!) --- @param viewport ImGuiViewportP --- @param old_pos ImVec2 --- @param new_pos ImVec2 @@ -15224,7 +17767,7 @@ function ImGui.TranslateWindowsInViewport(viewport, old_pos, new_pos, old_size, end end --- If the backend doesn't support ImGuiBackendFlags_HasMouseHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs for it, we do a search ourselves. +-- If the backend doesn't support ImGuiBackendFlags.HasMouseHoveredViewport or doesn't honor ImGuiViewportFlags.NoInputs for it, we do a search ourselves. -- A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window. -- B) It requires Platform_GetWindowFocus to be implemented by backend. --- @param mouse_platform_pos ImVec2 @@ -15244,6 +17787,8 @@ function ImGui.FindHoveredViewportFromPlatformWindowStack(mouse_platform_pos) return best_candidate end +-- Update viewports and monitor infos +-- Note that this is running even if 'ImGuiConfigFlags.ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info. function ImGui.UpdateViewportsNewFrame() local g = GImGui IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size) @@ -15400,6 +17945,7 @@ function ImGui.UpdateViewportsNewFrame() viewport:UpdateWorkRect() + -- Garbage collect transient buffers of recently BG/FG drawlists for dl_n = 1, 2 do -- IM_COUNTOF(viewport->BgFgDrawLists) if viewport.BgFgDrawListsLastTimeActive[dl_n] < memory_compact_start_time and viewport.BgFgDrawLists[dl_n] ~= nil then IM_DELETE(viewport.BgFgDrawLists, dl_n) @@ -15529,6 +18075,7 @@ function ImGui.UpdateViewportsNewFrame() IM_ASSERT(g.MouseViewport ~= nil) end +-- Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some) function ImGui.UpdateViewportsEndFrame() local g = GImGui g.PlatformIO.Viewports:resize(0) @@ -15539,7 +18086,7 @@ function ImGui.UpdateViewportsEndFrame() ImVec2_Copy(viewport.LastPos, ImVec2(viewport.Pos.x, viewport.Pos.y)) ImVec2_Copy(viewport.LastSize, ImVec2(viewport.Size.x, viewport.Size.y)) - if (viewport.LastFrameActive < g.FrameCount or viewport.Size.x <= 0.0 or viewport.Size.y <= 0.0) and (i > 1) then + if (viewport.LastFrameActive < g.FrameCount or viewport.Size.x <= 0.0 or viewport.Size.y <= 0.0) and (i > 1) then -- Always include main viewport in the list break end if viewport.Window and not ImGui.IsWindowActiveAndVisible(viewport.Window) then @@ -15556,6 +18103,7 @@ function ImGui.UpdateViewportsEndFrame() g.Viewports.Data[1]:ClearRequestFlags() -- Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called end +-- FIXME: We should ideally refactor the system to call this every frame (we currently don't) --- @param window? ImGuiWindow --- @param id ImGuiID --- @param pos ImVec2 @@ -15593,8 +18141,7 @@ function ImGui.AddUpdateViewport(window, id, pos, size, flags) if not viewport.PlatformRequestResize or viewport.ID == IMGUI_VIEWPORT_DEFAULT_ID then ImVec2_Copy(viewport.Size, size) end - -- Preserve existing flags - viewport.Flags = bit32.bor(flags, bit32.band(viewport.Flags, bit32.bor(ImGuiViewportFlags.IsMinimized, ImGuiViewportFlags.IsFocused))) + viewport.Flags = bit32.bor(flags, bit32.band(viewport.Flags, bit32.bor(ImGuiViewportFlags.IsMinimized, ImGuiViewportFlags.IsFocused))) -- Preserve existing flags if prev_pos.x ~= viewport.Pos.x or prev_pos.y ~= viewport.Pos.y or prev_size.x ~= viewport.Size.x or prev_size.y ~= viewport.Size.y then ImGui.UpdateViewportPlatformMonitor(viewport) end @@ -15667,6 +18214,7 @@ function ImGui.DestroyViewport(viewport) -- IM_DELETE(viewport) end +-- FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten. --- @param window ImGuiWindow function ImGui.WindowSelectViewport(window) local g = GImGui @@ -15845,7 +18393,7 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) -- Not correct to set modal as topmost because: -- - Because other popups can be stacked above a modal (e.g. combo box in a modal) - -- - ImGuiViewportFlags.TopMost is currently handled different in backends + -- - ImGuiViewportFlags.TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost" -- if bit32.band(window_flags, ImGuiWindowFlags.Modal) ~= 0 then -- viewport_flags = bit32.bor(viewport_flags, ImGuiViewportFlags.TopMost) -- end @@ -15896,6 +18444,8 @@ function ImGui.WindowSyncOwnedViewport(window, parent_window_in_stack) end end +-- Called by user at the end of the main loop, after EndFrame() +-- This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api. function ImGui.UpdatePlatformWindows() local g = GImGui IM_ASSERT(g.FrameCountEnded == g.FrameCount, "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?") @@ -16057,6 +18607,9 @@ function ImGui.FindPlatformMonitorForPos(pos) return -1 end +-- Search for the monitor with the largest intersection area with the given rectangle +-- We generally try to avoid searching loops but the monitor count should be very small here +-- FIXME-OPT: We could test the last monitor used for that viewport first, and early --- @param rect ImRect --- @return int function ImGui.FindPlatformMonitorForRect(rect) @@ -16098,11 +18651,13 @@ function ImGui.FindPlatformMonitorForRect(rect) return best_monitor_n end +-- Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor) --- @param viewport ImGuiViewportP function ImGui.UpdateViewportPlatformMonitor(viewport) viewport.PlatformMonitor = ImGui.FindPlatformMonitorForRect(viewport:GetMainRect()) end +-- Return value is always ~= nil, but don't hold on it across frames. --- @param viewport_p ImGuiViewport --- @return ImGuiPlatformMonitor function ImGui.GetViewportPlatformMonitor(viewport_p) @@ -16144,15 +18699,24 @@ function ImGui.DestroyPlatformWindow(viewport) end function ImGui.DestroyPlatformWindows() + -- We call the destroy window on every viewport (including the main viewport, index 1) to give a chance to the backend + -- to clear any data they may have stored in e.g. PlatformUserData, RendererUserData. + -- It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling + -- code to operator a consistent manner. + -- It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without + -- crashing if it doesn't have data stored. local g = GImGui for _, viewport in g.Viewports:iter() do ImGui.DestroyPlatformWindow(viewport) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] METRICS/DEBUGGER WINDOW ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - DebugRenderViewportThumbnail() [Internal] +-- - RenderViewportsThumbnails() [Internal] +------------------------------------------------------------------------------- --- @param draw_list ImDrawList --- @param viewport ImGuiViewport @@ -16178,7 +18742,7 @@ function ImGui.DebugRenderViewportThumbnail(draw_list, viewport, bb) local thumb_r = thumb_window:Rect() local title_r = thumb_window:TitleBarRect() thumb_r = ImRect(ImTrunc(off + thumb_r.Min * scale), ImTrunc(off + thumb_r.Max * scale)) - title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r:GetHeight() * 3.0) * scale)) + title_r = ImRect(ImTrunc(off + title_r.Min * scale), ImTrunc(off + ImVec2(title_r.Max.x, title_r.Min.y + title_r:GetHeight() * 3.0) * scale)) -- Exaggerate title bar height thumb_r:ClipWithFull(bb) title_r:ClipWithFull(bb) local window_is_focused = g.NavWindow and thumb_window.RootWindowForTitleBarHighlight == g.NavWindow.RootWindowForTitleBarHighlight @@ -16200,6 +18764,7 @@ function ImGui.RenderViewportsThumbnails() local g = GImGui local window = g.CurrentWindow + -- Draw monitor and calculate their boundaries local SCALE = 1.0 / 8.0 local bb_full = ImRect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX) for _, monitor in g.PlatformIO.Monitors:iter() do @@ -16214,6 +18779,7 @@ function ImGui.RenderViewportsThumbnails() window.DrawList:AddRectFilled(monitor_draw_bb.Min, monitor_draw_bb.Max, ImGui.GetColorU32(ImGuiCol.Border, 0.10), 4.0) end + -- Draw viewports for _, viewport in g.Viewports:iter() do local viewport_draw_bb = ImRect(off + viewport.Pos * SCALE, off + (viewport.Pos + viewport.Size) * SCALE) ImGui.DebugRenderViewportThumbnail(window.DrawList, viewport, viewport_draw_bb) @@ -16230,6 +18796,19 @@ function ImGui.GetStyleColorVec4(idx) return GImGui.Style.Colors[idx] end +-- 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. +-- +-- 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. function ImGui.ErrorCheckUsingSetCursorPosToExtendParentBoundaries() local g = GImGui local window = g.CurrentWindow @@ -16242,9 +18821,9 @@ function ImGui.ErrorCheckUsingSetCursorPosToExtendParentBoundaries() window.DC.CursorMaxPos = ImMax(window.DC.CursorMaxPos, window.DC.CursorPos) end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] POPUPS: modals, context popups, dimming ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- local function GetWindowDisplayLayer(window) return (bit32.band(window.Flags, ImGuiWindowFlags.Tooltip) ~= 0) and 1 or 0 @@ -16282,6 +18861,7 @@ function ImGui.FindBottomMostVisibleWindowWithinBeginStack(parent_window) return bottom_most_visible_window end +-- See Demo->Stacked Modal to confirm what this is for. function ImGui.GetTopMostAndVisiblePopupModal() local g = GImGui for n = g.OpenPopupStack.Size, 1, -1 do @@ -16298,18 +18878,22 @@ function ImGui.RenderDimmedBackgroundBehindWindow(window, col) local viewport = window.Viewport local viewport_rect = viewport:GetMainRect() -- Draw behind window by moving the draw command at the FRONT of the draw list + -- Draw list have been trimmed already, hence the explicit recreation of a draw command if missing. + -- FIXME: This is a little bit complicated, solely to avoid creating/injecting an extra drawlist in drawdata. local draw_list = (window.RootWindowDockTree or window.RootWindow).DrawList draw_list:ChannelsMerge() if draw_list.CmdBuffer.Size == 0 then draw_list:AddDrawCmd() end - draw_list:PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false) + draw_list:PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false) -- FIXME: Need to strictly ensure ImDrawCmd are not merged draw_list:AddRectFilled(viewport_rect.Min, viewport_rect.Max, col) local cmd = draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size] draw_list.CmdBuffer:pop_back() draw_list.CmdBuffer:push_front(cmd) - draw_list:AddDrawCmd() + draw_list:AddDrawCmd() -- We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command. draw_list:PopClipRect() end +-- Important: AddWindowToDrawData() has not been called yet, meaning DockNodeHost windows needs a DrawList:ChannelsMerge() before usage. +-- We call ChannelsMerge() lazily here at it is faster that doing a full iteration of g.Windows[] prior to calling RenderDimmedBackgrounds(). function ImGui.RenderDimmedBackgrounds() local g = GImGui local modal_window = ImGui.GetTopMostAndVisiblePopupModal() @@ -16319,24 +18903,27 @@ function ImGui.RenderDimmedBackgrounds() if not dim_bg_for_modal and not dim_bg_for_window_list then return end if dim_bg_for_modal then + -- Draw dimming behind modal or a begin stack child, whichever comes first in draw order. local dim_behind_window = ImGui.FindBottomMostVisibleWindowWithinBeginStack(modal_window) ImGui.RenderDimmedBackgroundBehindWindow(dim_behind_window, ImGui.GetColorU32(modal_window.DC.ModalDimBgColor, g.DimBgRatio, true)) elseif dim_bg_for_window_list then + -- Draw dimming behind Ctrl+Tab target window and behind Ctrl+Tab UI window ImGui.RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, ImGui.GetColorU32(ImGuiCol.NavWindowingDimBg, g.DimBgRatio)) if g.NavWindowingListWindow ~= nil and g.NavWindowingListWindow.Active and g.NavWindowingListWindow.Viewport and g.NavWindowingListWindow.Viewport ~= g.NavWindowingTargetAnim.Viewport then ImGui.RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, ImGui.GetColorU32(ImGuiCol.NavWindowingDimBg, g.DimBgRatio)) end + -- Draw border around Ctrl+Tab target window local window = g.NavWindowingTargetAnim local viewport = window.Viewport local distance = g.FontSize local bb = window:Rect() bb:Expand(distance) - if bb:GetWidth() >= viewport.Size.x and bb:GetHeight() >= viewport.Size.y then bb:Expand(-distance - 1.0) end + if bb:GetWidth() >= viewport.Size.x and bb:GetHeight() >= viewport.Size.y then bb:Expand(-distance - 1.0) end -- If a window fits the entire viewport, adjust its highlight inward window.DrawList:ChannelsMerge() if window.DrawList.CmdBuffer.Size == 0 then window.DrawList:AddDrawCmd() end window.DrawList:PushClipRect(viewport.Pos, viewport.Pos + viewport.Size) - window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.NavWindowingHighlight, g.NavWindowingHighlightAlpha), window.WindowRounding, 0, 3.0) + window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.NavWindowingHighlight, g.NavWindowingHighlightAlpha), window.WindowRounding, 0, 3.0) -- FIXME-DPI window.DrawList:PopClipRect() end end @@ -16349,11 +18936,15 @@ function ImGui.ClosePopupsExceptModals() if not window or bit32.band(window.Flags, ImGuiWindowFlags.Modal) ~= 0 then break end popup_count_to_keep = popup_count_to_keep - 1 end - if popup_count_to_keep < g.OpenPopupStack.Size then + if popup_count_to_keep < g.OpenPopupStack.Size then -- This test is not required but it allows to set a convenient breakpoint on the statement below ImGui.ClosePopupToLevel(popup_count_to_keep, true) end end +-- If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup. +-- Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup). +-- - p_open is returned set back to false by BeginPopupModal() when popup is not open. +-- - if you set p_open to false before calling BeginPopupModal(), it will close the popup. --- @return bool visible, bool? p_open # p_open is the updated value of the optional close button flag function ImGui.BeginPopupModal(name, p_open, flags) if flags == nil then flags = 0 end @@ -16361,20 +18952,23 @@ function ImGui.BeginPopupModal(name, p_open, flags) local window = g.CurrentWindow local id = window:GetID(name) if not ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values if p_open then p_open = false end return false, p_open end + -- 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 bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasPos) == 0 then - local viewport = window.WasActive and window.Viewport or ImGui.GetMainViewport() + local viewport = window.WasActive and window.Viewport or ImGui.GetMainViewport() -- FIXME-VIEWPORT: What may be our reference viewport? ImGui.SetNextWindowPos(viewport:GetCenter(), ImGuiCond.FirstUseEver, ImVec2(0.5, 0.5)) end flags = bit32.bor(flags, ImGuiWindowFlags.Popup, ImGuiWindowFlags.Modal, ImGuiWindowFlags.NoCollapse, ImGuiWindowFlags.NoDocking) local is_open p_open, is_open = ImGui.Begin(name, p_open, flags) - if not is_open or (p_open ~= nil and not p_open) then + if not is_open or (p_open ~= nil and not p_open) then -- NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) ImGui.EndPopup() if is_open then ImGui.ClosePopupToLevel(g.BeginPopupStack.Size, true) end return false, p_open @@ -16391,7 +18985,7 @@ function ImGui.IsPopupOpenRequestForWindow(popup_flags) end end if g.NavOpenContextMenuWindowId and g.NavOpenContextMenuWindowId ~= 0 and g.CurrentWindow.ID ~= 0 then - if ImGui.IsWindowChildOf(g.NavWindow, g.CurrentWindow, false, false) then return true end + if ImGui.IsWindowChildOf(g.NavWindow, g.CurrentWindow, false, false) then return true end -- This enable ordering to be used to disambiguate item vs window (#8803) end return false end @@ -16411,7 +19005,7 @@ function ImGui.BeginPopupContextVoid(str_id, popup_flags) local g = GImGui local window = g.CurrentWindow if not str_id then str_id = "void_context" end - local id = window:GetID(str_id) + local id = window:GetID(str_id) -- FIXME: Use a global ID? local mouse_button = ImGui.GetMouseButtonFromPopupFlags(popup_flags) if ImGui.IsMouseReleased(mouse_button, id) and not ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) then if ImGui.GetTopMostPopupModal() == nil then ImGui.OpenPopupEx(id, popup_flags) end @@ -16427,7 +19021,9 @@ function ImGui.BeginTooltipHidden() return ret end +------------------------------------------------------------------------------- -- [SECTION] MISC GETTERS/SETTERS, FOCUS +------------------------------------------------------------------------------- function ImGui.NavMoveRequestResolveWithLastItem(result) local g = GImGui @@ -16436,12 +19032,18 @@ function ImGui.NavMoveRequestResolveWithLastItem(result) ImGui.NavUpdateAnyRequestFlag() end +-- Note: this will likely be called ActivateItem() once we rework our Focus/Activation system! +-- But ActivateItem() should function without altering scroll/focus? function ImGui.SetKeyboardFocusHere(offset) if offset == nil then offset = 0 end local g = GImGui local window = g.CurrentWindow IM_ASSERT(offset >= -1) -- -1 is allowed but not below + -- It makes sense in the vast majority of cases to never interrupt a drag and drop. + -- When we refactor this function into ActivateItem() we may want to make this an option. + -- MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but + -- is also automatically dropped in the event g.ActiveId is stolen. if g.DragDropActive or g.MovingWindow ~= nil then return end @@ -16450,7 +19052,7 @@ function ImGui.SetKeyboardFocusHere(offset) local move_flags = bit32.bor(ImGuiNavMoveFlags.IsTabbing, ImGuiNavMoveFlags.Activate, ImGuiNavMoveFlags.FocusApi, ImGuiNavMoveFlags.NoSetNavCursorVisible) local scroll_flags = window.Appearing and bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.AlwaysCenterY) or bit32.bor(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleEdgeY) - ImGui.NavMoveRequestSubmit(ImGuiDir.None, (offset < 0) and ImGuiDir.Up or ImGuiDir.Down, move_flags, scroll_flags) + ImGui.NavMoveRequestSubmit(ImGuiDir.None, (offset < 0) and ImGuiDir.Up or ImGuiDir.Down, move_flags, scroll_flags) -- FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable. if offset == -1 then ImGui.NavMoveRequestResolveWithLastItem(g.NavMoveResultLocal) else @@ -16459,10 +19061,11 @@ function ImGui.SetKeyboardFocusHere(offset) end end +-- Focus = move navigation cursor, set scrolling, set focus window. function ImGui.FocusItem() local g = GImGui local window = g.CurrentWindow - if g.DragDropActive or g.MovingWindow ~= nil then + if g.DragDropActive or g.MovingWindow ~= nil then -- FIXME: Opt-in flags for this? return end local move_flags = bit32.bor(ImGuiNavMoveFlags.IsTabbing, ImGuiNavMoveFlags.FocusApi, ImGuiNavMoveFlags.NoSetNavCursorVisible, ImGuiNavMoveFlags.NoSelect) @@ -16507,10 +19110,13 @@ function ImGui.GetStyleColorName(idx) return StyleColorNames[idx] or "Unknown" end +------------------------------------------------------------------------------- -- [SECTION] NAV END FRAME +------------------------------------------------------------------------------- local NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15 +-- Window has already passed the IsWindowNavFocusable() local function GetFallbackWindowNameForWindowingList(window) if bit32.band(window.Flags, ImGuiWindowFlags.Popup) ~= 0 then return "(Popup)" @@ -16519,11 +19125,12 @@ local function GetFallbackWindowNameForWindowingList(window) return "(Main menu bar)" end if window.DockNodeAsHost then - return "(Dock node)" + return "(Dock node)" -- Not normally shown to user. end return "(Untitled)" end +-- Overlay displayed when using Ctrl+Tab. Called by EndFrame(). function ImGui.NavUpdateWindowingOverlay() local g = GImGui IM_ASSERT(g.NavWindowingTarget ~= nil) @@ -16540,7 +19147,7 @@ function ImGui.NavUpdateWindowingOverlay() g.NavWindowingListWindow = g.CurrentWindow for n = g.WindowsFocusOrder.Size, 1, -1 do local window = g.WindowsFocusOrder.Data[n] - IM_ASSERT(window ~= nil) + IM_ASSERT(window ~= nil) -- Fix static analyzers if ImGui.IsWindowNavFocusable(window) then local label = window.Name if ImGui.FindRenderedTextEnd(label) == 1 then @@ -16563,12 +19170,15 @@ local function NavUpdateCreateWrappingRequest() local clip_dir = g.NavMoveDir local move_flags = g.NavMoveFlags + -- local move_axis = (g.NavMoveDir == ImGuiDir.Up or g.NavMoveDir == ImGuiDir.Down) and ImGuiAxis.Y or ImGuiAxis.X + + -- Menu layer does not maintain scrolling / content size (#9178) local wrap_size = (g.NavLayer == ImGuiNavLayer.Menu) and window.Size or (window.ContentSize + window.WindowPadding) if g.NavMoveDir == ImGuiDir.Left and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapX, ImGuiNavMoveFlags.LoopX)) ~= 0 then bb_rel.Min.x = wrap_size.x; bb_rel.Max.x = wrap_size.x if bit32.band(move_flags, ImGuiNavMoveFlags.WrapX) ~= 0 then - bb_rel:TranslateY(-bb_rel:GetHeight()) + bb_rel:TranslateY(-bb_rel:GetHeight()) -- Previous row clip_dir = ImGuiDir.Up end do_forward = true @@ -16576,7 +19186,7 @@ local function NavUpdateCreateWrappingRequest() if g.NavMoveDir == ImGuiDir.Right and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapX, ImGuiNavMoveFlags.LoopX)) ~= 0 then bb_rel.Min.x = -window.WindowPadding.x; bb_rel.Max.x = -window.WindowPadding.x if bit32.band(move_flags, ImGuiNavMoveFlags.WrapX) ~= 0 then - bb_rel:TranslateY(bb_rel:GetHeight()) + bb_rel:TranslateY(bb_rel:GetHeight()) -- Next row clip_dir = ImGuiDir.Down end do_forward = true @@ -16584,7 +19194,7 @@ local function NavUpdateCreateWrappingRequest() if g.NavMoveDir == ImGuiDir.Up and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapY, ImGuiNavMoveFlags.LoopY)) ~= 0 then bb_rel.Min.y = wrap_size.y; bb_rel.Max.y = wrap_size.y if bit32.band(move_flags, ImGuiNavMoveFlags.WrapY) ~= 0 then - bb_rel:TranslateX(-bb_rel:GetWidth()) + bb_rel:TranslateX(-bb_rel:GetWidth()) -- Previous column clip_dir = ImGuiDir.Left end do_forward = true @@ -16592,7 +19202,7 @@ local function NavUpdateCreateWrappingRequest() if g.NavMoveDir == ImGuiDir.Down and bit32.band(move_flags, bit32.bor(ImGuiNavMoveFlags.WrapY, ImGuiNavMoveFlags.LoopY)) ~= 0 then bb_rel.Min.y = -window.WindowPadding.y; bb_rel.Max.y = -window.WindowPadding.y if bit32.band(move_flags, ImGuiNavMoveFlags.WrapY) ~= 0 then - bb_rel:TranslateX(bb_rel:GetWidth()) + bb_rel:TranslateX(bb_rel:GetWidth()) -- Next column clip_dir = ImGuiDir.Right end do_forward = true @@ -16609,21 +19219,28 @@ end function ImGui.NavEndFrame() local g = GImGui + -- Show Ctrl+Tab list window if g.NavWindowingTarget ~= nil then ImGui.NavUpdateWindowingOverlay() end + -- Perform wrap-around in menus + -- FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly. + -- FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame. if g.NavWindow and ImGui.NavMoveRequestButNoResultYet() and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.WrapMask_) ~= 0 and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) == 0 then NavUpdateCreateWrappingRequest() end end +------------------------------------------------------------------------------- -- [SECTION] ImGuiTextFilter +------------------------------------------------------------------------------- --- @class ImGuiTextFilter MT.ImGuiTextFilter = {} MT.ImGuiTextFilter.__index = MT.ImGuiTextFilter +-- Helper: Parse and apply text filters e.g. 'aaa bbb -ccc'. --- @param default_filter? string function ImGuiTextFilter(default_filter) local this = setmetatable({ InputBuf = {}, _CountExclude = 0, _Items = ImVector() }, MT.ImGuiTextFilter) @@ -16641,6 +19258,7 @@ function MT.ImGuiTextFilter:Draw(label, width) return self:DrawWithHint(label, "incl -excl") end +-- Use ImGui.SetNextItemWidth() manually if you want to use this. function MT.ImGuiTextFilter:DrawWithHint(label, hint) if label == nil then label = "Filter" end if hint == nil then hint = "incl -excl" end @@ -16654,6 +19272,7 @@ end function MT.ImGuiTextFilter:Clear() self.InputBuf[1] = 0; self:Build() end function MT.ImGuiTextFilter:IsActive() return self._Items.Size ~= 0 end +-- Parse filter and split into a format optimal for PassFilter() -- Items are { Text = string (lowercased), CountInclude = int } function MT.ImGuiTextFilter:Build() local items = self._Items @@ -16667,6 +19286,7 @@ function MT.ImGuiTextFilter:Build() local word_b = 1 local seq_start_idx = -1 -- 1-based index into items, -1 = none while word_b < buf_e do + -- Trim blanks while word_b < buf_e and ImCharIsBlankA(string.byte(buf, word_b)) do word_b = word_b + 1 end @@ -16675,10 +19295,12 @@ function MT.ImGuiTextFilter:Build() local is_quote = word_b < buf_e and string.byte(buf, word_b) == 34 -- '"' local word_e if is_quote then + -- Parsing quotes. Omit storing leading/trailing quotes. word_b = word_b + 1 word_e = string.find(buf, '"', word_b, true) or buf_e if word_e > buf_e then word_e = buf_e end else + -- Handle both ' ' and ',' separators. word_e = word_b while word_e < buf_e do local c = string.byte(buf, word_e) @@ -16687,7 +19309,9 @@ function MT.ImGuiTextFilter:Build() end end + -- Min length if word_e - word_b > 0 then + -- Add to list. The '-' is not stored in items but implicitly inferred using (n < CountExclude). local item = { Text = string.lower(string.sub(buf, word_b, word_e - 1)), CountInclude = 0 } if is_excl then items:insert(self._CountExclude + 1, item) @@ -16700,6 +19324,7 @@ function MT.ImGuiTextFilter:Build() end end + -- Next sequence if word_e < buf_e and string.byte(buf, word_e) == 44 then -- ',' seq_start_idx = -1 end @@ -16707,6 +19332,7 @@ function MT.ImGuiTextFilter:Build() end end +-- FIXME: Could use a specialized ImStristr() + pre-convert our filter to uppercase. --- @param text string? --- @param text_end? int # exclusive, 1-based function MT.ImGuiTextFilter:PassFilter(text, text_end) @@ -16716,6 +19342,7 @@ function MT.ImGuiTextFilter:PassFilter(text, text_end) if text_end ~= nil then text = string.sub(text, 1, text_end - 1) end text = string.lower(text) + -- Filters are sorted so that '-' ones are always leading. local seq = 1 local seq_excl_end = self._CountExclude + 1 while seq < seq_excl_end do @@ -16723,24 +19350,29 @@ function MT.ImGuiTextFilter:PassFilter(text, text_end) seq = seq + 1 end + -- Process includes local seq_end = items.Size + 1 - if seq == seq_end then return true end + if seq == seq_end then return true end -- When no inclusion are specified (only exclusions) we implicitly pass while seq < seq_end do local seq_incl_end = seq + items.Data[seq].CountInclude while seq < seq_incl_end do if not string.find(text, items.Data[seq].Text, 1, true) then break end seq = seq + 1 end - if seq == seq_incl_end then return true end - seq = seq_incl_end + if seq == seq_incl_end then return true end -- All matched + seq = seq_incl_end -- Try next end return false end +------------------------------------------------------------------------------- -- [SECTION] ImGuiListClipper +------------------------------------------------------------------------------- ImGuiListClipperFlags = ImGuiListClipperFlags or { None = 0, NoSetTableRowCounters = bit32.lshift(1, 0) } +-- FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell. +-- The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous. local function GetSkipItemForListClipping() local g = GImGui if g.CurrentTable then return g.CurrentTable.HostSkipItems end @@ -16755,11 +19387,13 @@ local function ImGuiListClipper_SortAndFuseRanges(ranges, offset) if offset == nil then offset = 0 end if ranges.Size - offset <= 1 then return end local d = ranges.Data + -- Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries) for sort_end = ranges.Size - offset - 1, 1, -1 do for i = offset + 1, sort_end + offset do if d[i].Min > d[i + 1].Min then d[i], d[i + 1] = d[i + 1], d[i] end end end + -- Now fuse ranges together as much as possible. local i = 2 + offset while i <= ranges.Size do IM_ASSERT(not d[i].PosToIndexConvert and not d[i - 1].PosToIndexConvert) @@ -16774,16 +19408,19 @@ local function ImGuiListClipper_SortAndFuseRanges(ranges, offset) end local function ImGuiListClipper_SeekCursorAndSetupPrevLine(clipper, pos_y, line_height) + -- Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. + -- FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. + -- The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek? local g = GImGui local window = g.CurrentWindow local off_y = pos_y - window.DC.CursorPos.y window.DC.CursorPos.y = pos_y window.DC.CursorMaxPos.y = ImMax(window.DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y) - window.DC.CursorPosPrevLine.y = window.DC.CursorPos.y - line_height - window.DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y) + window.DC.CursorPosPrevLine.y = window.DC.CursorPos.y - line_height -- Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. + window.DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y) -- If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. local columns = window.DC.CurrentColumns if columns then - columns.LineMinY = window.DC.CursorPos.y + columns.LineMinY = window.DC.CursorPos.y -- Setting this so that cell Y position are set properly end local tbl = g.CurrentTable if tbl then @@ -16791,7 +19428,7 @@ local function ImGuiListClipper_SeekCursorAndSetupPrevLine(clipper, pos_y, line_ ImGui.TableEndRow(tbl) end local row_increase = math.floor((off_y / line_height) + 0.5) - if row_increase > 0 and bit32.band(clipper.Flags, ImGuiListClipperFlags.NoSetTableRowCounters) == 0 then + if row_increase > 0 and bit32.band(clipper.Flags, ImGuiListClipperFlags.NoSetTableRowCounters) == 0 then -- If your clipper item height is ~= from actual table row height, consider using ImGuiListClipperFlags.NoSetTableRowCounters. See #8886. tbl.CurrentRow = tbl.CurrentRow + row_increase tbl.RowBgColorCounter = tbl.RowBgColorCounter + row_increase end @@ -16827,6 +19464,7 @@ function MT.ImGuiListClipper:Begin(items_count, items_height) self.DisplayStart = -1 self.DisplayEnd = 0 + -- Acquire temporary buffer g.ClipperTempDataStacked = g.ClipperTempDataStacked + 1 while g.ClipperTempDataStacked > g.ClipperTempData.Size do g.ClipperTempData:push_back({ ListClipper = nil, LossynessOffset = 0.0, StepNo = 0, ItemsFrozen = 0, Ranges = ImVector() }) @@ -16841,10 +19479,13 @@ end function MT.ImGuiListClipper:End() local data = self.TempData if data then + -- In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user. local g = self.Ctx if self.ItemsCount >= 0 and self.ItemsCount < INT_MAX and self.DisplayStart >= 0 then self:SeekCursorForItem(self.ItemsCount) end + + -- Restore temporary buffer and fix back pointers which may be invalidated when nesting IM_ASSERT(data.ListClipper == self) data.StepNo = data.Ranges.Size g.ClipperTempDataStacked = g.ClipperTempDataStacked - 1 @@ -16854,7 +19495,7 @@ function MT.ImGuiListClipper:End() end self.TempData = nil end - self.DisplayStart = self.ItemsCount + self.DisplayStart = self.ItemsCount -- Clear this so code which may be reused past last Step() won't trip on a non-empty range. self.DisplayEnd = self.ItemsCount self.ItemsCount = -1 end @@ -16863,14 +19504,18 @@ function MT.ImGuiListClipper:IncludeItemByIndex(item_index) self:IncludeItemsByI function MT.ImGuiListClipper:IncludeItemsByIndex(item_begin, item_end) local data = self.TempData - IM_ASSERT(self.DisplayStart < 0) + IM_ASSERT(self.DisplayStart < 0) -- Only allowed after Begin() and if there has not been a specified range yet. IM_ASSERT(item_begin <= item_end) if item_begin < item_end then data.Ranges:push_back(ClipperRangeFromIndices(item_begin, item_end)) end end +-- This is already called while stepping. +-- The ONLY reason you may want to call this is if you passed INT_MAX to ImGuiListClipper:Begin() because you couldn't step item count beforehand. function MT.ImGuiListClipper:SeekCursorForItem(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. local pos_y = self.StartPosY + self.StartSeekOffsetY + item_n * self.ItemsHeight ImGuiListClipper_SeekCursorAndSetupPrevLine(self, pos_y, self.ItemsHeight) end @@ -16886,10 +19531,13 @@ local function ImGuiListClipper_StepInternal(clipper) ImGui.TableEndRow(tbl) end + -- No items if clipper.ItemsCount == 0 or GetSkipItemForListClipping() then return false end + -- While we are in frozen row state, keep displaying items one by one, unclipped + -- FIXME: Could be stored as a table-agnostic state. if data.StepNo == 0 and tbl ~= nil and not tbl.IsUnfrozenRows then clipper.DisplayStart = data.ItemsFrozen clipper.DisplayEnd = ImMin(data.ItemsFrozen + 1, clipper.ItemsCount) @@ -16899,40 +19547,47 @@ local function ImGuiListClipper_StepInternal(clipper) return true end + -- Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height) local calc_clipping = false if data.StepNo == 0 then clipper.StartPosY = window.DC.CursorPos.y if clipper.ItemsHeight <= 0.0 then + -- Submit the first item (or range) so we can measure its height (generally the first range is 0..1) data.Ranges:push_front(ClipperRangeFromIndices(data.ItemsFrozen, data.ItemsFrozen + 1)) clipper.DisplayStart = ImMax(data.Ranges.Data[1].Min, data.ItemsFrozen) clipper.DisplayEnd = ImMin(data.Ranges.Data[1].Max, clipper.ItemsCount) data.StepNo = 1 return true end - calc_clipping = true + calc_clipping = true -- If on the first step with known item height, calculate clipping. end + -- Step 1: Let the clipper infer height from first range if clipper.ItemsHeight <= 0.0 then IM_ASSERT(data.StepNo == 1) -- (no float precision mitigation needed: Luau numbers are doubles) clipper.ItemsHeight = (window.DC.CursorPos.y - clipper.StartPosY) / (clipper.DisplayEnd - clipper.DisplayStart) - if clipper.ItemsHeight == 0.0 and clipper.ItemsCount == INT_MAX then + if clipper.ItemsHeight == 0.0 and clipper.ItemsCount == INT_MAX then -- Accept that no item have been submitted if in indeterminate mode. return false end if clipper.ItemsHeight <= 0.0 then IM_ASSERT_USER_ERROR(clipper.ItemsHeight > 0.0, "ImGuiListClipper: Failed to calculate item height! First item hasn't been submitted by user code, or has not moved the cursor vertically!") return false end - calc_clipping = true + calc_clipping = true -- If item height had to be calculated, calculate clipping afterwards. end + -- Step 0 or 1: Calculate the actual ranges of visible elements. local already_submitted = clipper.DisplayEnd if calc_clipping then + -- Record seek offset, this is so ImGuiListClipper:Seek() can be called after ImGuiListClipperData is done clipper.StartSeekOffsetY = data.LossynessOffset - data.ItemsFrozen * clipper.ItemsHeight if g.LogEnabled then + -- If logging is active, do not perform any clipping data.Ranges:push_back(ClipperRangeFromIndices(0, clipper.ItemsCount)) else + -- Add range selected to be included for navigation local is_nav_request = (g.NavMoveScoringItems and g.NavWindow and g.NavWindow.RootWindowForNav == window.RootWindowForNav) and true or false local nav_off_min = (is_nav_request and g.NavMoveClipDir == ImGuiDir.Up) and -1 or 0 local nav_off_max = (is_nav_request and g.NavMoveClipDir == ImGuiDir.Down) and 1 or 0 @@ -16946,6 +19601,7 @@ local function ImGuiListClipper_StepInternal(clipper) data.Ranges:push_back(ClipperRangeFromIndices(clipper.ItemsCount - 1, clipper.ItemsCount)) end + -- Add focused/active item local nav_rect_abs = ImGui.WindowRectRelToAbs(window, window.NavRectRel[0]) if g.NavId ~= 0 and window.NavLastIds[0] == g.NavId then data.Ranges:push_back(ClipperRangeFromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0)) @@ -16954,19 +19610,31 @@ local function ImGuiListClipper_StepInternal(clipper) local min_y = window.ClipRect.Min.y local max_y = window.ClipRect.Max.y + -- Add box selection range local bs = g.BoxSelectState if bs and bs.IsActive and bs.Window == window then + -- FIXME: Selectable() use of half-ItemSpacing isn't consistent in matter of layout, as ItemAdd(bb) stray above ItemSize()'s CursorPos. + -- RangeSelect's BoxSelect relies on comparing overlap of previous and current rectangle and is sensitive to that. + -- As a workaround we currently half ItemSpacing worth on each side. local pad_y = g.Style.ItemSpacing.y min_y = min_y - pad_y max_y = max_y + pad_y + + -- Box-select on 2D area requires different clipping. + -- (best adding pad_y here than in BeginBoxSelect() as we are closer to current state) if bs.UnclipMode then data.Ranges:push_back(ClipperRangeFromPositions(bs.UnclipRect.Min.y - pad_y, bs.UnclipRect.Max.y + pad_y, 0, 0)) end end + -- Add main visible range data.Ranges:push_back(ClipperRangeFromPositions(min_y, max_y, nav_off_min, nav_off_max)) end + -- Convert position ranges to item index ranges + -- - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping. + -- - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list, + -- which with the flooring/ceiling tend to lead to 2 items instead of one being submitted. for _, range in data.Ranges:iter() do if range.PosToIndexConvert then local m1 = ImTrunc((range.Min - window.DC.CursorPos.y - data.LossynessOffset) / clipper.ItemsHeight) @@ -16979,6 +19647,7 @@ local function ImGuiListClipper_StepInternal(clipper) ImGuiListClipper_SortAndFuseRanges(data.Ranges, data.StepNo) end + -- Step 0+ (if item height is given in advance) or 1+: Display the next range in line. while data.StepNo < data.Ranges.Size do local r = data.Ranges.Data[data.StepNo + 1] clipper.DisplayStart = ImMax(r.Min, already_submitted) @@ -16992,6 +19661,8 @@ local function ImGuiListClipper_StepInternal(clipper) end end + -- After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), + -- Advance the cursor to the end of the list and then returns 'false' to end the loop. if clipper.ItemsCount < INT_MAX then clipper:SeekCursorForItem(clipper.ItemsCount) end @@ -17009,13 +19680,22 @@ function MT.ImGuiListClipper:Step() return ret end +-- Generic helper, equivalent to old ImGui.CalcListClipping() but stateless +-- Returns (out_visible_start, out_visible_end) function ImGui.CalcClipRectVisibleItemsY(clip_rect, pos, items_height) local out_visible_start = ImMax(ImTrunc((clip_rect.Min.y - pos.y) / items_height), 0) local out_visible_end = ImMax(ImTrunc(ImCeil((clip_rect.Max.y - pos.y) / items_height)), out_visible_start) return out_visible_start, out_visible_end end +------------------------------------------------------------------------------- -- [SECTION] ERROR CHECKING, STATE RECOVERY +------------------------------------------------------------------------------- +-- - ErrorRecoveryStoreState() +-- - ErrorRecoveryTryToRecoverState() +-- - ErrorRecoveryTryToRecoverWindowState() +-- - ErrorLog() +------------------------------------------------------------------------------- function ImGuiErrorRecoveryState() return { SizeOfWindowStack = 0, SizeOfIDStack = 0, SizeOfTreeStack = 0, SizeOfColorStack = 0, SizeOfStyleVarStack = 0, @@ -17023,6 +19703,7 @@ function ImGuiErrorRecoveryState() SizeOfBeginPopupStack = 0, SizeOfDisabledStack = 0 } end +-- Save current stack sizes. Called e.g. by NewFrame() and by Begin() but may be called for manual recovery. function ImGui.ErrorRecoveryStoreState(state_out) local g = GImGui state_out.SizeOfWindowStack = g.CurrentWindowStack.Size @@ -17038,9 +19719,17 @@ function ImGui.ErrorRecoveryStoreState(state_out) state_out.SizeOfDisabledStack = g.DisabledStackSize end +-- Chosen name "Try to recover" over e.g. "Restore" to suggest this is not a 100% guaranteed recovery. +-- Called by e.g. EndFrame() but may be called for manual recovery. +-- Attempt to recover full window stack. function ImGui.ErrorRecoveryTryToRecoverState(state_in) local g = GImGui while g.CurrentWindowStack.Size > state_in.SizeOfWindowStack do + -- Recap: + -- - Begin()/BeginChild() return false to indicate the window is collapsed or fully clipped. + -- - Always call a matching End() for each Begin() call, regardless of its return value! + -- - Begin/End and BeginChild/EndChild logic is KNOWN TO BE INCONSISTENT WITH ALL OTHER BEGIN/END FUNCTIONS. + -- - We will fix that in a future major update. local window = g.CurrentWindow if bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0 then if g.CurrentTable ~= nil and g.CurrentTable.InnerWindow == g.CurrentWindow then @@ -17060,6 +19749,8 @@ function ImGui.ErrorRecoveryTryToRecoverState(state_in) end end +-- Called by e.g. End() but may be called for manual recovery. +-- Attempt to recover from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls. function ImGui.ErrorRecoveryTryToRecoverWindowState(state_in) local g = GImGui @@ -17126,6 +19817,7 @@ function ImGui.ErrorRecoveryTryToRecoverWindowState(state_in) IM_ASSERT_USER_ERROR(false, "Missing PopFocusScope()") ImGui.PopFocusScope() end + -- IM_ASSERT(g.FocusScopeStack.Size == state_in.SizeOfFocusScopeStack) end -- Lines are stored in g.DebugLogBuf (one chunk per call) @@ -17151,6 +19843,7 @@ end function ImGui.ErrorLog(msg) local g = GImGui if g == nil then return true end + -- Output to debug log local window = g.CurrentWindow if g.IO.ConfigErrorRecoveryEnableDebugLog then @@ -17162,6 +19855,7 @@ function ImGui.ErrorLog(msg) end g.ErrorFirst = false + -- Output to tooltip if g.IO.ConfigErrorRecoveryEnableTooltip then if g.WithinFrameScope and ImGui.BeginErrorTooltip() then if g.ErrorCountCurrentFrame < 20 then @@ -17173,18 +19867,23 @@ function ImGui.ErrorLog(msg) if g.ErrorCountCurrentFrame == 20 then ImGui.Text("(and more errors)") end + -- EndFrame() will amend debug buttons to this window, after all errors have been submitted. ImGui.EndErrorTooltip() end g.ErrorCountCurrentFrame = g.ErrorCountCurrentFrame + 1 end + -- Output to callback if g.ErrorCallback ~= nil then g.ErrorCallback(g, g.ErrorCallbackUserData, msg) end + -- Return whether we should assert return g.IO.ConfigErrorRecoveryEnableAssert end +-- Display an error tooltip when same ID as HoveredId was submitted multiple times. +-- See code in ItemHoverable() for an explanation of why we associate this error to HoveredId + code drawing of rectangles over individual items instances. function ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() local g = GImGui if g.DebugDrawIdConflictsId ~= 0 and g.IO.KeyCtrl == false then @@ -17194,6 +19893,7 @@ function ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() ImGui.Text("Programmer error: %d visible items with conflicting ID!", g.DebugDrawIdConflictsCount) ImGui.BulletText("Code should use PushID()/PopID() in loops, or append \"##xx\" to same-label identifiers!") ImGui.BulletText("Empty label e.g. Button(\"\") == same ID as parent widget/node. Use Button(\"##xx\") instead!") + -- ImGui.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. ImGui.BulletText("Set io.ConfigDebugHighlightIdConflicts=false to disable this warning in non-programmers builds.") ImGui.Separator() ImGui.Text("(Hold Ctrl to: ") @@ -17204,19 +19904,24 @@ function ImGui.ErrorCheckEndFrameFinalizeErrorTooltip() ImGui.EndErrorTooltip() end - if g.ErrorCountCurrentFrame > 0 and ImGui.BeginErrorTooltip() then + if g.ErrorCountCurrentFrame > 0 and ImGui.BeginErrorTooltip() then -- Amend at end of frame ImGui.Separator() ImGui.Text("(Hold Ctrl to: ") ImGui.SameLine(0.0, 0.0) if ImGui.SmallButton("Enable Asserts") then g.IO.ConfigErrorRecoveryEnableAssert = true end + -- ImGui.SameLine() + -- if ImGui.SmallButton("Hide Error Tooltips") then + -- g.IO.ConfigErrorRecoveryEnableTooltip = false -- Too dangerous + -- end ImGui.SameLine(0, 0) ImGui.Text(")") ImGui.EndErrorTooltip() end end +-- Pseudo-tooltip. Follow mouse until Ctrl is held. When Ctrl is held we lock position, allowing to click it. function ImGui.BeginErrorTooltip() local g = GImGui local window = ImGui.FindWindowByName("##Tooltip_Error") @@ -17246,9 +19951,9 @@ end do --[[ [SECTION] METRICS/DEBUGGER WINDOW, DEBUG LOG, ID STACK TOOL, FONT DEBUG ]] ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Font atlas / font debugging ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- byte buffers for InputText (same as the demo's DemoBuf/DemoBufStr; kept here so the library doesn't need the demo) local function DemoBuf(str, size) @@ -17265,6 +19970,7 @@ local function DemoBufStr(buf) return ImGui._ByteArrayToString(buf, 1, n + 1) end +-- Avoid naming collision with imgui_demo's HelpMarker() for unity builds. local function MetricsHelpMarker(desc) ImGui.TextDisabled("(?)") if ImGui.BeginItemTooltip() then @@ -17278,6 +19984,8 @@ ImGui.MetricsHelpMarker = MetricsHelpMarker local function U8(c) return (c and c > 0) and utf8.char(c) or "" end +-- Demo helper function to select among loaded fonts. +-- Here we use the regular BeginCombo()/EndCombo() api which is the more flexible one. function ImGui.ShowFontSelector(label) local io = ImGui.GetIO() local font_current = ImGui.GetFont() @@ -17326,9 +20034,12 @@ function ImGui.DebugNodeFontGlyphsForSrcMask(font, baked, src_mask) end end if count > 0 and ImGui.TreeNode(base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, (count > 1) and "glyphs" or "glyph") then + -- Draw a 16x16 grid of glyphs local base_pos = ImGui.GetCursorScreenPos() for n = 0, 255 do local c = base + 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. local cell_p1 = ImVec2(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + math.floor(n / 16) * (cell_size + cell_spacing)) local cell_p2 = ImVec2(cell_p1.x + cell_size, cell_p1.y + cell_size) local glyph = baked:IsGlyphLoaded(c) and baked:FindGlyphNoFallback(c) or nil @@ -17348,11 +20059,14 @@ function ImGui.DebugNodeFontGlyphsForSrcMask(font, baked, src_mask) end end +-- [DEBUG] Display details for a single font, called by ShowStyleEditor(). function ImGui.DebugNodeFont(font) local g = ImGui.GetCurrentContext() local cfg = g.DebugMetricsConfig local atlas = font.OwnerAtlas local opened = ImGui.TreeNode(tostring(font), "Font: \"%s\": %d sources(s)", font:GetDebugName(), font.Sources.Size) + + -- Display preview text if not opened then ImGui.Indent() end ImGui.Indent() if cfg.ShowFontPreview then @@ -17375,6 +20089,7 @@ function ImGui.DebugNodeFont(font) ImGui.SameLine() if ImGui.SmallButton("Clear unused") then ImFontAtlasFontDiscardBakes(atlas, font, 2) end + -- Display details ImGui.Text("Fallback character: '%s' (U+%04X)", U8(font.FallbackChar), font.FallbackChar or 0) ImGui.Text("Ellipsis character: '%s' (U+%04X)", U8(font.EllipsisChar), font.EllipsisChar or 0) for src_n, src in font.Sources:iter() do @@ -17382,10 +20097,15 @@ function ImGui.DebugNodeFont(font) src_n - 1, src.Name or "", src.FontNo or 0, src.OversampleH or 0, src.OversampleV or 0, src.PixelSnapH and 1 or 0, src.GlyphOffset.x, src.GlyphOffset.y) then local loader = src.FontLoader or atlas.FontLoader ImGui.Text("Loader: '%s'", (loader and loader.Name) or "N/A") + + -- if ImGui.DragFloat("ExtraSizeScale", src.ExtraSizeScale, 0.01, 0.10, 2.0) then + -- ImFontAtlasFontRebuildOutput(atlas, font) + -- end ImGui.TreePop() end end + -- Display all glyphs of the fonts in separate pages of 256 characters local builder = atlas.Builder if builder then for _, baked in builder.BakedPool:iter() do @@ -17449,6 +20169,7 @@ function ImGui.DebugNodeTexture(tex, int_id, highlight_rect) ImGui.PopID() end +-- [DEBUG] List fonts in a font atlas and display its texture function ImGui.ShowFontAtlas(atlas) local g = ImGui.GetCurrentContext() local io = g.IO @@ -17459,7 +20180,7 @@ function ImGui.ShowFontAtlas(atlas) ImGui.ShowFontSelector("Font") local changed style.FontSizeBase, changed = ImGui.DragFloat("FontSizeBase", style.FontSizeBase, 0.20, 5.0, 100.0, "%.0f") - if changed then style._NextFrameFontSizeBase = style.FontSizeBase end + if changed then style._NextFrameFontSizeBase = style.FontSizeBase end -- FIXME: Temporary hack until we finish remaining work. ImGui.SameLine(0.0, 0.0); ImGui.Text(" (out %.2f)", ImGui.GetFontSize()) ImGui.SameLine(); MetricsHelpMarker("- This is scaling font only. General scaling will come later.") style.FontScaleMain = ImGui.DragFloat("FontScaleMain", style.FontScaleMain, 0.02, 0.5, 4.0) @@ -17473,6 +20194,7 @@ function ImGui.ShowFontAtlas(atlas) ImGui.SeparatorText("Font List") local cfg = g.DebugMetricsConfig _, cfg.ShowFontPreview = ImGui.Checkbox("Show font preview", cfg.ShowFontPreview == true) + -- Font loaders if ImGui.TreeNode("Loader", "Loader: '%s'", atlas.FontLoaderName or "NULL") then ImGui.BeginDisabled() ImGui.RadioButtonEx("stb_truetype", true) @@ -17482,6 +20204,7 @@ function ImGui.ShowFontAtlas(atlas) ImGui.EndDisabled() ImGui.TreePop() end + -- Font list for i, font in atlas.Fonts:iter() do ImGui.PushID(i) ImGui.DebugNodeFont(font) @@ -17506,16 +20229,19 @@ function ImGui.ShowFontAtlas(atlas) ImGui.Text("Packed rects: %d, area: about %d px ~%dx%d px", b.RectsPackedCount or 0, b.RectsPackedSurface or 0, packed_sqrt, packed_sqrt) ImGui.Text("incl. Discarded rects: %d, area: about %d px ~%dx%d px", b.RectsDiscardedCount or 0, b.RectsDiscardedSurface or 0, discarded_sqrt, discarded_sqrt) end + -- Texture list + -- (ensure the last texture always use the same ID, so we can keep it open neatly) for tex_n, tex in atlas.TexList:iter() do if tex_n == atlas.TexList.Size then ImGui.SetNextItemOpen(true, ImGuiCond.Once) end ImGui.DebugNodeTexture(tex, atlas.TexList.Size - tex_n, nil) end end ----------------------------------------------------------------- --- [SECTION] Debug Log window ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] DEBUG LOG WINDOW +------------------------------------------------------------------------------- +-- FIXME-LAYOUT: To be done automatically via layout mode once we rework ItemSize/ItemAdd into ItemLayout. local function SameLineOrWrap(size) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow @@ -17526,7 +20252,7 @@ end local function ShowDebugLogFlag(name, flags) local g = ImGui.GetCurrentContext() local size = ImVec2(ImGui.GetFrameHeight() + g.Style.ItemInnerSpacing.x + ImGui.CalcTextSize(name).x, ImGui.GetFrameHeight()) - SameLineOrWrap(size) + SameLineOrWrap(size) -- FIXME-LAYOUT: To be done automatically once we rework ItemSize/ItemAdd into ItemLayout. local pressed pressed, g.DebugLogFlags = ImGui.CheckboxFlags(name, g.DebugLogFlags, flags) if pressed and g.IO.KeyShift and bit32.band(g.DebugLogFlags, flags) ~= 0 then @@ -17591,9 +20317,9 @@ function ImGui.ShowDebugLogWindow(p_open) return p_open end ----------------------------------------------------------------- --- [SECTION] ID Stack Tool ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, ID STACK TOOL) +------------------------------------------------------------------------------- local function PathQuery(g) local q = g.DebugItemPathQuery @@ -17606,7 +20332,9 @@ local function PathQuery(g) end -- 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 local function DebugItemPathQuery_UpdateAndGetHookId(query, id) + -- Update query. Clear hook when no active query if query.MainID ~= id then query.MainID = id query.Step = -1 @@ -17616,9 +20344,11 @@ local function DebugItemPathQuery_UpdateAndGetHookId(query, id) query.Active = false if id == 0 then return 0 end local res = query.Results + -- Advance to next stack level when we got our result, or after 2 frames (in case we never get a result) if query.Step >= 0 and query.Step < #res then if res[query.Step + 1].QuerySuccess or res[query.Step + 1].QueryFrameCount > 2 then query.Step = query.Step + 1 end end + -- Update status and hook query.Complete = (query.Step == #res) if query.Step == -1 then query.Active = true @@ -17631,6 +20361,7 @@ local function DebugItemPathQuery_UpdateAndGetHookId(query, id) return 0 end +-- [DEBUG] ID Stack Tool: update query. Called by NewFrame() function ImGui.UpdateDebugToolItemPathQuery() local g = ImGui.GetCurrentContext() local q = PathQuery(g) @@ -17641,12 +20372,16 @@ function ImGui.UpdateDebugToolItemPathQuery() g.DebugHookIdInfoId = DebugItemPathQuery_UpdateAndGetHookId(q, id) end --- Hooks called by GetID() family functions. `data_id` is the string/number that was hashed. +-- [DEBUG] ID Stack tool: hooks called by GetID() family functions +-- `data_id` is the string/number that was hashed. function ImGui.DebugHookIdInfo(id, data_type, data_id) local g = ImGui.GetCurrentContext() local query = PathQuery(g) if not query.Active then return end local window = g.CurrentWindow + + -- Step -1: stack query + -- This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget. if query.Step == -1 then query.Step = 0 query.Results = {} @@ -17655,13 +20390,14 @@ function ImGui.DebugHookIdInfo(id, data_type, data_id) end return end + -- Step 0+: query for individual level if query.Step ~= window.IDStack.Size then return end local info = query.Results[query.Step + 1] if info == nil or info.ID ~= id then return end if info.Desc == nil then if data_type == ImGuiDataType.S32 then info.Desc = string.format("%d", data_id) elseif data_type == ImGuiDataType.String then info.Desc = tostring(data_id) - else info.Desc = string.format("0x%08X [override]", id) end + else info.Desc = string.format("0x%08X [override]", id) end -- PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one. end info.QuerySuccess = true if info.DataType == -1 then info.DataType = data_type end @@ -17676,9 +20412,9 @@ end local function FormatLevelInfo(g, query, n, format_for_ui) local info = query.Results[n + 1] local window = (info.Desc == nil and n == 0) and ImGui.FindWindowByID(info.ID) or nil - if window then return string.format(format_for_ui and "\"%s\" [window]" or "%s", SkipUncontributingPrefix(window.Name)) end - if info.QuerySuccess then return string.format((format_for_ui and info.DataType == ImGuiDataType.String) and "\"%s\"" or "%s", SkipUncontributingPrefix(info.Desc)) end - if query.Step < #query.Results then return "" end + if window then return string.format(format_for_ui and "\"%s\" [window]" or "%s", SkipUncontributingPrefix(window.Name)) end -- Source: window name (because the root ID don't call GetID() and so doesn't get hooked) + if info.QuerySuccess then return string.format((format_for_ui and info.DataType == ImGuiDataType.String) and "\"%s\"" or "%s", SkipUncontributingPrefix(info.Desc)) end -- Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id) + if query.Step < #query.Results then return "" end -- Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers. return "???" end @@ -17696,6 +20432,7 @@ local function GetResultAsPath(g, query, hex_encode_non_ascii_chars) return table.concat(out) end +-- ID Stack Tool: Display UI function ImGui.ShowIDStackToolWindow(p_open) local g = ImGui.GetCurrentContext() if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 then @@ -17714,6 +20451,8 @@ function ImGui.ShowIDStackToolWindow(p_open) ImGui.Text("0x%08X", query.MainID) ImGui.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 local time_since_copy = g.Time - tool.CopyToClipboardLastTime ImGui.PushStyleVarY(ImGuiStyleVar.FramePadding, 0.0) _, tool.OptHexEncodeNonAsciiChars = ImGui.Checkbox("Hex-encode non-ASCII", tool.OptHexEncodeNonAsciiChars) @@ -17728,6 +20467,8 @@ function ImGui.ShowIDStackToolWindow(p_open) end ImGui.Text("- Path \"%s\"", query.Complete and result_path or "") ImGui.Separator() + + -- Display decorated stack if #query.Results > 0 and ImGui.BeginTable("##table", 3, ImGuiTableFlags.Borders) then local id_width = ImGui.CalcTextSize("0xDDDDDDDD").x ImGui.TableSetupColumn("Seed", ImGuiTableColumnFlags.WidthFixed, id_width) @@ -17750,14 +20491,30 @@ function ImGui.ShowIDStackToolWindow(p_open) return p_open end ----------------------------------------------------------------- --- [SECTION] Metrics/Debugger window ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] METRICS/DEBUGGER WINDOW +------------------------------------------------------------------------------- +-- - DebugTextEncoding() +-- - ShowMetricsWindow() +-- - DebugNodeColumns() [Internal] +-- - DebugNodeDockNode() [Internal] +-- - DebugNodeDrawList() [Internal] +-- - DebugNodeStorage() [Internal] +-- - DebugNodeTabBar() [Internal] +-- - DebugNodeTable() [Internal] +-- - DebugNodeTableSettings() [Internal] +-- - DebugNodeViewport() [Internal] +-- - DebugNodeWindow() [Internal] +-- - DebugNodeWindowSettings() [Internal] +-- - DebugNodeWindowsList() [Internal] +-- - DebugNodeWindowsListByBeginStackParent() [Internal] +------------------------------------------------------------------------------- local function B(v) return v and 1 or 0 end local function FG(window) return ImGui.GetForegroundDrawList(window and window.Viewport or ImGui.GetMainViewport()) end local function YellowRect(window, min, max) FG(window):AddRect(min, max, IM_COL32(255, 255, 0, 255)) end +-- [DEBUG] Display contents of Columns function ImGui.DebugNodeColumns(columns) if not ImGui.TreeNode(columns.ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns.ID, columns.Count, columns.Flags) then return end ImGui.BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns.OffMaxX - columns.OffMinX, columns.OffMinX, columns.OffMaxX) @@ -17767,6 +20524,7 @@ function ImGui.DebugNodeColumns(columns) ImGui.TreePop() end +-- [DEBUG] Display contents of ImGuiStorage function ImGui.DebugNodeStorage(storage, label) local n = 0 for _ in pairs(storage) do n = n + 1 end @@ -17777,6 +20535,8 @@ function ImGui.DebugNodeStorage(storage, label) ImGui.TreePop() end +-- [DEBUG] Display contents of ImDrawList +-- Note that both 'window' and 'viewport' may be nil here. Viewport is generally nil of destroyed popups which previously owned a viewport. function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) local g = ImGui.GetCurrentContext() local cfg = g.DebugMetricsConfig @@ -17787,11 +20547,11 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) local node_open = ImGui.TreeNode(tostring(draw_list), "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list._OwnerName or "", draw_list.VtxBuffer.Size, draw_list.IdxBuffer.Size, cmd_count) if draw_list == ImGui.GetWindowDrawList() then ImGui.SameLine() - ImGui.TextColored(ImVec4(1.0, 0.4, 0.4, 1.0), "CURRENTLY APPENDING") + ImGui.TextColored(ImVec4(1.0, 0.4, 0.4, 1.0), "CURRENTLY APPENDING") -- Can't display stats for active draw list! (we don't have the data double-buffered) if node_open then ImGui.TreePop() end return end - local fg_draw_list = viewport and ImGui.GetForegroundDrawList(viewport) or nil + local fg_draw_list = viewport and ImGui.GetForegroundDrawList(viewport) or nil -- Render additional visuals into the top-most draw list if window and ImGui.IsItemHovered() and fg_draw_list then fg_draw_list:AddRect(window.Pos, window.Pos + window.Size, IM_COL32(255, 255, 0, 255)) end @@ -17819,11 +20579,11 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) tri[n + 1] = ImVec2(ImDrawVtx_Pos(vtx, vi)) vtxs_rect:Add(tri[n + 1]) end - if show_mesh then fg_draw_list:AddPolyline(tri, 3, IM_COL32(255, 255, 0, 255), 1.0, ImDrawFlags.Closed) end + if show_mesh then fg_draw_list:AddPolyline(tri, 3, IM_COL32(255, 255, 0, 255), 1.0, ImDrawFlags.Closed) end -- In yellow: mesh triangles end if show_aabb then - fg_draw_list:AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)) - fg_draw_list:AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)) + fg_draw_list:AddRect(ImTrunc(clip_rect.Min), ImTrunc(clip_rect.Max), IM_COL32(255, 0, 255, 255)) -- In pink: clipping rectangle submitted to GPU + fg_draw_list:AddRect(ImTrunc(vtxs_rect.Min), ImTrunc(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)) -- In cyan: bounding box of triangles end end if ImGui.IsItemHovered() and (cfg.ShowDrawCmdMesh or cfg.ShowDrawCmdBoundingBoxes) then ShowMesh(cfg.ShowDrawCmdMesh, cfg.ShowDrawCmdBoundingBoxes) end @@ -17837,7 +20597,9 @@ function ImGui.DebugNodeDrawList(window, viewport, draw_list, label) ImGui.TreePop() end +-- [DEBUG] Display contents of ImGuiTabBar function ImGui.DebugNodeTabBar(tab_bar, label) + -- Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. local g = ImGui.GetCurrentContext() local is_active = (tab_bar.PrevFrameVisible >= ImGui.GetFrameCount() - 2) local names = {} @@ -17896,7 +20658,7 @@ end function ImGui.DebugNodeTable(tbl) local g = ImGui.GetCurrentContext() - local is_active = (tbl.LastFrameActive >= g.FrameCount - 2) + local is_active = (tbl.LastFrameActive >= g.FrameCount - 2) -- Note that fully clipped early out scrolling tables will appear as inactive here. if not is_active then ImGui.PushStyleColor(ImGuiCol.Text, g.Style.Colors[ImGuiCol.TextDisabled]) end local open = ImGui.TreeNode(tostring(tbl), "Table 0x%08X (%d columns, in '%s')%s", tbl.ID, tbl.ColumnsCount, tbl.OuterWindow and tbl.OuterWindow.Name or "?", is_active and "" or " *Inactive*") if not is_active then ImGui.PopStyleColor() end @@ -17937,7 +20699,7 @@ function ImGui.DebugNodeTable(tbl) end local settings = ImGui.TableGetBoundSettings(tbl) if settings then ImGui.DebugNodeTableSettings(settings, tbl) end - if clear_settings then tbl.IsResetAllRequest = true end + if clear_settings then tbl.IsResetAllRequest = true end -- Queue a call to TableResetSettings() ImGui.TreePop() end @@ -17957,10 +20719,11 @@ local function DebugNodeDockNodeFlags(flags, label, enabled) return flags end +-- [DEBUG] Display contents of ImDockNode function ImGui.DebugNodeDockNode(node, label) local g = ImGui.GetCurrentContext() - local is_alive = (g.FrameCount - node.LastFrameAlive < 2) - local is_active = (g.FrameCount - node.LastFrameActive < 2) + local is_alive = (g.FrameCount - node.LastFrameAlive < 2) -- Submitted with ImGuiDockNodeFlags.KeepAliveOnly + local is_active = (g.FrameCount - node.LastFrameActive < 2) -- Submitted if not is_alive then ImGui.PushStyleColor(ImGuiCol.Text, g.Style.Colors[ImGuiCol.TextDisabled]) end local tree_node_flags = node.IsFocused and ImGuiTreeNodeFlags.Selected or ImGuiTreeNodeFlags.None local open @@ -18067,7 +20830,7 @@ end function ImGui.DebugNodeWindowsList(windows, label) if not ImGui.TreeNode(label, "%s (%d)", label, windows.Size) then return end - for i = windows.Size, 1, -1 do + for i = windows.Size, 1, -1 do -- Iterate front to back ImGui.PushID(tostring(windows.Data[i])) ImGui.DebugNodeWindow(windows.Data[i], "Window") ImGui.PopID() @@ -18075,11 +20838,13 @@ function ImGui.DebugNodeWindowsList(windows, label) ImGui.TreePop() end +-- FIXME-OPT: This is technically suboptimal, but it is simpler this way. function ImGui.DebugNodeWindowsListByBeginStackParent(windows, first, last, parent_in_begin_stack) for i = first, last do local window = windows[i] if window.ParentWindowInBeginStack == parent_in_begin_stack then local buf = string.format("[%04d] Window", window.BeginOrderWithinContext) + -- ImGui.BulletText("[%04d] Window '%s'", window.BeginOrderWithinContext, window.Name) ImGui.DebugNodeWindow(window, buf) ImGui.TreePush(buf) ImGui.DebugNodeWindowsListByBeginStackParent(windows, i + 1, last, window) @@ -18105,6 +20870,7 @@ function ImGui.DebugNodeViewport(viewport) end end +-- Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct. function ImGui.DebugTextEncoding(str) ImGui.Text("Text: \"%s\"", str) if not ImGui.BeginTable("##DebugTextEncoding", 4, bit32.bor(ImGuiTableFlags.Borders, ImGuiTableFlags.RowBg, ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.Resizable)) then return end @@ -18130,6 +20896,7 @@ function ImGui.DebugTextEncoding(str) ImGui.EndTable() end +-- Debugging enums local WRT_Names = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" } local TRT_Names = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" } @@ -18147,14 +20914,14 @@ local function GetWindowRect(window, t) end local function GetTableRect(tbl, t, n) - local inst = ImGui.TableGetInstanceData(tbl, tbl.InstanceCurrent) + local inst = ImGui.TableGetInstanceData(tbl, tbl.InstanceCurrent) -- Always using last submitted instance if t == 0 then return tbl.OuterRect elseif t == 1 then return tbl.InnerRect elseif t == 2 then return tbl.WorkRect elseif t == 3 then return tbl.HostClipRect elseif t == 4 then return tbl.InnerClipRect elseif t == 5 then return tbl.BgClipRect end local c = tbl.Columns[n] if t == 6 then return ImRect(c.MinX, tbl.InnerClipRect.Min.y, c.MaxX, tbl.InnerClipRect.Min.y + inst.LastOuterHeight) elseif t == 7 then return ImRect(c.WorkMinX, tbl.WorkRect.Min.y, c.WorkMaxX, tbl.WorkRect.Max.y) elseif t == 8 then return c.ClipRect - elseif t == 9 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXHeadersUsed, tbl.InnerClipRect.Min.y + inst.LastTopHeadersRowHeight) + elseif t == 9 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXHeadersUsed, tbl.InnerClipRect.Min.y + inst.LastTopHeadersRowHeight) -- Note: y1/y2 not always accurate elseif t == 10 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXHeadersIdeal, tbl.InnerClipRect.Min.y + inst.LastTopHeadersRowHeight) elseif t == 11 then return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y, c.ContentMaxXFrozen, tbl.InnerClipRect.Min.y + inst.LastFrozenHeight) else return ImRect(c.WorkMinX, tbl.InnerClipRect.Min.y + inst.LastFrozenHeight, c.ContentMaxXUnfrozen, tbl.InnerClipRect.Max.y) end @@ -18183,6 +20950,7 @@ function ImGui.ShowMetricsWindow(p_open) return p_open end + -- Basic info ImGui.Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM) ImGui.Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0 / math.max(io.Framerate, 0.0001), io.Framerate) ImGui.Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, math.floor(io.MetricsRenderIndices / 3)) @@ -18220,7 +20988,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.SetNextItemWidth(ImGui.GetFontSize() * 12) cfg.ShowTablesRectsType, changed = ImGui.Combo("##show_table_rects_type", cfg.ShowTablesRectsType, TRT_Names, #TRT_Names, #TRT_Names) cfg.ShowTablesRects = cfg.ShowTablesRects or changed - _, g.DebugShowGroupRects = ImGui.Checkbox("Show groups rectangles", g.DebugShowGroupRects == true) + _, g.DebugShowGroupRects = ImGui.Checkbox("Show groups rectangles", g.DebugShowGroupRects == true) -- Storing in context as this is used by group code and prefers to be in hot-data ImGui.SeparatorText("Validate") _, io.ConfigDebugBeginReturnValueLoop = ImGui.Checkbox("Debug Begin/BeginChild return value", io.ConfigDebugBeginReturnValueLoop == true) @@ -18239,9 +21007,11 @@ function ImGui.ShowMetricsWindow(p_open) -- Windows if ImGui.TreeNode("Windows", "Windows (%d)", g.Windows.Size) then + -- ImGui.SetNextItemOpen(true, ImGuiCond.Once) ImGui.DebugNodeWindowsList(g.Windows, "By display order") ImGui.DebugNodeWindowsList(g.WindowsFocusOrder, "By focus order (root windows)") if ImGui.TreeNode("By submission order (begin stack)") then + -- Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship! local tmp = {} for _, window in g.Windows:iter() do if window.LastFrameActive + 1 >= g.FrameCount then tmp[#tmp + 1] = window end @@ -18282,7 +21052,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- Fonts + -- Details for Fonts for i, atlas in g.FontAtlases:iter() do if ImGui.TreeNode(tostring(atlas), "Fonts (%d), Textures (%d)", atlas.Fonts.Size, atlas.TexList.Size) then ImGui.ShowFontAtlas(atlas) @@ -18290,9 +21060,10 @@ function ImGui.ShowMetricsWindow(p_open) end end - -- Popups + -- Details for Popups if ImGui.TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size) then for _, popup_data in g.OpenPopupStack:iter() do + -- As it's difficult to interact with tree nodes while popups are open, we display everything inline. local window = popup_data.Window local W = ImGuiWindowFlags ImGui.BulletText("PopupID: %08x, Window: '%s' (%s%s), RestoreNavWindow '%s', ParentWindow '%s'", popup_data.PopupId, window and window.Name or "NULL", @@ -18302,7 +21073,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- TabBars + -- Details for TabBars if ImGui.TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.AliveCount) then for n = 0, g.TabBars:GetMapSize() - 1 do local tab_bar = g.TabBars:GetByIndex(n) @@ -18315,13 +21086,13 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- Tables + -- Details for Tables if ImGui.TreeNode("Tables", "Tables (%d)", g.Tables.AliveCount) then ForEachTable(g, ImGui.DebugNodeTable) ImGui.TreePop() end - -- Docking + -- Details for Docking if ImGui.TreeNode("Docking") then local dc = g.DockContext _, MetricsDockRootOnly = ImGui.Checkbox("List root nodes", MetricsDockRootOnly) @@ -18387,6 +21158,7 @@ function ImGui.ShowMetricsWindow(p_open) -- Inputs if ImGui.TreeNode("Inputs") then ImGui.Text("KEYBOARD/GAMEPAD/MOUSE KEYS") + -- User code should never have to go through such hoops! You can generally iterate between ImGuiKey.NamedKey_BEGIN and ImGuiKey.NamedKey_END. ImGui.Indent() ImGui.Text("Keys down:") for key = ImGuiKey.NamedKey_BEGIN, ImGuiKey.NamedKey_END - 1 do @@ -18439,7 +21211,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.Indent() ImGui.Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, B(g.ActiveIdAllowOverlap)) ImGui.Text("ActiveIdWindow: '%s'", N(g.ActiveIdWindow)) - ImGui.Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, B(g.HoveredIdAllowOverlap)) + ImGui.Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, B(g.HoveredIdAllowOverlap)) -- Not displaying g.HoveredId as it is update mid-frame ImGui.Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId or 0, g.HoverItemDelayTimer or 0, g.HoverItemDelayClearTimer or 0) ImGui.Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\"", B(g.DragDropActive), g.DragDropPayload.SourceId or 0, tostring(g.DragDropPayload.DataType or "")) ImGui.Unindent() @@ -18457,7 +21229,7 @@ function ImGui.ShowMetricsWindow(p_open) ImGui.TreePop() end - -- Overlays + -- Overlay: Display windows Rectangles and Begin Order if cfg.ShowWindowsRects or cfg.ShowWindowsBeginOrder then for _, window in g.Windows:iter() do if window.WasActive then @@ -18474,6 +21246,8 @@ function ImGui.ShowMetricsWindow(p_open) end end end + + -- Overlay: Display Tables Rectangles if cfg.ShowTablesRects then ForEachTable(g, function(tbl) if tbl.LastFrameActive < g.FrameCount - 1 then return end diff --git a/imgui_demo.lua b/imgui_demo.lua index 6d25e71..9feb05d 100644 --- a/imgui_demo.lua +++ b/imgui_demo.lua @@ -1,20 +1,127 @@ -- dear imgui demo (Luau port of imgui_demo.cpp). Optional: the library never calls into this file. do --[[ imgui_demo.lua ]] ---- Dear ImGui WIP --- (Demo Code) Port of imgui_demo.cpp (docking branch) +-- dear imgui, v1.93.0 WIP +-- (demo code) Port of imgui_demo.cpp (docking branch) -- This file: shared demo helpers, ShowDemoWindow(), DemoWindowMenuBar(), DemoWindowWidgets() dispatcher, example tree/image viewer helpers. -- Other parts (all global functions, loaded from the same bundle): +-- Help: +-- - Read FAQ at http://dearimgui.com/faq +-- - Call and read ImGui.ShowDemoWindow() in imgui_demo.lua. +-- - Need help integrating Dear ImGui in your codebase? +-- - Read Getting Started https://github.com/ocornut/imgui/wiki/Getting-Started +-- Read top of imgui.cpp and imgui.h for many details, documentation, comments, links. +-- Get the latest version at https://github.com/ocornut/imgui + +-- How to easily locate code? +-- - Use Tools->Item Picker to debug break in code by clicking any widgets: https://github.com/ocornut/imgui/wiki/Debug-Tools +-- - Browse pthom's online imgui_explorer: web version the demo w/ source code browser: https://pthom.github.io/imgui_explorer +-- - Find a visible string and search for it in the code! + +----------------------------------------------------- +-- PLEASE DO NOT REMOVE THIS FILE FROM YOUR PROJECT! +----------------------------------------------------- +-- Message to the person tempted to delete this file when integrating Dear ImGui into their codebase: +-- Think again! It is the most useful reference code that you and other coders will want to refer to and call. +-- Have the ImGui.ShowDemoWindow() function wired in an always-available debug menu of your game/app! +-- Also include Metrics! ItemPicker! DebugLog! and other debug features. +-- Removing this file from your project is hindering access to documentation for everyone in your team, +-- likely leading you to poorer usage of the library. +-- Whenever you have Dear ImGui available you probably want this to be available for reference. +-- Thank you, +-- -Your beloved friend, imgui_demo.cpp (which you won't delete) + +---------------------------------------------- +-- ABOUT THE MEANING OF THE 'static' KEYWORD: +---------------------------------------------- +-- In the upstream C++ demo code, 'static' variables inside functions are frequently used. +-- A static variable persists across calls. It is essentially a global variable but declared inside the scope of the function. +-- Think of "static int n = 0;" as "global int n = 0;" ! +-- (PORT: Lua has no function-local statics; this port keeps them as fields of file-level tables, e.g. `S`, `SL`, `ST`.) +-- We do this IN THE DEMO because we want: +-- - to gather code and data in the same place. +-- - to make the demo source code faster to read, faster to change, smaller in size. +-- - it is also a convenient way of storing simple UI related information as long as your function +-- doesn't need to be reentrant or used in multiple threads. +-- This might be a pattern you will want to use in your code, but most of the data you would be working +-- with in a complex codebase is likely going to be stored outside your functions. + +------------------------------------------- +-- ABOUT THE CODING STYLE OF OUR DEMO CODE +------------------------------------------- +-- The Demo code in this file is designed to be easy to copy-and-paste into your application! +-- Because of this: +-- - We never omit the ImGui. prefix when calling functions. + +-- Navigating this file: +-- - You can search/grep for all sections listed in the index to find the section. + +-- Index of this file: +-- +-- [SECTION] Helpers +-- [SECTION] Demo Window / ShowDemoWindow() +-- [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) +-- [SECTION] Helpers: ExampleImageViewer +-- [SECTION] DemoWindowWidgetsBasic() +-- [SECTION] DemoWindowWidgetsBullets() +-- [SECTION] DemoWindowWidgetsCollapsingHeaders() +-- [SECTION] DemoWindowWidgetsComboBoxes() +-- [SECTION] DemoWindowWidgetsColorAndPickers() +-- [SECTION] DemoWindowWidgetsDataTypes() +-- [SECTION] DemoWindowWidgetsDisableBlocks() +-- [SECTION] DemoWindowWidgetsDragAndDrop() +-- [SECTION] DemoWindowWidgetsDragsAndSliders() +-- [SECTION] DemoWindowWidgetsFonts() +-- [SECTION] DemoWindowWidgetsImages() +-- [SECTION] DemoWindowWidgetsListBoxes() +-- [SECTION] DemoWindowWidgetsLiveEdit() +-- [SECTION] DemoWindowWidgetsMixedValues() +-- [SECTION] DemoWindowWidgetsMultiComponents() +-- [SECTION] DemoWindowWidgetsPlotting() +-- [SECTION] DemoWindowWidgetsProgressBars() +-- [SECTION] DemoWindowWidgetsQueryingStatuses() +-- [SECTION] DemoWindowWidgetsSelectables() +-- [SECTION] DemoWindowWidgetsTabs() +-- [SECTION] DemoWindowWidgetsText() +-- [SECTION] DemoWindowWidgetsTextFilter() +-- [SECTION] DemoWindowWidgetsTextInput() +-- [SECTION] DemoWindowWidgetsTooltips() +-- [SECTION] DemoWindowWidgetsTreeNodes() +-- [SECTION] DemoWindowWidgetsVerticalSliders() +-- [SECTION] DemoWindowWidgets() +-- [SECTION] DemoWindowLayout() +-- [SECTION] DemoWindowPopups() +-- [SECTION] DemoWindowTables() +-- [SECTION] About Window / ShowAboutWindow() +-- [SECTION] Style Editor / ShowStyleEditor() +-- [SECTION] User Guide / ShowUserGuide() +-- [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() +-- [SECTION] Example App: Debug Console / ShowExampleAppConsole() +-- [SECTION] Example App: Debug Log / ShowExampleAppLog() +-- [SECTION] Example App: Simple Layout / ShowExampleAppLayout() +-- [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() +-- [SECTION] Example App: Long Text / ShowExampleAppLongText() +-- [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() +-- [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize() +-- [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() +-- [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() +-- [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles() +-- [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() +-- [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() +-- [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() + local _ ----------------------------------------------------------------- --- Shared helpers (globals) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Helpers +------------------------------------------------------------------------------- +-- Helper to wire demo markers located in code to an interactive browser (e.g. https://pthom.github.io/imgui_explorer) function IMGUI_DEMO_MARKER(_) end -- upstream hook, no-op here ---- Helper to display a little (?) mark which shows a tooltip when hovered. +-- Helper to display a little (?) mark which shows a tooltip when hovered. +-- In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md) function HelpMarker(desc) ImGui.TextDisabled("(?)") if ImGui.BeginItemTooltip() then @@ -162,9 +269,9 @@ function DemoTextFilter() return f end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Demo Window data ----------------------------------------------------------------- +------------------------------------------------------------------------------- --- Data to be shared across different functions of the demo. function ImGuiDemoWindowData() @@ -202,10 +309,12 @@ function ImGuiDemoWindowData() } end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Helpers: ExampleTreeNode, ExampleMemberInfo (for use by Property Editor & Multi-Select demos) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Simple representation for a tree +-- (this is designed to be simple to understand for our demos, not to be fancy or efficient etc.) function ExampleTreeNode() return { -- Tree structure @@ -213,7 +322,7 @@ function ExampleTreeNode() UID = 0, Parent = nil, Childs = {}, -- 1-based - IndexInParent = 0, -- 0-based + IndexInParent = 0, -- 0-based. Maintaining this allows us to implement linear traversal more easily -- Leaf Data HasData = false, -- All leaves have data @@ -237,8 +346,14 @@ end function ExampleTree_DestroyNode(node) end -- GC ---- Create example tree data +-- Create example tree data +-- (warning: this can allocates MANY MANY more times than other code in all of Dear ImGui + demo combined) +-- (a real application managing one million nodes would likely store its tree data differently) function ExampleTree_CreateDemoTree() + -- 20 root nodes -> 211 total nodes, ~261 allocs. + -- 1000 root nodes -> ~11K total nodes, ~14K allocs. + -- 10000 root nodes -> ~123K total nodes, ~154K allocs. + -- 100000 root nodes -> ~1338K total nodes, ~1666K allocs. local ROOT_ITEMS_COUNT = 20 local category_names = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pear", "Pineapple", "Strawberry", "Watermelon" } local category_count = #category_names @@ -264,9 +379,9 @@ function ExampleTree_CreateDemoTree() return node_L0 end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Helpers: ExampleImageViewer ----------------------------------------------------------------- +------------------------------------------------------------------------------- function ExampleImageViewerData() return { @@ -282,7 +397,7 @@ function ExampleImageViewerData() end function ExampleImageViewer_DrawOptions(data) - ImGui.SetNextItemShortcut(ImGuiKey.G, ImGuiInputFlags.Tooltip) + ImGui.SetNextItemShortcut(ImGuiKey.G, ImGuiInputFlags.Tooltip) -- | ImGuiInputFlags.RouteGlobal _, data.GridEnabled = ImGui.Checkbox("Grid", data.GridEnabled) ImGui.SameLine() ImGui.SetNextItemWidth(ImGui.GetFontSize() * 10.0) @@ -316,7 +431,7 @@ function ExampleImageViewer_DrawCanvas(data, canvas_size, image_tex_ref, image_w data.Zoom = DemoClamp(data.Zoom * (1.0 + io.MouseWheel * 0.10), data.ZoomMin, data.ZoomMax) end end - local zoom = data.Zoom + local zoom = data.Zoom -- (float)(int)ViewZoom; if ImGui.IsItemActive() and ImGui.IsMouseDragging(0) then data.ViewOffset.x = data.ViewOffset.x - io.MouseDelta.x / zoom data.ViewOffset.y = data.ViewOffset.y - io.MouseDelta.y / zoom @@ -352,10 +467,11 @@ function ExampleImageViewer_DrawCanvas(data, canvas_size, image_tex_ref, image_w draw_list:PopClipRect() end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Demo Window / ShowDemoWindow() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Stored data local demo_data = ImGuiDemoWindowData() local no_titlebar = false @@ -413,6 +529,7 @@ local function DemoWindowMenuBar(data) ImGui.EndMenu() end + -- if ImGui.MenuItem("MenuItem") then end -- You can also use MenuItem() inside a menu bar! if ImGui.BeginMenu("Tools") then IMGUI_DEMO_MARKER("Menu/Tools") local io = ImGui.GetIO() @@ -429,7 +546,7 @@ local function DemoWindowMenuBar(data) _, data.ShowDebugLog = ImGui.MenuItem("Debug Log", nil, data.ShowDebugLog, has_debug_tools and ImGui.ShowDebugLogWindow ~= nil) _, data.ShowIDStackTool = ImGui.MenuItem("ID Stack Tool", nil, data.ShowIDStackTool, has_debug_tools and ImGui.ShowIDStackToolWindow ~= nil) local is_debugger_present = io.ConfigDebugIsDebuggerPresent - if ImGui.MenuItem("Item Picker", nil, false, has_debug_tools and ImGui.DebugStartItemPicker ~= nil) then + if ImGui.MenuItem("Item Picker", nil, false, has_debug_tools and ImGui.DebugStartItemPicker ~= nil) then -- and is_debugger_present ImGui.DebugStartItemPicker() end if not is_debugger_present then @@ -537,6 +654,12 @@ local function DemoWindowConfiguration(io) ImGui.Unindent() end + -- ImGui.SeparatorText("DPI/Scaling") + -- CB("io.ConfigDpiScaleFonts", "ConfigDpiScaleFonts") + -- HM("Experimental: Automatically update style.FontScaleDpi when Monitor DPI changes. This will scale fonts but NOT style sizes/padding for now.") + -- CB("io.ConfigDpiScaleViewports", "ConfigDpiScaleViewports") + -- HM("Experimental: Scale Dear ImGui and Platform Windows when Monitor DPI changes.") + ImGui.SeparatorText("Windows") CB("io.ConfigWindowsResizeFromEdges", "ConfigWindowsResizeFromEdges") HM("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires ImGuiBackendFlags_HasMouseCursors for better mouse cursor feedback.") @@ -610,6 +733,7 @@ local function DemoWindowConfiguration(io) "Here we expose them as read-only fields to avoid breaking interactions with your backend.") -- Make a local copy to avoid modifying actual backend flags. + -- FIXME: Maybe we need a BeginReadonly() equivalent to keep label bright? local B = ImGuiBackendFlags local backend_flags = io.BackendFlags ImGui.BeginDisabled() @@ -663,10 +787,14 @@ local function DemoWindowConfiguration(io) end end ---- Demonstrate most Dear ImGui features (this is big function!) +-- Demonstrate most Dear ImGui features (this is big function!) +-- You may execute this function to experiment with the UI and understand what it does. +-- You may then search for keywords in the code when you are interested by a specific feature. --- @param p_open? bool --- @return bool? p_open function ImGui.ShowDemoWindow(p_open) + -- Exceptionally add an extra assert here for people confused about initial Dear ImGui setup + -- Most functions would normally just assert/crash if the context is missing. IM_ASSERT(ImGui.GetCurrentContext() ~= nil, "Missing Dear ImGui context. Refer to examples app!") local data = demo_data @@ -722,6 +850,7 @@ function ImGui.ShowDemoWindow(p_open) if no_close then p_open = nil end -- Don't pass our bool* to Begin -- We specify a default position/size in case there's no data in the .ini file. + -- We only do it to make the demo applications a little more welcoming, but typically this isn't required. local main_viewport = ImGui.GetMainViewport() ImGui.SetNextWindowPos(ImVec2(main_viewport.WorkPos.x + 650, main_viewport.WorkPos.y + 20), ImGuiCond.FirstUseEver) ImGui.SetNextWindowSize(ImVec2(550, 680), ImGuiCond.FirstUseEver) @@ -737,10 +866,18 @@ function ImGui.ShowDemoWindow(p_open) end -- Most framed widgets share a common width settings. Remaining width is used for the label. + -- The width of the frame may be changed with PushItemWidth() or SetNextItemWidth(). + -- - Positive value for absolute size, negative value for right-alignment. + -- - The default value is about GetWindowWidth() * 0.65f. + -- - See 'Demo->Layout->Widgets Width' for details. + -- Here we change the frame width based on how much width we want to give to the label. local label_width_base = ImGui.GetFontSize() * 12 -- Some amount of width for label, based on font size. local label_width_max = ImGui.GetContentRegionAvail().x * 0.40 -- ...but always leave some room for framed widgets. local label_width = math.min(label_width_base, label_width_max) ImGui.PushItemWidth(-label_width) -- Right-align: framed items will leave 'label_width' available for the label. + -- ImGui.PushItemWidth(ImGui.GetContentRegionAvail().x * 0.40) -- e.g. Use 40% width for framed widgets, leaving 60% width for labels. + -- ImGui.PushItemWidth(-ImGui.GetContentRegionAvail().x * 0.40) -- e.g. Use 40% width for labels, leaving 60% width for framed widgets. + -- ImGui.PushItemWidth(ImGui.GetFontSize() * -12) -- e.g. Use XXX width for labels, leaving the rest for framed widgets. -- Menu Bar DemoWindowMenuBar(data) @@ -809,9 +946,9 @@ function ImGui.ShowDemoWindow(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] DemoWindowWidgets() ----------------------------------------------------------------- +------------------------------------------------------------------------------- --- Calls a (global) demo section if it exists, otherwise shows a placeholder local function Sub(fn, title, ...) @@ -821,6 +958,7 @@ local function Sub(fn, title, ...) end function DemoWindowWidgets(data) + -- ImGui.SetNextItemOpen(true, ImGuiCond.Once) if not ImGui.CollapsingHeader("Widgets") then return end @@ -881,9 +1019,9 @@ function DemoWindowWidgets(data) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] User Guide / ShowUserGuide() ----------------------------------------------------------------- +------------------------------------------------------------------------------- function ImGui.ShowUserGuide() local io = ImGui.GetIO() @@ -932,6 +1070,10 @@ do --[[ imgui_demo_2.lua ]] -- DemoWindowInputs() and all ShowExampleAppXXX() example apps. -- Port of imgui_demo.cpp (docking branch). Globals are shared with imgui_demo.lua (HelpMarker, ShowExampleMenuFile, ...) +-- Helpers macros +-- We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste, +-- but making an exception here as those are largely simplifying code... +-- In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo. local IM_MIN = math.min local IM_MAX = math.max local function IM_CLAMP(V, MN, MX) return (V < MN) and MN or (V > MX) and MX or V end @@ -1120,6 +1262,10 @@ local function DemoWindowLayout_ChildWindows() ImGui.SeparatorText("Manual-resize") do DemoHelpMarker("Drag bottom border to resize. Double-click bottom border to auto-fit to vertical contents.") + -- if ImGui.Button("Set Height to 200") then + -- ImGui.SetNextWindowSize(ImVec2(-FLT_MIN, 200.0)) + -- end + ImGui.PushStyleColor(ImGuiCol.ChildBg, ImGui.GetStyleColorVec4(ImGuiCol.FrameBg)) if BeginChild("ResizableChild", ImVec2(-FLT_MIN, ImGui.GetTextLineHeightWithSpacing() * 8), bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.ResizeY)) then for n = 0, 9 do @@ -1149,6 +1295,13 @@ local function DemoWindowLayout_ChildWindows() ImGui.SeparatorText("Misc/Advanced") + -- Demonstrate a few extra things + -- - Changing ImGuiCol.ChildBg (which is transparent black in default styles) + -- - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window) + -- You can also call SetNextWindowPos() to position the child window. The parent window will effectively + -- layout from this position. + -- - Using ImGui.GetItemRectMin/Max() to query the "item" state (because the child window is an item from + -- the POV of the parent window). See 'Demo->Querying Status (Edited/Active/Hovered etc.)' for details. do if SL.child_flags == nil then SL.child_flags = bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY) end ImGui.SetNextItemWidth(ImGui.GetFontSize() * 8) @@ -1189,6 +1342,11 @@ local function DemoWindowLayout_WidgetsWidth() IMGUI_DEMO_MARKER("Layout/Widgets Width") _, SL.show_indented_items = ImGui.Checkbox("Show indented items", SL.show_indented_items) + -- Use SetNextItemWidth() to set the width of a single upcoming item. + -- Use PushItemWidth()/PopItemWidth() to set the width of a group of items. + -- In real code use you'll probably want to choose width values that are proportional to your font size + -- e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc. + local function block(text, help, width, l1, l2) ImGui.Text(text) if help then ImGui.SameLine(); DemoHelpMarker(help) end @@ -1207,6 +1365,7 @@ local function DemoWindowLayout_WidgetsWidth() block("SetNextItemWidth/PushItemWidth(-GetContentRegionAvail().x * 0.5f)", "Align to right edge minus half", -ImGui.GetContentRegionAvail().x * 0.5, "float##4a", "float (indented)##4b") block("SetNextItemWidth/PushItemWidth(-Min(GetContentRegionAvail().x * 0.40f, GetFontSize() * 12))", nil, -IM_MIN(ImGui.GetFontSize() * 12, ImGui.GetContentRegionAvail().x * 0.40), "float##5a", "float (indented)##5b") -- Demonstrate using PushItemWidth to surround three items. + -- Calling SetNextItemWidth() before each of them would have the same effect. block("SetNextItemWidth/PushItemWidth(-FLT_MIN)", "Align to right edge", -FLT_MIN, "##float6a", "float (indented)##6b") end @@ -1274,6 +1433,7 @@ local function DemoWindowLayout_BasicHorizontal() NotPorted("ListBox") end ImGui.PopID() + -- ImGui.SetItemTooltip("ListBox %d hovered", i) end ImGui.PopItemWidth() @@ -1285,6 +1445,7 @@ local function DemoWindowLayout_BasicHorizontal() ImGui.Button("B", button_sz) -- Manually wrapping + -- (we should eventually provide this as an automatic layout feature, but for now you can do it manually) IMGUI_DEMO_MARKER("Layout/Basic Horizontal Layout/Manual wrapping") ImGui.Text("Manual wrapping:") local style = ImGui.GetStyle() @@ -1358,6 +1519,9 @@ local function DemoWindowLayout_TextBaseline() ImGui.Button("Some framed item"); ImGui.SameLine() DemoHelpMarker("Baseline of button will look misaligned with text..") + -- If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. + -- (because we don't know what's coming after the Text() statement, we need to move the text baseline + -- down by FramePadding.y ahead of time) ImGui.AlignTextToFramePadding() ImGui.Text("OK Blahblah"); ImGui.SameLine() ImGui.Button("Some framed item##2"); ImGui.SameLine() @@ -1368,6 +1532,7 @@ local function DemoWindowLayout_TextBaseline() ImGui.Text("TEST"); ImGui.SameLine() ImGui.SmallButton("TEST##2") + -- If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets. ImGui.AlignTextToFramePadding() ImGui.Text("Text aligned to framed item"); ImGui.SameLine() ImGui.Button("Item##1"); ImGui.SameLine() @@ -1408,6 +1573,7 @@ local function DemoWindowLayout_TextBaseline() ImGui.BulletText("Misc items:") ImGui.Indent() + -- SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button. ImGui.Button("80x80", ImVec2(80, 80)) ImGui.SameLine() ImGui.Button("50x50", ImVec2(50, 50)) @@ -1417,10 +1583,12 @@ local function DemoWindowLayout_TextBaseline() ImGui.SmallButton("SmallButton()") -- Tree + -- (here the node appears after a button and has odd intent, so we use ImGuiTreeNodeFlags.DrawLinesNone to disable hierarchy outline) local spacing = ImGui.GetStyle().ItemInnerSpacing.x ImGui.Button("Button##1") -- Will make line higher ImGui.SameLine(0.0, spacing) if ImGui.TreeNodeEx("Node##1", ImGuiTreeNodeFlags.DrawLinesNone) then + -- Placeholder tree data for i = 0, 5 do ImGui.BulletText("Item %d..", i) end @@ -1436,11 +1604,16 @@ local function DemoWindowLayout_TextBaseline() ImGui.TreePop() end + -- Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. + -- Otherwise you can use SmallButton() (smaller fit). ImGui.AlignTextToFramePadding() + -- Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add + -- other contents "inside" the node. local node_open = ImGui.TreeNode("Node##3") ImGui.SameLine(0.0, spacing); ImGui.Button("Button##3") if node_open then + -- Placeholder tree data for i = 0, 5 do ImGui.BulletText("Item %d..", i) end @@ -1471,12 +1644,12 @@ local function DemoWindowLayout_HorizontalContentsSizeWindow() "Test how different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\n" .. "Use 'Metrics->Tools->Show windows rectangles' to visualize rectangles.") _, SL.show_h_scrollbar = ImGui.Checkbox("H-scrollbar", SL.show_h_scrollbar) - _, SL.show_button = ImGui.Checkbox("Button", SL.show_button) - _, SL.show_tree_nodes = ImGui.Checkbox("Tree nodes", SL.show_tree_nodes) - _, SL.show_text_wrapped = ImGui.Checkbox("Text wrapped", SL.show_text_wrapped) - _, SL.show_columns = ImGui.Checkbox("Columns", SL.show_columns) - _, SL.show_tab_bar = ImGui.Checkbox("Tab bar", SL.show_tab_bar) - _, SL.show_child = ImGui.Checkbox("Child", SL.show_child) + _, SL.show_button = ImGui.Checkbox("Button", SL.show_button) -- Will grow contents size (unless explicitly overwritten) + _, SL.show_tree_nodes = ImGui.Checkbox("Tree nodes", SL.show_tree_nodes) -- Will grow contents size and display highlight over full width + _, SL.show_text_wrapped = ImGui.Checkbox("Text wrapped", SL.show_text_wrapped) -- Will grow and use contents size + _, SL.show_columns = ImGui.Checkbox("Columns", SL.show_columns) -- Will use contents size + _, SL.show_tab_bar = ImGui.Checkbox("Tab bar", SL.show_tab_bar) -- Will use contents size + _, SL.show_child = ImGui.Checkbox("Child", SL.show_child) -- Will grow and use contents size _, SL.explicit_content_size = ImGui.Checkbox("Explicit content size", SL.explicit_content_size) ImGui.Text("Scroll %.1f/%.1f %.1f/%.1f", ImGui.GetScrollX(), ImGui.GetScrollMaxX(), ImGui.GetScrollY(), ImGui.GetScrollMaxY()) if SL.explicit_content_size then @@ -1544,6 +1717,7 @@ end local function DemoWindowLayout_Scrolling() IMGUI_DEMO_MARKER("Layout/Scrolling/Vertical") + -- Vertical scroll functions DemoHelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position.") _, SL.enable_extra_decorations = ImGui.Checkbox("Decoration", SL.enable_extra_decorations) @@ -1634,7 +1808,7 @@ local function DemoWindowLayout_Scrolling() if scroll_to_pos then ImGui.SetScrollFromPosX(ImGui.GetCursorStartPos().x + SL.scroll_to_pos_px, i * 0.25) end - if child_is_visible then + if child_is_visible then -- Avoid calling SetScrollHereY when running with culled items for item = 0, 99 do if item > 0 then ImGui.SameLine() @@ -1667,6 +1841,10 @@ local function DemoWindowLayout_Scrolling() local scrolling_child_size = ImVec2(0, ImGui.GetFrameHeightWithSpacing() * 7 + 30) BeginChild("scrolling", scrolling_child_size, ImGuiChildFlags.Borders, ImGuiWindowFlags.HorizontalScrollbar) for line = 0, SL.lines - 1 do + -- Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine() + -- If you want to create your own time line for a real application you may be better off manipulating + -- the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets + -- yourself. You may also want to use the lower-level ImDrawList API. local num_buttons = 10 + ((line % 2 == 1) and line * 9 or line * 3) local base_w = ImGui.GetFontSize() * 3 for n = 0, num_buttons - 1 do @@ -1701,6 +1879,7 @@ local function DemoWindowLayout_Scrolling() ImGui.Text("%.0f/%.0f", scroll_x, scroll_max_x) if scroll_x_delta ~= 0.0 then -- Demonstrate a trick: you can use Begin to set yourself in the context of another window + -- (here we are already out of your child window) BeginChild("scrolling") ImGui.SetScrollX(ImGui.GetScrollX() + scroll_x_delta) ImGui.EndChild() @@ -1765,7 +1944,7 @@ local function DemoWindowLayout_TextClipping() draw_list:AddText(text_pos, IM_COL32_WHITE, text_str) draw_list:PopClipRect() else - local clip_rect = ImVec4(p0.x, p0.y, p1.x, p1.y) + local clip_rect = ImVec4(p0.x, p0.y, p1.x, p1.y) -- AddText() takes a ImVec4 here so let's convert. draw_list:AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255)) draw_list:AddText(ImGui.GetFont(), ImGui.GetFontSize(), text_pos, IM_COL32_WHITE, text_str, 1, #text_str + 1, 0.0, clip_rect) end @@ -1789,6 +1968,9 @@ local function DemoWindowLayout_OverlapMode() ImGui.SetCursorScreenPos(button2_pos) ImGui.Button("Button 2", ImVec2(80, 80)) + -- This is typically used with width-spanning items. + -- (note that Selectable() has a dedicated flag ImGuiSelectableFlags.AllowOverlap, which is a shortcut + -- for using SetNextItemAllowOverlap(). For demo purpose we use SetNextItemAllowOverlap() here.) if SL.enable_allow_overlap then ImGui.SetNextItemAllowOverlap() end @@ -1830,6 +2012,8 @@ local function DemoWindowPopups_Popups() local names = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" } local toggles = SP.toggles + -- Simple selection popup (if you want to show the current selection inside the Button itself, + -- you may want to build a string using the "###" operator to preserve a constant ID with a variable label) if ImGui.Button("Select..") then ImGui.OpenPopup("my_select_popup") end @@ -1911,7 +2095,20 @@ local function DemoWindowPopups_ContextMenus() IMGUI_DEMO_MARKER("Popups/Context menus") DemoHelpMarker("\"Context\" functions are simple helpers to associate a Popup to a given Item or Window identifier.") + -- BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing: + -- if id == 0 then + -- id = GetItemID() -- Use last item id + -- end + -- if IsItemHovered() and IsMouseReleased(ImGuiMouseButton.Right) then + -- OpenPopup(id) + -- end + -- return BeginPopup(id) + -- For advanced uses you may want to replicate and customize this code. + -- See more details in BeginPopupContextItem(). + -- Example 1 + -- When used after an item that has an ID (e.g. Button), we can skip providing an ID to BeginPopupContextItem(), + -- and BeginPopupContextItem() will use the last item ID as the popup ID. do local names = { "Label1", "Label2", "Label3", "Label4", "Label5" } for n = 0, 4 do @@ -1931,6 +2128,8 @@ local function DemoWindowPopups_ContextMenus() end -- Example 2 + -- Popup on a Text() element which doesn't have an identifier: we need to provide an identifier to BeginPopupContextItem(). + -- Using an explicit identifier is also convenient if you want to activate the popups from different locations. do DemoHelpMarker("Text() elements don't have stable identifiers so we need to provide one.") ImGui.Text("Value = %.3f <-- (1) right-click this text", SP.value) @@ -1942,15 +2141,22 @@ local function DemoWindowPopups_ContextMenus() ImGui.EndPopup() end + -- We can also use OpenPopupOnItemClick() to toggle the visibility of a given popup. + -- Here we make it that right-clicking this other text element opens the same popup as above. + -- The popup itself will be submitted by the code above. ImGui.Text("(2) Or right-click this text") ImGui.OpenPopupOnItemClick("my popup", ImGuiPopupFlags.MouseButtonRight) + -- Back to square one: manually open the same popup. if ImGui.Button("(3) Or click this button") then ImGui.OpenPopup("my popup") end end -- Example 3 + -- When using BeginPopupContextItem() with an implicit identifier (nil == use last item ID), + -- we need to make sure your item identifier is stable. + -- In this example we showcase altering the item label while preserving its identifier, using the ### operator (see FAQ). do DemoHelpMarker("Showcase using a popup ID linked to item ID, with the item having a changing label + stable ID using the ### operator.") if SP.name == nil then SP.name = Buf("Label1", 32) end @@ -1984,6 +2190,9 @@ local function DemoWindowPopups_Modals() ImGui.Text("All those beautiful files will be deleted.\nThis operation cannot be undone!") ImGui.Separator() + -- local unused_i = 0 + -- unused_i = ImGui.Combo("Combo", unused_i, "Delete\0Delete harder\0") + ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, ImVec2(0, 0)) _, SP.dont_ask_me_next_time = ImGui.Checkbox("Don't ask me next time", SP.dont_ask_me_next_time) ImGui.PopStyleVar() @@ -2020,6 +2229,9 @@ local function DemoWindowPopups_Modals() ImGui.OpenPopup("Stacked 2") end + -- Also demonstrate passing a p_open bool to BeginPopupModal(), this will create a regular close button which + -- will close the popup. Note that the visibility state of popups is owned by imgui, so the input value + -- of the bool actually doesn't matter here. local unused_open = true if ImGui.BeginPopupModal("Stacked 2", unused_open) then ImGui.Text("Hello from Stacked The Second!") @@ -2042,6 +2254,24 @@ function DemoWindowPopups() return end + -- The properties of popups windows are: + -- - They block normal mouse hovering detection outside them. (*) + -- - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE. + -- - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as + -- we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup(). + -- (*) One can use IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByPopup) to bypass it and detect hovering even + -- when normally blocked by a popup. + -- Those three properties are connected. The library needs to hold their visibility state BECAUSE it can close + -- popups at any time. + + -- Typical use for regular windows: + -- local my_tool_is_active = false; if ImGui.Button("Open") then my_tool_is_active = true end; [...] if my_tool_is_active then my_tool_is_active, visible = ImGui.Begin("My Tool", my_tool_is_active); [...] ImGui.End() end + -- Typical use for popups: + -- if ImGui.Button("Open") then ImGui.OpenPopup("MyPopup") end; if ImGui.BeginPopup("MyPopup") then [...] ImGui.EndPopup() end + + -- With popups we have to go through a library call (here OpenPopup) to manipulate the visibility state. + -- This may be a bit confusing at first but it should quickly make sense. Follow on the examples below. + if ImGui.TreeNode("Popups") then DemoWindowPopups_Popups(); ImGui.TreePop() end if ImGui.TreeNode("Context menus") then DemoWindowPopups_ContextMenus(); ImGui.TreePop() end if ImGui.TreeNode("Modals") then @@ -2068,6 +2298,11 @@ end -- [SECTION] DemoWindowTables() ------------------------------------------------------------------------------- +-- Dummy data structure that we use for the Table demo. +-- We are passing our own identifier to TableSetupColumn() to facilitate identifying columns in the sorting code. +-- This identifier will be passed down into ImGuiTableSortSpec::ColumnUserID. +-- But it is possible to omit the user id parameter of TableSetupColumn() and just use the column index instead! (ImGuiTableSortSpec::ColumnIndex) +-- If you don't use sorting, you will generally never care about giving column an ID! -- MyItemColumnID local MyItemColumnID_ID, MyItemColumnID_Name, MyItemColumnID_Action, MyItemColumnID_Quantity, MyItemColumnID_Description = 0, 1, 2, 3, 4 @@ -2083,6 +2318,8 @@ local function MyItem_SortWithSortSpecs(sort_specs, items, items_count) end local function cmp(a, b) -- returns <0, 0, >0 for n = 0, sort_specs.SpecsCount - 1 do + -- Here we identify columns using the ColumnUserID value that we ourselves passed to TableSetupColumn() + -- We could also choose to identify columns based on their index (sort_spec.ColumnIndex), which is simpler! local sort_spec = get_spec(n) local delta = 0 local uid = sort_spec.ColumnUserID @@ -2098,6 +2335,10 @@ local function MyItem_SortWithSortSpecs(sort_specs, items, items_count) return (sort_spec.SortDirection == ImGuiSortDirection.Ascending) and -1 or 1 end end + + -- table.sort() is instable so always return a way to differentiate items. + -- Your own compare function may want to avoid fallback on implicit sort specs. + -- e.g. a Name compare if it wasn't already part of the sort specs. return a.ID - b.ID end local arr = items.Data or items @@ -2205,11 +2446,16 @@ local function bor(...) return bit32.bor(...) end local TF = setmetatable({}, { __index = function(_, k) return ImGuiTableFlags[k] end }) local ST = {} -- statics for DemoWindowTables (one sub-table per section) +-- Using those as a base value to create width/height that are factor of the size of our font local TEXT_BASE_WIDTH, TEXT_BASE_HEIGHT = 0, 0 local function Tables_Basic() IMGUI_DEMO_MARKER("Tables/Basic") + -- Here we will showcase three different ways to output a table. + -- They are very simple variations of a same thing! + -- [Method 1] Using TableNextRow() to create a new row, and TableSetColumnIndex() to select the column. + -- In many situations, this is the most flexible and easy to use pattern. DemoHelpMarker("Using TableNextRow() + calling TableSetColumnIndex() _before_ each cell, in a loop.") if ImGui.BeginTable("table1", 3) then for row = 0, 3 do @@ -2223,6 +2469,7 @@ local function Tables_Basic() end -- [Method 2] Using TableNextColumn() called multiple times, instead of using a for loop + TableSetColumnIndex(). + -- This is generally more convenient when you have code manually submitting the contents of each column. DemoHelpMarker("Using TableNextRow() + calling TableNextColumn() _before_ each cell, manually.") if ImGui.BeginTable("table2", 3) then for row = 0, 3 do @@ -2238,6 +2485,8 @@ local function Tables_Basic() end -- [Method 3] We call TableNextColumn() _before_ each cell. We never call TableNextRow(), + -- as TableNextColumn() will automatically wrap around and create new rows as needed. + -- This is generally more convenient when your cells all contains the same type of data. DemoHelpMarker( "Only using TableNextColumn(), which tends to be convenient for tables where every cell contains " .. "the same type of contents.\n This is also more similar to the old NextColumn() function of the " .. @@ -2253,6 +2502,7 @@ end local function Tables_BordersBackground() IMGUI_DEMO_MARKER("Tables/Borders, background") + -- Expose a few Borders related flags interactively local CT_Text, CT_FillButton = 0, 1 local s = ST.borders if s == nil then s = { flags = bor(TF.Borders, TF.RowBg), display_headers = false, contents_type = CT_Text }; ST.borders = s end @@ -2287,6 +2537,8 @@ local function Tables_BordersBackground() PopStyleCompact() if ImGui.BeginTable("table1", 3, s.flags) then + -- Display headers so we can inspect their interaction with borders + -- (Headers are not the main purpose of this section of the demo, so we are not elaborating on them now. See other sections for details) if s.display_headers then ImGui.TableSetupColumn("One") ImGui.TableSetupColumn("Two") @@ -2325,6 +2577,8 @@ end local function Tables_ResizableStretch() IMGUI_DEMO_MARKER("Tables/Resizable, stretch") + -- By default, if we don't enable ScrollX the sizing policy for each column is "Stretch" + -- All columns maintain a sizing weight, and they will occupy all available width. local s = ST.rstretch if s == nil then s = { flags = bor(TF.SizingStretchSame, TF.Resizable, TF.BordersOuter, TF.BordersV, TF.ContextMenuInBody) }; ST.rstretch = s end PushStyleCompact() @@ -2340,6 +2594,10 @@ end local function Tables_ResizableFixed() IMGUI_DEMO_MARKER("Tables/Resizable, fixed") + -- Here we use ImGuiTableFlags.SizingFixedFit (even though _ScrollX is not set) + -- So columns will adopt the "Fixed" policy and will maintain a fixed width regardless of the whole available width (unless table is small) + -- If there is not enough available width to fit all columns, they will however be resized down. + -- FIXME-TABLE: Providing a stretch-on-init would make sense especially for tables which don't have saved settings DemoHelpMarker( "Using _Resizable + _SizingFixedFit flags.\n" .. "Fixed-width columns generally makes more sense if you want to use horizontal scrolling.\n\n" .. @@ -2411,6 +2669,8 @@ local function Tables_Reorderable() PopStyleCompact() if ImGui.BeginTable("table1", 3, s.flags) then + -- Submit columns name with TableSetupColumn() and call TableHeadersRow() to create a row with a header in each column. + -- (Later we will show how TableSetupColumn() has other uses, optional flags, sizing weight etc.) ImGui.TableSetupColumn("One") ImGui.TableSetupColumn("Two") ImGui.TableSetupColumn("Three") @@ -2426,6 +2686,7 @@ local function Tables_Reorderable() end -- Use outer_size.x == 0.0f instead of default to make the table as tight as possible + -- (only valid when no scrolling and no stretch column) if ImGui.BeginTable("table2", 3, bor(s.flags, TF.SizingFixedFit), ImVec2(0.0, 0.0)) then ImGui.TableSetupColumn("One") ImGui.TableSetupColumn("Two") @@ -2444,6 +2705,8 @@ end local function Tables_Padding() IMGUI_DEMO_MARKER("Tables/Padding") + -- First example: showcase use of padding flags and effect of BorderOuterV/BorderInnerV on X padding. + -- We don't expose BorderOuterH/BorderInnerH here because they have no effect on X padding. DemoHelpMarker( "We often want outer padding activated when any using features which makes the edges of a column visible:\n" .. "e.g.:\n" .. @@ -2457,7 +2720,7 @@ local function Tables_Padding() local s = ST.padding if s == nil then s = { flags1 = TF.BordersV, show_headers = false, flags2 = bor(TF.Borders, TF.RowBg), cell_padding = ImVec2(0.0, 0.0), - show_widget_frame_bg = true, text_bufs = {}, init = true } + show_widget_frame_bg = true, text_bufs = {}, init = true } -- text_bufs: Mini text storage for 3x5 cells ST.padding = s end PushStyleCompact() @@ -2490,12 +2753,16 @@ local function Tables_Padding() local buf = string.format("Hello %d,%d", column, row) ImGui.Button(buf, ImVec2(-FLT_MIN, 0.0)) end + -- if bit32.band(ImGui.TableGetColumnFlags(), ImGuiTableColumnFlags.IsHovered) ~= 0 then + -- ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, IM_COL32(0, 100, 0, 255)) + -- end end end ImGui.EndTable() end -- Second example: set style.CellPadding to (0.0) or a custom value. + -- FIXME-TABLE: Vertical border effectively not displayed the same way as horizontal one... DemoHelpMarker("Setting style.CellPadding to (0,0) or a custom value.") PushStyleCompact() @@ -2553,6 +2820,9 @@ local function Tables_SizingPolicies() ImGui.SetNextItemWidth(TEXT_BASE_WIDTH * 30) s.sizing_policy_flags[table_n + 1] = EditTableSizingFlags(s.sizing_policy_flags[table_n + 1]) + -- To make it easier to understand the different sizing policy, + -- For each policy: we display one table where the columns have equal contents width, + -- and one where the columns have different contents width. if ImGui.BeginTable("table1", 3, bor(s.sizing_policy_flags[table_n + 1], s.flags1)) then for row = 0, 2 do ImGui.TableNextRow() @@ -2643,6 +2913,8 @@ local function Tables_VerticalScrolling() _, s.flags = ImGui.CheckboxFlags("ImGuiTableFlags_ScrollY", s.flags, TF.ScrollY) PopStyleCompact() + -- When using ScrollX or ScrollY we need to specify a size for our table container! + -- Otherwise by default the table will fit all available space, like a BeginChild() call. local outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 8) if ImGui.BeginTable("table_scrolly", 3, s.flags, outer_size) then ImGui.TableSetupScrollFreeze(0, 1) -- Make top row always visible @@ -2693,6 +2965,8 @@ local function Tables_HorizontalScrolling() s.freeze_rows = ImGui.DragInt("freeze_rows", s.freeze_rows, 0.2, 0, 9, nil, ImGuiSliderFlags.NoInput) PopStyleCompact() + -- When using ScrollX or ScrollY we need to specify a size for our table container! + -- Otherwise by default the table will fit all available space, like a BeginChild() call. local outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 8) if ImGui.BeginTable("table_scrollx", 7, s.flags, outer_size) then ImGui.TableSetupScrollFreeze(s.freeze_cols, s.freeze_rows) @@ -2707,6 +2981,12 @@ local function Tables_HorizontalScrolling() for row = 0, 19 do ImGui.TableNextRow() for column = 0, 6 do repeat + -- Both TableNextColumn() and TableSetColumnIndex() return true when a column is visible or performing width measurement. + -- Because here we know that: + -- - A) all our columns are contributing the same to row height + -- - B) column 0 is always visible, + -- We only always submit this one column and can skip others. + -- More advanced per-column clipping behaviors may benefit from polling the status flags via TableGetColumnFlags(). if not ImGui.TableSetColumnIndex(column) and column > 0 then break -- continue end @@ -2747,11 +3027,12 @@ end local function Tables_ColumnsFlags() IMGUI_DEMO_MARKER("Tables/Columns flags") + -- Create a first table just to show all the options/flags we want to make visible in our example! local column_count = 3 local column_names = { "One", "Two", "Three" } local s = ST.colflags if s == nil then - s = { column_flags = { ImGuiTableColumnFlags.DefaultSort, ImGuiTableColumnFlags.None, ImGuiTableColumnFlags.DefaultHide }, column_flags_out = { 0, 0, 0 } } + s = { column_flags = { ImGuiTableColumnFlags.DefaultSort, ImGuiTableColumnFlags.None, ImGuiTableColumnFlags.DefaultHide }, column_flags_out = { 0, 0, 0 } } -- column_flags_out: Output from TableGetColumnFlags() ST.colflags = s end @@ -2776,6 +3057,10 @@ local function Tables_ColumnsFlags() ImGui.EndTable() end + -- Create the real table we care about for the example! + -- We use a scrolling table to be able to showcase the difference between the _IsEnabled and _IsVisible flags above, + -- otherwise in a non-scrolling table columns are always visible (unless using ImGuiTableFlags_NoKeepColumnsVisible + -- + resizing the parent window down). local flags = bor(TF.SizingFixedFit, TF.ScrollX, TF.ScrollY, TF.RowBg, TF.BordersOuter, TF.BordersV, TF.Resizable, TF.Reorderable, TF.Hideable, TF.Sortable) local outer_size = ImVec2(0.0, TEXT_BASE_HEIGHT * 9) if ImGui.BeginTable("table_columns_flags", column_count, flags, outer_size) then @@ -2819,6 +3104,7 @@ local function Tables_ColumnsWidths() _, s.flags1 = ImGui.CheckboxFlags("ImGuiTableFlags_NoBordersInBodyUntilResize", s.flags1, TF.NoBordersInBodyUntilResize) PopStyleCompact() if ImGui.BeginTable("table1", 3, s.flags1) then + -- We could also set ImGuiTableFlags_SizingFixedFit on the table and all columns will default to ImGuiTableColumnFlags_WidthFixed. ImGui.TableSetupColumn("one", CF.WidthFixed, 100.0) -- Default to 100.0f ImGui.TableSetupColumn("two", CF.WidthFixed, 200.0) -- Default to 200.0f ImGui.TableSetupColumn("three", CF.WidthFixed) -- Default to auto @@ -2847,6 +3133,8 @@ local function Tables_ColumnsWidths() _, s.flags2 = ImGui.CheckboxFlags("ImGuiTableFlags_BordersOuterV", s.flags2, TF.BordersOuterV) PopStyleCompact() if ImGui.BeginTable("table2", 4, s.flags2) then + -- We could also set ImGuiTableFlags_SizingFixedFit on the table and then all columns + -- will default to ImGuiTableColumnFlags_WidthFixed. ImGui.TableSetupColumn("", CF.WidthFixed, 100.0) ImGui.TableSetupColumn("", CF.WidthFixed, TEXT_BASE_WIDTH * 15.0) ImGui.TableSetupColumn("", CF.WidthFixed, TEXT_BASE_WIDTH * 30.0) @@ -2964,6 +3252,8 @@ end local function Tables_OuterSize() IMGUI_DEMO_MARKER("Tables/Outer size") + -- Showcasing use of ImGuiTableFlags_NoHostExtendX and ImGuiTableFlags_NoHostExtendY + -- Important to that note how the two flags have slightly different behaviors! ImGui.Text("Using NoHostExtendX and NoHostExtendY:") PushStyleCompact() local s = ST.outer @@ -3040,6 +3330,8 @@ local function Tables_BackgroundColor() for row = 0, 5 do ImGui.TableNextRow() + -- Demonstrate setting a row background color with 'ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBgX, ...)' + -- We use a transparent color so we can see the one behind in case our target is RowBg1 and RowBg0 was already targeted by the ImGuiTableFlags_RowBg flag. if s.row_bg_type ~= 0 then local row_bg_color = ImGui.GetColorU32(s.row_bg_type == 1 and ImVec4(0.7, 0.3, 0.3, 0.65) or ImVec4(0.2 + row * 0.1, 0.2, 0.2, 0.65)) -- Flat or Gradient? ImGui.TableSetBgColor(ImGuiTableBgTarget.RowBg0 + s.row_bg_target, row_bg_color) @@ -3050,6 +3342,10 @@ local function Tables_BackgroundColor() ImGui.TableSetColumnIndex(column) ImGui.Text("%s%s", string.char(65 + row), string.char(48 + column)) + -- Change background of Cells B1->C2 + -- Demonstrate setting a cell background color with 'ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, ...)' + -- (the CellBg color will be blended over the RowBg and ColumnBg colors) + -- We can also pass a column number as a third parameter to TableSetBgColor() and do this outside the column loop. if row >= 1 and row <= 2 and column >= 1 and column <= 2 and s.cell_bg_type == 1 then local cell_bg_color = ImGui.GetColorU32(ImVec4(0.3, 0.3, 0.7, 0.65)) ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, cell_bg_color) @@ -3060,6 +3356,7 @@ local function Tables_BackgroundColor() end end +-- Simple storage to output a dummy file-system. local tree_view_nodes = { { Name = "Root with Long Name", Type = "Folder", Size = -1, ChildIdx = 1, ChildCount = 3 }, -- 0 { Name = "Music", Type = "Folder", Size = -1, ChildIdx = 4, ChildCount = 2 }, -- 1 @@ -3121,6 +3418,7 @@ local function Tables_TreeView() DemoHelpMarker("See \"Columns flags\" section to configure how indentation is applied to individual columns.") if ImGui.BeginTable("3ways", 3, s.table_flags) then + -- The first column will use the default _WidthStretch when ScrollX is Off and _WidthFixed when ScrollX is On ImGui.TableSetupColumn("Name", ImGuiTableColumnFlags.NoHide) ImGui.TableSetupColumn("Size", ImGuiTableColumnFlags.WidthFixed, TEXT_BASE_WIDTH * 12.0) ImGui.TableSetupColumn("Type", ImGuiTableColumnFlags.WidthFixed, TEXT_BASE_WIDTH * 18.0) @@ -3170,6 +3468,7 @@ local function Tables_ItemWidth() end end +-- Demonstrate using TableHeader() calls instead of TableHeadersRow() local function Tables_CustomHeaders() IMGUI_DEMO_MARKER("Tables/Custom headers") local COLUMNS_COUNT = 3 @@ -3179,9 +3478,15 @@ local function Tables_CustomHeaders() ImGui.TableSetupColumn("Cherry") -- Dummy entire-column selection storage + -- FIXME: It would be nice to actually demonstrate full-featured selection using those checkbox. if ST.column_selected == nil then ST.column_selected = { false, false, false } end local column_selected = ST.column_selected + -- Instead of calling TableHeadersRow() we'll submit custom headers ourselves. + -- (A different approach is also possible: + -- - Specify ImGuiTableColumnFlags_NoHeaderLabel in some TableSetupColumn() call. + -- - Call TableHeadersRow() normally. This will submit TableHeader() with no name. + -- - Then call TableSetColumnIndex() to position yourself in the column and submit your stuff e.g. Checkbox().) ImGui.TableNextRow(ImGuiTableRowFlags.Headers) for column = 0, COLUMNS_COUNT - 1 do ImGui.TableSetColumnIndex(column) @@ -3208,6 +3513,7 @@ local function Tables_CustomHeaders() end end +-- Demonstrate using ImGuiTableColumnFlags_AngledHeader flag to create angled headers local function Tables_AngledHeaders() IMGUI_DEMO_MARKER("Tables/Angled headers") local column_names = { "Track", "cabasa", "ride", "smash", "tom-hi", "tom-mid", "tom-low", "hihat-o", "hihat-c", "snare-s", "snare-c", "clap", "rim", "kick" } @@ -3218,7 +3524,7 @@ local function Tables_AngledHeaders() if s == nil then s = { table_flags = bor(TF.SizingFixedFit, TF.ScrollX, TF.ScrollY, TF.BordersOuter, TF.BordersInnerH, TF.Hideable, TF.Resizable, TF.Reorderable, TF.HighlightHoveredColumn), column_flags = bor(ImGuiTableColumnFlags.AngledHeader, ImGuiTableColumnFlags.WidthFixed), - bools = {}, frozen_cols = 1, frozen_rows = 2 } + bools = {}, frozen_cols = 1, frozen_rows = 2 } -- bools: Dummy storage selection storage for i = 1, columns_count * rows_count do s.bools[i] = false end ST.angled = s end @@ -3274,6 +3580,8 @@ local function Tables_AngledHeaders() end end +-- Demonstrate creating custom context menus inside columns, +-- while playing it nice with context menus provided by TableHeadersRow()/TableHeader() local function Tables_ContextMenus() IMGUI_DEMO_MARKER("Tables/Context menus") DemoHelpMarker( @@ -3286,6 +3594,9 @@ local function Tables_ContextMenus() _, s.flags1 = ImGui.CheckboxFlags("ImGuiTableFlags_ContextMenuInBody", s.flags1, TF.ContextMenuInBody) PopStyleCompact() + -- Context Menus: first example + -- [1.1] Right-click on the TableHeadersRow() line to open the default table context menu. + -- [1.2] Right-click in columns also open the default table context menu (if ImGuiTableFlags_ContextMenuInBody is set) local COLUMNS_COUNT = 3 if ImGui.BeginTable("table_context_menu", COLUMNS_COUNT, s.flags1) then ImGui.TableSetupColumn("One") @@ -3306,6 +3617,10 @@ local function Tables_ContextMenus() ImGui.EndTable() end + -- Context Menus: second example + -- [2.1] Right-click on the TableHeadersRow() line to open the default table context menu. + -- [2.2] Right-click on the ".." to open a custom popup + -- [2.3] Right-click in columns to open another custom popup DemoHelpMarker( "Demonstrate mixing table context menu (over header), item context button (over button) " .. "and custom per-column context menu (over column body).") @@ -3340,6 +3655,8 @@ local function Tables_ContextMenus() end -- [2.3] Right-click anywhere in columns to open another custom popup + -- (instead of testing for not IsAnyItemHovered() we could also call OpenPopup() with ImGuiPopupFlags_NoOpenOverExistingPopup + -- to manage popup priority as the popups triggers, here "are we hovering a column" are overlapping) local hovered_column = -1 for column = 0, COLUMNS_COUNT do ImGui.PushID(column) @@ -3368,6 +3685,7 @@ local function Tables_ContextMenus() end end +-- Demonstrate creating multiple tables with the same ID local function Tables_SyncedInstances() IMGUI_DEMO_MARKER("Tables/Synced instances") DemoHelpMarker("Multiple tables with the same identifier will share their settings, width, visibility, order etc.") @@ -3396,6 +3714,9 @@ local function Tables_SyncedInstances() end end +-- Demonstrate using Sorting facilities +-- This is a simplified version of the "Advanced" example, where we mostly focus on the code necessary to handle sorting. +-- Note that the "Advanced" example also showcase manually triggering a sort (e.g. if item quantities have been modified) local template_items_names = { "Banana", "Apple", "Cherry", "Watermelon", "Grapefruit", "Strawberry", "Mango", "Kiwi", "Orange", "Pineapple", "Blueberry", "Plum", "Coconut", "Pear", "Apricot" @@ -3403,6 +3724,7 @@ local template_items_names = { local function Tables_Sorting() IMGUI_DEMO_MARKER("Tables/Sorting") + -- Create item list local s = ST.sorting if s == nil then s = { items = {}, @@ -3415,6 +3737,7 @@ local function Tables_Sorting() end local items = s.items + -- Options PushStyleCompact() _, s.flags = ImGui.CheckboxFlags("ImGuiTableFlags_SortMulti", s.flags, TF.SortMulti) ImGui.SameLine(); DemoHelpMarker("When sorting is enabled: hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).") @@ -3424,6 +3747,13 @@ local function Tables_Sorting() if ImGui.BeginTable("table_sorting", 4, s.flags, ImVec2(0.0, TEXT_BASE_HEIGHT * 15), 0.0) then local CF = ImGuiTableColumnFlags + -- Declare columns + -- We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + -- This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! + -- Demonstrate using a mixture of flags among available sort-related flags: + -- - ImGuiTableColumnFlags_DefaultSort + -- - ImGuiTableColumnFlags_NoSort / ImGuiTableColumnFlags_NoSortAscending / ImGuiTableColumnFlags_NoSortDescending + -- - ImGuiTableColumnFlags_PreferSortAscending / ImGuiTableColumnFlags_PreferSortDescending ImGui.TableSetupColumn("ID", bor(CF.DefaultSort, CF.WidthFixed), 0.0, MyItemColumnID_ID) ImGui.TableSetupColumn("Name", CF.WidthFixed, 0.0, MyItemColumnID_Name) ImGui.TableSetupColumn("Action", bor(CF.NoSort, CF.WidthFixed), 0.0, MyItemColumnID_Action) @@ -3554,6 +3884,8 @@ local function Tables_AdvancedOptions(s) "- OuterSize.x = 0.0f will narrow fit the table unless there are any Stretch columns.\n" .. "- OuterSize.y then becomes the minimum size for the table, which will extend vertically if there are more rows (unless NoHostExtendY is set).") + -- From a user point of view we will tend to use 'inner_width' differently depending on whether our table is embedding scrolling. + -- To facilitate toying with this demo we will actually pass 0.0f to the BeginTable() when ScrollX is disabled. s.inner_width_with_scroll = ImGui.DragFloat("inner_width (when ScrollX active)", s.inner_width_with_scroll, 1.0, 0.0, FLT_MAX) s.row_min_height = ImGui.DragFloat("row_min_height", s.row_min_height, 1.0, 0.0, FLT_MAX) @@ -3574,6 +3906,9 @@ local function Tables_AdvancedOptions(s) ImGui.Spacing() end +-- In this example we'll expose most table flags and settings. +-- For specific flags and settings refer to the corresponding section for more detailed explanation. +-- This section is mostly useful to experiment with combining certain flags or settings with each others. local function Tables_Advanced() IMGUI_DEMO_MARKER("Tables/Advanced") local CT_Text, CT_Button, CT_SmallButton, CT_FillButton, CT_Selectable, CT_SelectableSpanRow = 0, 1, 2, 3, 4, 5 @@ -3587,6 +3922,7 @@ local function Tables_Advanced() items = {}, selection = {}, items_need_sort = false, show_debug_details = false } ST.advanced = s end + --ImGui.SetNextItemOpen(true, ImGuiCond.Once) -- FIXME-TABLE: Enabling this results in initial clipped first pass on table which tend to affect column sizing if ImGui.TreeNode("Options") then Tables_AdvancedOptions(s) ImGui.TreePop() @@ -3606,7 +3942,7 @@ local function Tables_Advanced() local parent_draw_list = ImGui.GetWindowDrawList() local parent_draw_list_draw_cmd_count = parent_draw_list.CmdBuffer.Size local table_scroll_cur, table_scroll_max -- For debug display - local table_draw_list = nil + local table_draw_list = nil -- " -- Submit table local flags = s.flags @@ -3614,6 +3950,9 @@ local function Tables_Advanced() local inner_width_to_use = Has(flags, TF.ScrollX) and s.inner_width_with_scroll or 0.0 local CF = ImGuiTableColumnFlags if ImGui.BeginTable("table_advanced", 6, flags, s.outer_size_enabled and s.outer_size_value or ImVec2(0, 0), inner_width_to_use) then + -- Declare columns + -- We use the "user_id" parameter of TableSetupColumn() to specify a user id that will be stored in the sort specifications. + -- This is so our sort function can identify a column given our own identifier. We could also identify them based on their index! ImGui.TableSetupColumn("ID", bor(columns_base_flags, CF.DefaultSort, CF.WidthFixed, CF.NoHide), 0.0, MyItemColumnID_ID) ImGui.TableSetupColumn("Name", bor(columns_base_flags, CF.WidthFixed), 0.0, MyItemColumnID_Name) ImGui.TableSetupColumn("Action", bor(columns_base_flags, CF.NoSort, CF.WidthFixed), 0.0, MyItemColumnID_Action) @@ -3633,6 +3972,8 @@ local function Tables_Advanced() end s.items_need_sort = false + -- Take note of whether we are currently sorting based on the Quantity field, + -- we will use this to trigger sorting when we know the data of this column has been modified. local sorts_specs_using_quantity = Has(ImGui.TableGetColumnFlags(3), CF.IsSorted) -- Show headers @@ -3643,6 +3984,8 @@ local function Tables_Advanced() ImGui.TableHeadersRow() end + -- Show data + -- FIXME-TABLE FIXME-NAV: How we can get decent up/down even though we have the buttons here? -- Demonstrate using clipper for large vertical lists local clipper = ImGuiListClipper() clipper:Begin(#items) @@ -3686,6 +4029,10 @@ local function Tables_Advanced() ImGui.TextUnformatted(item.Name) end + -- Here we demonstrate marking our data set as needing to be sorted again if we modified a quantity, + -- and we are currently sorting on the column showing the Quantity. + -- To avoid triggering a sort while holding the button, we only trigger it when the button has been released. + -- You will probably need some extra logic if you want to automatically sort when a specific entry changes. if ImGui.TableSetColumnIndex(2) then if ImGui.SmallButton("Chop") then item.Quantity = item.Quantity + 1 end if sorts_specs_using_quantity and ImGui.IsItemDeactivated() then s.items_need_sort = true end @@ -3735,6 +4082,8 @@ end local DCS = { selected = -1, h_borders = true, v_borders = true, columns_count = 4, foo = 1.0, bar = 1.0 } +-- Demonstrate old/legacy Columns API! +-- [2020: Columns are under-featured and not maintained. Prefer using the more flexible and powerful BeginTable() API!] local function DemoWindowColumns() local open = ImGui.TreeNode("Legacy Columns API") ImGui.SameLine() @@ -3752,6 +4101,7 @@ local function DemoWindowColumns() for n = 0, 13 do local label = string.format("Item %d", n) if ImGui.Selectable(label) then end + --if ImGui.Button(label, ImVec2(-FLT_MIN,0.0)) then end ImGui.NextColumn() end ImGui.Columns(1) @@ -3950,6 +4300,7 @@ local tables_sections = { } function DemoWindowTables() + --ImGui.SetNextItemOpen(true, ImGuiCond.Once) if not ImGui.CollapsingHeader("Tables & Columns") then return end @@ -3980,6 +4331,16 @@ function DemoWindowTables() ImGui.PushStyleVar(ImGuiStyleVar.IndentSpacing, 0.0) end + -- About Styling of tables + -- Most settings are configured on a per-table basis via the flags passed to BeginTable() and TableSetupColumns APIs. + -- There are however a few settings that a shared and part of the ImGuiStyle structure: + -- style.CellPadding -- Padding within each cell + -- style.Colors[ImGuiCol.TableHeaderBg] -- Table header background + -- style.Colors[ImGuiCol.TableBorderStrong] -- Table outer and header borders + -- style.Colors[ImGuiCol.TableBorderLight] -- Table inner borders + -- style.Colors[ImGuiCol.TableRowBg] -- Table row background when ImGuiTableFlags_RowBg is enabled (even rows) + -- style.Colors[ImGuiCol.TableRowBgAlt] -- Table row background when ImGuiTableFlags_RowBg is enabled (odds rows) + -- Demos for _, sec in ipairs(tables_sections) do if open_action ~= -1 then @@ -4011,26 +4372,36 @@ local function BufSet(buf, str) buf[#str + 1] = 0 end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Debug Console / ShowExampleAppConsole() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a simple console window, with scrolling, filtering, completion and history. +-- For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions. local Console = nil local function ConsoleNew() + -- HistoryPos: -1: new line, 0..#History-1 browsing history. + -- "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches. local c = { InputBuf = Buf("", 256), Items = {}, Commands = { "HELP", "HISTORY", "CLEAR", "CLASSIFY" }, History = {}, HistoryPos = -1, Filter = ImGuiTextFilter(), AutoScroll = true, ScrollToBottom = false } function c:ClearLog() self.Items = {} end function c:AddLog(fmt, ...) + -- FIXME-OPT local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt self.Items[#self.Items + 1] = s end function c:ExecCommand(command_line) self:AddLog("# %s\n", command_line) + + -- Insert into history. First find match and delete it so it can be pushed to the back. + -- This isn't trying to be smart or optimal. self.HistoryPos = -1 for i = #self.History, 1, -1 do if string.upper(self.History[i]) == string.upper(command_line) then table.remove(self.History, i); break end end self.History[#self.History + 1] = command_line + + -- Process command local cmd = string.upper(command_line) if cmd == "CLEAR" then self:ClearLog() @@ -4043,10 +4414,15 @@ local function ConsoleNew() else self:AddLog("Unknown command: '%s'\n", command_line) end + + -- On command input, we scroll to bottom even if AutoScroll==false self.ScrollToBottom = true end function c:TextEditCallback(data) + --self:AddLog("cursor: %d, selection: %d-%d", data.CursorPos, data.SelectionStart, data.SelectionEnd) if data.EventFlag == ImGuiInputTextFlags.CallbackCompletion then + -- Example of TEXT COMPLETION + -- Locate beginning of current word (positions are 0-based offsets into data.Buf) local word_end = data.CursorPos local word_start = word_end @@ -4057,17 +4433,23 @@ local function ConsoleNew() end local word = "" for i = word_start + 1, word_end do word = word .. string.char(data.Buf[i]) end + + -- Build a list of candidates local candidates = {} for i = 1, #self.Commands do if string.upper(string.sub(self.Commands[i], 1, #word)) == string.upper(word) then candidates[#candidates + 1] = self.Commands[i] end end if #candidates == 0 then + -- No match self:AddLog("No match for \"%s\"!\n", word) elseif #candidates == 1 then + -- Single match. Delete the beginning of the word and replace it entirely so we've got nice casing. data:DeleteChars(word_start, word_end - word_start) data:InsertChars(data.CursorPos, candidates[1]) data:InsertChars(data.CursorPos, " ") else + -- Multiple matches. Complete as much as we can.. + -- So inputting "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches. local match_len = word_end - word_start while true do local ch, all_match = nil, true @@ -4082,10 +4464,13 @@ local function ConsoleNew() data:DeleteChars(word_start, word_end - word_start) data:InsertChars(data.CursorPos, string.sub(candidates[1], 1, match_len)) end + + -- List matches self:AddLog("Possible matches:\n") for i = 1, #candidates do self:AddLog("- %s\n", candidates[i]) end end elseif data.EventFlag == ImGuiInputTextFlags.CallbackHistory then + -- Example of HISTORY local prev_history_pos = self.HistoryPos if data.EventKey == ImGuiKey.UpArrow then if self.HistoryPos == -1 then self.HistoryPos = #self.History - 1 @@ -4096,6 +4481,8 @@ local function ConsoleNew() if self.HistoryPos >= #self.History then self.HistoryPos = -1 end end end + + -- A better implementation would preserve the data on the current input line along with cursor position. if prev_history_pos ~= self.HistoryPos then local history_str = (self.HistoryPos >= 0) and self.History[self.HistoryPos + 1] or "" data:DeleteChars(0, data.BufTextLen) @@ -4110,12 +4497,18 @@ local function ConsoleNew() p_open, visible = ImGui.Begin(title, p_open) if not visible then ImGui.End(); return p_open end + -- As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar. + -- So e.g. IsItemHovered() will return true when hovering the title bar. + -- Here we create a context menu only available from the title bar. if ImGui.BeginPopupContextItem() then if ImGui.MenuItem("Close Console") then p_open = false end ImGui.EndPopup() end ImGui.TextWrapped("This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc.") ImGui.TextWrapped("Enter 'HELP' for help.") + + -- TODO: display items starting from the bottom + if ImGui.SmallButton("Add Debug Text") then self:AddLog("%d some text", #self.Items); self:AddLog("some more text"); self:AddLog("display very important message here!") end ImGui.SameLine() if ImGui.SmallButton("Add Debug Error") then self:AddLog("[error] something went wrong") end @@ -4123,12 +4516,17 @@ local function ConsoleNew() if ImGui.SmallButton("Clear") then self:ClearLog() end ImGui.SameLine() local copy_to_clipboard = ImGui.SmallButton("Copy") + --local t = 0.0; if ImGui.GetTime() - t > 0.02 then t = ImGui.GetTime(); self:AddLog("Spam %f", t) end + ImGui.Separator() + -- Options menu if ImGui.BeginPopup("Options") then _, self.AutoScroll = ImGui.Checkbox("Auto-scroll", self.AutoScroll) ImGui.EndPopup() end + + -- Options, Filter ImGui.SetNextItemShortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.O), ImGuiInputFlags.Tooltip) if ImGui.Button("Options") then ImGui.OpenPopup("Options") end ImGui.SameLine() @@ -4137,6 +4535,7 @@ local function ConsoleNew() self.Filter:DrawWithHint("##Filter", "Filter (incl -excl)") ImGui.Separator() + -- Reserve enough left-over height for 1 separator + 1 input text local style = ImGui.GetStyle() local footer_height_to_reserve = (style.SeparatorSize or 1.0) + style.ItemSpacing.y + ImGui.GetFrameHeightWithSpacing() if ImGui.BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), ImGuiChildFlags.NavFlattened, ImGuiWindowFlags.HorizontalScrollbar) then @@ -4144,10 +4543,37 @@ local function ConsoleNew() if ImGui.Selectable("Clear") then self:ClearLog() end ImGui.EndPopup() end - ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(4, 1)) + + -- Display every line as a separate entry so we can change their color or add custom widgets. + -- If you only want raw text you can use ImGui.TextUnformatted(log.begin(), log.end()) + -- NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping + -- to only process visible items. The clipper will automatically measure the height of your first item and then + -- "seek" to display only items in the visible area. + -- To use the clipper we can replace your standard loop: + -- for i = 1, #Items do + -- With: + -- local clipper = ImGuiListClipper() + -- clipper:Begin(#Items) + -- while clipper:Step() do + -- for i = clipper.DisplayStart, clipper.DisplayEnd - 1 do + -- - That your items are evenly spaced (same height) + -- - That you have cheap random access to your elements (you can access them given their index, + -- without processing all the ones before) + -- You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property. + -- We would need random-access on the post-filtered list. + -- A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices + -- or offsets of items that passed the filtering test, recomputing this array when user changes the filter, + -- and appending newly elements as they are inserted. This is left as a task to the user until we can manage + -- to improve this example code! + -- If your items are of variable height: + -- - Split them into same height items would be simpler and facilitate random-seeking into your list. + -- - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items. + ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(4, 1)) -- Tighten spacing if copy_to_clipboard then ImGui.LogToClipboard() end for _, item in ipairs(self.Items) do if self.Filter:PassFilter(item) then + -- Normally you would store more information in your item than just a string. + -- (e.g. make Items[] an array of structure, store color/type etc.) local color if string.find(item, "[error]", 1, true) then color = ImVec4(1.0, 0.4, 0.4, 1.0) elseif string.sub(item, 1, 2) == "# " then color = ImVec4(1.0, 0.8, 0.6, 1.0) end @@ -4157,6 +4583,9 @@ local function ConsoleNew() end end if copy_to_clipboard then ImGui.LogFinish() end + + -- Keep up at the bottom of the scroll region if we were already at the bottom at the beginning of the frame. + -- Using a scrollbar or mouse-wheel will take away from the bottom edge. if self.ScrollToBottom or (self.AutoScroll and ImGui.GetScrollY() >= ImGui.GetScrollMaxY()) then ImGui.SetScrollHereY(1.0) end self.ScrollToBottom = false ImGui.PopStyleVar() @@ -4164,6 +4593,7 @@ local function ConsoleNew() ImGui.EndChild() ImGui.Separator() + -- Command-line local reclaim_focus = false local IT = ImGuiInputTextFlags local input_text_flags = bit32.bor(IT.EnterReturnsTrue, IT.EscapeClearsAll, IT.CallbackCompletion, IT.CallbackHistory) @@ -4173,8 +4603,10 @@ local function ConsoleNew() self.InputBuf[1] = 0 reclaim_focus = true end + + -- Auto-focus on window apparition ImGui.SetItemDefaultFocus() - if reclaim_focus then ImGui.SetKeyboardFocusHere(-1) end + if reclaim_focus then ImGui.SetKeyboardFocusHere(-1) end -- Auto focus previous widget ImGui.End() return p_open end @@ -4187,13 +4619,17 @@ function ShowExampleAppConsole(p_open) return Console:Draw("Example: Console", p_open) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Debug Log / ShowExampleAppLog() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Usage: +-- local my_log = ExampleAppLog() +-- my_log:AddLog("Hello %d world\n", 123) +-- my_log:Draw("title") -- Lines are stored as a Lua array (equivalent of Buf + LineOffsets) local function ExampleAppLog() - local l = { Lines = { "" }, Filter = ImGuiTextFilter(), AutoScroll = true } + local l = { Lines = { "" }, Filter = ImGuiTextFilter(), AutoScroll = true } -- AutoScroll: Keep scrolling if already at the bottom. function l:Clear() self.Lines = { "" } end function l:AddLog(fmt, ...) local s = (select("#", ...) > 0) and string.format(fmt, ...) or fmt @@ -4208,10 +4644,14 @@ local function ExampleAppLog() local visible p_open, visible = ImGui.Begin(title, p_open) if not visible then ImGui.End(); return p_open end + + -- Options menu if ImGui.BeginPopup("Options") then _, self.AutoScroll = ImGui.Checkbox("Auto-scroll", self.AutoScroll) ImGui.EndPopup() end + + -- Main window if ImGui.Button("Options") then ImGui.OpenPopup("Options") end ImGui.SameLine() local clear = ImGui.Button("Clear") @@ -4227,10 +4667,27 @@ local function ExampleAppLog() ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0)) local lines = self.Lines if self.Filter:IsActive() then + -- In this example we don't use the clipper when Filter is enabled. + -- This is because we don't have random access to the result of our filter. + -- A real application processing logs with ten of thousands of entries may want to store the result of + -- search/filter.. especially if the filtering function is not trivial (e.g. reg-exp). for line_no = 1, #lines do if self.Filter:PassFilter(lines[line_no]) then ImGui.TextUnformatted(lines[line_no]) end end else + -- The simplest and easy way to display the entire buffer: + -- ImGui.TextUnformatted(buf_begin, buf_end) + -- And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward + -- to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are + -- within the visible area. + -- If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them + -- on your side is recommended. Using ImGuiListClipper requires + -- - A) random access into your data + -- - B) items all being the same height, + -- both of which we can handle since we have an array pointing to the beginning of each line of text. + -- When using the filter (in the block of code above) we don't have random access into the data to display + -- anymore, which is why we don't use the clipper. Storing or skimming through the search result would make + -- it possible (and would be recommended if you want to search through tens of thousands of entries). local clipper = ImGuiListClipper() clipper:Begin(#lines) while clipper:Step() do @@ -4240,6 +4697,9 @@ local function ExampleAppLog() end ImGui.PopStyleVar() if copy then ImGui.LogFinish() end + + -- Keep up at the bottom of the scroll region if we were already at the bottom at the beginning of the frame. + -- Using a scrollbar or mouse-wheel will take away from the bottom edge. if self.AutoScroll and ImGui.GetScrollY() >= ImGui.GetScrollMaxY() then ImGui.SetScrollHereY(1.0) end end ImGui.EndChild() @@ -4249,9 +4709,14 @@ local function ExampleAppLog() return l end +-- Demonstrate creating a simple log window with basic filtering. local AppLog, AppLogCounter = nil, 0 function ShowExampleAppLog(p_open) AppLog = AppLog or ExampleAppLog() + + -- For the demo: add a debug button _BEFORE_ the normal log window contents + -- We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window. + -- Most of the contents of the window will be added by the log:Draw() call. ImGui.SetNextWindowSize(ImVec2(500, 400), ImGuiCond.FirstUseEver) p_open = ImGui.Begin("Example: Log", p_open) if ImGui.SmallButton("[Debug] Add 5 entries") then @@ -4265,13 +4730,16 @@ function ShowExampleAppLog(p_open) end end ImGui.End() + + -- Actually call in the regular Log helper (which will Begin() into the same window as we just did) return AppLog:Draw("Example: Log", p_open) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Simple Layout / ShowExampleAppLayout() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate create a window with multiple child windows. local LayoutSelected = 0 function ShowExampleAppLayout(p_open) ImGui.SetNextWindowSize(ImVec2(500, 440), ImGuiCond.FirstUseEver) @@ -4285,14 +4753,18 @@ function ShowExampleAppLayout(p_open) end ImGui.EndMenuBar() end + + -- Left ImGui.BeginChild("left pane", ImVec2(150, 0), bit32.bor(ImGuiChildFlags.Borders, ImGuiChildFlags.ResizeX)) for i = 0, 99 do if ImGui.Selectable(string.format("MyObject %d", i), LayoutSelected == i, ImGuiSelectableFlags.SelectOnNav) then LayoutSelected = i end end ImGui.EndChild() ImGui.SameLine() + + -- Right ImGui.BeginGroup() - ImGui.BeginChild("item view", ImVec2(0, -ImGui.GetFrameHeightWithSpacing())) + ImGui.BeginChild("item view", ImVec2(0, -ImGui.GetFrameHeightWithSpacing())) -- Leave room for 1 line below us ImGui.Text("MyObject: %d", LayoutSelected) ImGui.Separator() if ImGui.BeginTabBar("##Tabs", ImGuiTabBarFlags.None) then @@ -4316,9 +4788,14 @@ function ShowExampleAppLayout(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Some of the interactions are a bit lack-luster: +-- - We would want pressing validating or leaving the filter to somehow restore focus. +-- - We may want more advanced filtering (child nodes) and clipper support: both will need extra work. +-- - We would want to customize some keyboard interactions to easily keyboard navigate between the tree and the properties. +------------------------------------------------------------------------------- -- ExampleMemberInfo equivalent: field name, data type, component count local ExampleTreeNodeMemberInfos = { @@ -4330,19 +4807,30 @@ local ExampleTreeNodeMemberInfos = { local PropEd = { Filter = nil, SelectedNode = nil, UseClipper = false, NameBufs = setmetatable({}, { __mode = "k" }) } +-- Custom search filter +-- - Here we apply on root node only. +-- - This does a case insensitive stristr which is pretty heavy. In a real large-scale app you would likely store a filtered list which in turns would be trivial to linearize. function PropEd:IsNodePassingFilter(node) return node.Parent.Parent ~= nil or self.Filter:PassFilter(node.Name) end +-- To support node with same name we incorporate node.UID into the item ID. +-- (this would more naturally be done using PushID(node.UID) + TreeNodeEx(node.Name, tree_flags), +-- but it would require in DrawClippedTreeNodeAndAdvanceToNext() to add PushID() before TreePush(), and PopID() after TreePop(), +-- so instead we use TreeNodeEx(node.UID, tree_flags, "%s", node.Name) here) function PropEd:DrawTreeNode(node) local TN = ImGuiTreeNodeFlags ImGui.TableNextRow() ImGui.TableNextColumn() + -- OpenOnArrow | OpenOnDoubleClick: Standard opening mode as we are likely to want to add selection afterwards + -- NavLeftJumpsToParent: Left arrow support + -- SpanFullWidth: Span full width for easier mouse reach + -- DrawLinesToNodes: Always draw hierarchy outlines local tree_flags = bit32.bor(TN.OpenOnArrow, TN.OpenOnDoubleClick, TN.NavLeftJumpsToParent, TN.SpanFullWidth, TN.DrawLinesToNodes) - if node == self.SelectedNode then tree_flags = bit32.bor(tree_flags, TN.Selected) end - if #node.Childs == 0 then tree_flags = bit32.bor(tree_flags, TN.Leaf, TN.Bullet, TN.NoTreePushOnOpen) end + if node == self.SelectedNode then tree_flags = bit32.bor(tree_flags, TN.Selected) end -- Draw selection highlight + if #node.Childs == 0 then tree_flags = bit32.bor(tree_flags, TN.Leaf, TN.Bullet, TN.NoTreePushOnOpen) end -- Use _NoTreePushOnOpen + set is_open=false to avoid unnecessarily push/pop on leaves. if node.DataMyBool == false then ImGui.PushStyleColor(ImGuiCol.Text, ImGui.GetStyle().Colors[ImGuiCol.TextDisabled]) end - ImGui.SetNextItemStorageID(node.UID) + ImGui.SetNextItemStorageID(node.UID) -- Use node.UID as storage id local is_open = ImGui.TreeNodeEx(node.UID, tree_flags, "%s", node.Name) if #node.Childs == 0 then is_open = false end if node.DataMyBool == false then ImGui.PopStyleColor() end @@ -4350,6 +4838,10 @@ function PropEd:DrawTreeNode(node) return is_open end +-- Basic version, recursive. This is how you would generally draw a tree. +-- - Simple but going to be noticeably costly if you have a large amount of nodes as DrawTreeNode() is called for all of them. +-- - On my desktop PC (2020), for 10K nodes in an optimized build this takes ~1.2 ms +-- - Unlike arrays or grids which are very easy to clip, trees are currently more difficult to clip. function PropEd:DrawTree(node) for _, child in ipairs(node.Childs) do if self:IsNodePassingFilter(child) and self:DrawTreeNode(child) then @@ -4361,6 +4853,7 @@ end function PropEd:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) if self:IsNodePassingFilter(node) then + -- Draw node if within visible range local is_open if clipper.UserIndex >= clipper.DisplayStart and clipper.UserIndex < clipper.DisplayEnd then is_open = self:DrawTreeNode(node) @@ -4369,8 +4862,12 @@ function PropEd:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) if is_open then ImGui.TreePush(node.Name) end end clipper.UserIndex = clipper.UserIndex + 1 + + -- Next node: recurse into childs if is_open then return node.Childs[1] end end + + -- Next node: next sibling, otherwise move back to parent while node ~= nil do if node.IndexInParent + 1 < #node.Parent.Childs then return node.Parent.Childs[node.IndexInParent + 2] @@ -4382,8 +4879,18 @@ function PropEd:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) return nil end +-- More advanced version. Use a alternative clipping technique: fast-forwarding through non-visible chunks. +-- - On my desktop PC (2020), for 10K nodes in an optimized build this takes ~0.1 ms +-- (in ExampleTree_CreateDemoTree(), change 'ROOT_ITEMS_COUNT = 10000' to try with this amount of root nodes). +-- - 1. Use clipper with indeterminate count (items_count = INT_MAX): we need to call SeekCursorForItem() at the end once we know the count. +-- - 2. Use SetNextItemStorageID() to specify ID used for open/close storage, making it easy to call TreeNodeGetOpen() on any arbitrary node. +-- - 3. Linearize tree during traversal: our tree data structure makes it easy to access sibling and parents. +-- - Unlike clipping for a regular array or grid which may be done using random access limited to visible areas, +-- this technique requires traversing most accessible nodes. This could be made more optimal with extra work, +-- but this is a decent simplicity<>speed trade-off. +-- See https://github.com/ocornut/imgui/issues/3823 for discussions about this. function PropEd:DrawClippedTree(root_node) - local node = root_node.Childs[1] + local node = root_node.Childs[1] -- First node local clipper = ImGuiListClipper() clipper:Begin(INT_MAX) while clipper:Step() do @@ -4391,14 +4898,23 @@ function PropEd:DrawClippedTree(root_node) node = self:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) end end + + -- Keep going to count nodes and submit final count so we have a reliable scrollbar. + -- - One could consider caching this value and only refreshing it occasionally e.g. window is focused and an action occurs. + -- - Incorrect but cheap approximation would be to use 'clipper_current_idx = IM_MAX(clipper_current_idx, #root_node.Childs)' instead. + -- - If either of those is implemented, the general cost will approach zero when scrolling is at the top of the tree. while node ~= nil do node = self:DrawClippedTreeNodeAndAdvanceToNext(clipper, node) end + --clipper.UserIndex = math.max(clipper.UserIndex, #root_node.Childs) -- <-- Cheap approximation instead of while() loop above. clipper:SeekCursorForItem(clipper.UserIndex) end function PropEd:Draw(root_node) self.Filter = self.Filter or ImGuiTextFilter() + -- Left side: draw tree + -- - Currently using a table to benefit from RowBg feature + -- - Our tree node are all of equal height, facilitating the use of a clipper. if ImGui.BeginChild("##tree", ImVec2(300, 0), bit32.bor(ImGuiChildFlags.ResizeX, ImGuiChildFlags.Borders, ImGuiChildFlags.NavFlattened)) then ImGui.PushItemFlag(ImGuiItemFlags.NoNavDefaultFocus, true) _, self.UseClipper = ImGui.Checkbox("Use Clipper", self.UseClipper) @@ -4417,18 +4933,24 @@ function PropEd:Draw(root_node) end ImGui.EndChild() + -- Right side: draw properties ImGui.SameLine() - ImGui.BeginGroup() + + ImGui.BeginGroup() -- Lock X position local node = self.SelectedNode if node then ImGui.Text("%s", node.Name) ImGui.TextDisabled("UID: 0x%08X", node.UID) ImGui.Separator() if ImGui.BeginTable("##properties", 2, bit32.bor(ImGuiTableFlags.Resizable, ImGuiTableFlags.ScrollY)) then + -- Push object ID after we entered the table, so table is shared for all objects ImGui.PushID(node.UID) ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthFixed) - ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthStretch, 2.0) + ImGui.TableSetupColumn("", ImGuiTableColumnFlags.WidthStretch, 2.0) -- Default twice larger if node.HasData then + -- In a typical application, the structure description would be derived from a data-driven system. + -- - We try to mimic this with our ExampleMemberInfo structure and the ExampleTreeNodeMemberInfos[] array. + -- - Limits and some details are hard-coded to simplify the demo. for _, field_desc in ipairs(ExampleTreeNodeMemberInfos) do ImGui.TableNextRow() ImGui.PushID(field_desc.Name) @@ -4460,6 +4982,7 @@ function PropEd:Draw(root_node) ImGui.EndGroup() end +-- Demonstrate creating a simple property editor. local DemoTree = nil function ShowExampleAppPropertyEditor(p_open, demo_data) ImGui.SetNextWindowSize(ImVec2(430, 450), ImGuiCond.FirstUseEver) @@ -4473,10 +4996,11 @@ function ShowExampleAppPropertyEditor(p_open, demo_data) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Long Text / ShowExampleAppLongText() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate/test rendering huge amount of text, and the incidence of clipping. local LT = { test_type = 0, log = {}, lines = 0, bytes = 0 } function ShowExampleAppLongText(p_open) ImGui.SetNextWindowSize(ImVec2(520, 600), ImGuiCond.FirstUseEver) @@ -4499,9 +5023,11 @@ function ShowExampleAppLongText(p_open) end ImGui.BeginChild("Log") if LT.test_type == 0 then + -- Single call to TextUnformatted() with a big buffer LT.text = LT.text or table.concat(LT.log) ImGui.TextUnformatted(LT.text) elseif LT.test_type == 1 then + -- Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0)) local clipper = ImGuiListClipper() clipper:Begin(LT.lines) @@ -4510,6 +5036,7 @@ function ShowExampleAppLongText(p_open) end ImGui.PopStyleVar() else + -- Multiple calls to Text(), not clipped (slow) ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0)) for i = 0, LT.lines - 1 do ImGui.Text("%i The quick brown fox jumps over the lazy dog", i) end ImGui.PopStyleVar() @@ -4519,10 +5046,11 @@ function ShowExampleAppLongText(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a window which gets auto-resized according to its content. local AutoResizeLines = 10 function ShowExampleAppAutoResize(p_open) local visible @@ -4530,17 +5058,23 @@ function ShowExampleAppAutoResize(p_open) if not visible then ImGui.End(); return p_open end ImGui.TextUnformatted("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop.") AutoResizeLines = ImGui.SliderInt("Number of lines", AutoResizeLines, 1, 20) - for i = 0, AutoResizeLines - 1 do ImGui.Text("%sThis is line %d", string.rep(" ", i * 4), i) end + for i = 0, AutoResizeLines - 1 do ImGui.Text("%sThis is line %d", string.rep(" ", i * 4), i) end -- Pad with space to extend size horizontally ImGui.End() return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize() ----------------------------------------------------------------- +------------------------------------------------------------------------------- -local CR = { auto_resize = false, window_padding = true, type = 6, display_lines = 10 } +-- Demonstrate creating a window with custom resize constraints. +-- Note that size constraints currently don't work on a docked window (when in 'docking' branch) +-- Options +local CR = { auto_resize = false, window_padding = true, type = 6, display_lines = 10 } -- type 6: Aspect Ratio function ShowExampleAppConstrainedResize(p_open) + -- Helper functions to demonstrate programmatic constraints + -- FIXME: This doesn't take account of decoration size (e.g. title bar), library should make this easier. + -- FIXME: None of the three demos works consistently when resizing from borders. local function AspectRatio(data) data.DesiredSize.y = math.floor(data.DesiredSize.x / data.UserData) end local function Square(data) local m = math.max(data.DesiredSize.x, data.DesiredSize.y); data.DesiredSize.x = m; data.DesiredSize.y = m end local function Step(data) @@ -4549,17 +5083,19 @@ function ShowExampleAppConstrainedResize(p_open) end local test_desc = { "Between 100x100 and 500x500", "At least 100x100", "Resize vertical + lock current width", "Resize horizontal + lock current height", "Width Between 400 and 500", "Height at least 400", "Custom: Aspect Ratio 16:9", "Custom: Always Square", "Custom: Fixed Steps (100)" } + -- Submit constraint local t = CR.type - if t == 0 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(500, 500)) end - if t == 1 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)) end - if t == 2 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)) end - if t == 3 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)) end - if t == 4 then ImGui.SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)) end - if t == 5 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, FLT_MAX)) end - if t == 6 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), AspectRatio, 16.0 / 9.0) end - if t == 7 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Square) end - if t == 8 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Step, 100.0) end + if t == 0 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(500, 500)) end -- Between 100x100 and 500x500 + if t == 1 then ImGui.SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)) end -- Width > 100, Height > 100 + if t == 2 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)) end -- Resize vertical + lock current width + if t == 3 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)) end -- Resize horizontal + lock current height + if t == 4 then ImGui.SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)) end -- Width Between and 400 and 500 + if t == 5 then ImGui.SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, FLT_MAX)) end -- Height at least 400 + if t == 6 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), AspectRatio, 16.0 / 9.0) end -- Aspect ratio + if t == 7 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Square) end -- Always Square + if t == 8 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), Step, 100.0) end -- Fixed Step + -- Submit window if not CR.window_padding then ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0.0, 0.0)) end local window_flags = CR.auto_resize and ImGuiWindowFlags.AlwaysAutoResize or 0 local window_open @@ -4567,6 +5103,7 @@ function ShowExampleAppConstrainedResize(p_open) if not CR.window_padding then ImGui.PopStyleVar() end if window_open then if ImGui.GetIO().KeyShift then + -- Display a dummy viewport (in your real app you would likely use ImageButton() to display a texture) local avail_size = ImGui.GetContentRegionAvail() local pos = ImGui.GetCursorScreenPos() ImGui.ColorButton("viewport", ImVec4(0.5, 0.2, 0.5, 1.0), bit32.bor(ImGuiColorEditFlags.NoTooltip, ImGuiColorEditFlags.NoDragDrop), avail_size) @@ -4591,10 +5128,12 @@ function ShowExampleAppConstrainedResize(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Simple overlay / ShowExampleAppSimpleOverlay() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a simple static window with no decoration +-- + a context-menu to choose which corner of the screen to use. local OverlayLocation = 0 function ShowExampleAppSimpleOverlay(p_open) local io = ImGui.GetIO() @@ -4603,7 +5142,7 @@ function ShowExampleAppSimpleOverlay(p_open) if OverlayLocation >= 0 then local PAD = 10.0 local viewport = ImGui.GetMainViewport() - local work_pos, work_size = viewport.WorkPos, viewport.WorkSize + local work_pos, work_size = viewport.WorkPos, viewport.WorkSize -- Use work area to avoid menu-bar/task-bar, if any! local right, bottom = OverlayLocation % 2 == 1, OverlayLocation >= 2 local window_pos = ImVec2(right and (work_pos.x + work_size.x - PAD) or (work_pos.x + PAD), bottom and (work_pos.y + work_size.y - PAD) or (work_pos.y + PAD)) local window_pos_pivot = ImVec2(right and 1.0 or 0.0, bottom and 1.0 or 0.0) @@ -4611,10 +5150,11 @@ function ShowExampleAppSimpleOverlay(p_open) ImGui.SetNextWindowViewport(viewport.ID) window_flags = bit32.bor(window_flags, W.NoMove) elseif OverlayLocation == -2 then + -- Center window ImGui.SetNextWindowPos(ImGui.GetMainViewport():GetCenter(), ImGuiCond.Always, ImVec2(0.5, 0.5)) window_flags = bit32.bor(window_flags, W.NoMove) end - ImGui.SetNextWindowBgAlpha(0.35) + ImGui.SetNextWindowBgAlpha(0.35) -- Transparent background local visible p_open, visible = ImGui.Begin("Example: Simple overlay", p_open, window_flags) if visible then @@ -4636,12 +5176,15 @@ function ShowExampleAppSimpleOverlay(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Fullscreen window / ShowExampleAppFullscreen() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Demonstrate creating a window covering the entire screen/viewport local FS = { use_work_area = true, flags = bit32.bor(ImGuiWindowFlags.NoDecoration, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoSavedSettings) } function ShowExampleAppFullscreen(p_open) + -- We demonstrate using the full viewport area or the work area (without menu-bars, task-bars etc.) + -- Based on your use case you may want one or the other. local viewport = ImGui.GetMainViewport() ImGui.SetNextWindowPos(FS.use_work_area and viewport.WorkPos or viewport.Pos) ImGui.SetNextWindowSize(FS.use_work_area and viewport.WorkSize or viewport.Size) @@ -4665,13 +5208,21 @@ function ShowExampleAppFullscreen(p_open) return p_open end ----------------------------------------------------------------- --- [SECTION] Example App: Manipulating window titles / ShowExampleAppWindowTitles() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles() +------------------------------------------------------------------------------- +-- Demonstrate the use of "##" and "###" in identifiers to manipulate ID generation. +-- This applies to all regular items as well. +-- Read FAQ section "How can I have multiple widgets with the same label?" for details. function ShowExampleAppWindowTitles(p_open) local viewport = ImGui.GetMainViewport() local base_pos = viewport.Pos + + -- By default, Windows are uniquely identified by their title. + -- You can use the "##" and "###" markers to manipulate the display/ID. + + -- Using "##" to display same title but have unique identifier. ImGui.SetNextWindowPos(ImVec2(base_pos.x + 100, base_pos.y + 100), ImGuiCond.FirstUseEver) ImGui.Begin("Same title as another window##1") ImGui.Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique.") @@ -4680,6 +5231,8 @@ function ShowExampleAppWindowTitles(p_open) ImGui.Begin("Same title as another window##2") ImGui.Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique.") ImGui.End() + + -- Using "###" to display a changing title but keep a static identifier "AnimatedTitle" local spin = "|/-\\" local k = math.floor(ImGui.GetTime() / 0.25) % 4 + 1 local buf = string.format("Animated title %s %d###AnimatedTitle", string.sub(spin, k, k), ImGui.GetFrameCount()) @@ -4690,9 +5243,14 @@ function ShowExampleAppWindowTitles(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering() ----------------------------------------------------------------- +------------------------------------------------------------------------------- + +-- See our Wiki guides: +-- - ImDrawList Vector Rendering Reference: https://github.com/ocornut/imgui/wiki/Draw-List +-- - Pixel Perfect Anti-aliased Rendering: https://github.com/ocornut/imgui/wiki/Pixel-Perfect-Rendering +-- - How Anti-aliased Polyline Rendering is Implemented: https://github.com/ocornut/imgui/wiki/Polyline-Rendering local CRS = { sz = 42.0, base_rounding = 8.0, base_thickness = 3.0, animate_rounding = false, animate_thickness = false, ngon_segments = 6, circle_override = false, circle_override_v = 12, curve_override = false, curve_override_v = 8, @@ -4706,6 +5264,9 @@ local function CustomRenderingPrimitives() ImGui.PushItemFlag(ImGuiItemFlags.LiveEditOnInput, true) local draw_list = ImGui.GetWindowDrawList() + -- Draw gradients + -- (note that those are currently exacerbating our sRGB/Linear issues) + -- Calling ImGui.GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well.. ImGui.Text("Gradients") local gradient_size = ImVec2(ImGui.CalcItemWidth(), ImGui.GetFrameHeight()) ImGui.InvisibleButton("##gradient1", gradient_size) @@ -4715,11 +5276,12 @@ local function CustomRenderingPrimitives() col_a, col_b = ImGui.GetColorU32(IM_COL32(0, 255, 0, 255), nil, true), ImGui.GetColorU32(IM_COL32(255, 0, 0, 255), nil, true) draw_list:AddRectFilledMultiColor(ImGui.GetItemRectMin(), ImGui.GetItemRectMax(), col_a, col_b, col_b, col_a) + -- Draw a bunch of primitives ImGui.Text("All primitives") s.sz = ImGui.DragFloat("Size", s.sz, 0.2, 0.2, 100.0, "%.0f") local t = ImGui.GetTime() local rounding_wave = 1.0 - math.abs((t % 3.0) * (2.0 / 3.0) - 1.0) - local rounding = s.animate_rounding and (math.floor(rounding_wave * s.base_rounding * 10.0) / 10.0) or s.base_rounding + local rounding = s.animate_rounding and (math.floor(rounding_wave * s.base_rounding * 10.0) / 10.0) or s.base_rounding -- Sub-integer rounding works but has discontinuities in small values, so best disable we s.base_rounding = ImGui.DragFloat("Rounding", s.base_rounding, 0.02, 0.0, 32.0, "%.1f"); ImGui.SameLine() _, s.animate_rounding = ImGui.Checkbox("Animate##rounding", s.animate_rounding); ImGui.SameLine() ImGui.Text("%.2f", rounding) @@ -4752,9 +5314,9 @@ local function CustomRenderingPrimitives() local half_sz = sz * 0.5 local circle_segments = s.circle_override and s.circle_override_v or 0 local curve_segments = s.curve_override and s.curve_override_v or 0 - local cp3 = { ImVec2(0.0, sz * 0.6), ImVec2(sz * 0.5, -sz * 0.4), ImVec2(sz, sz) } + local cp3 = { ImVec2(0.0, sz * 0.6), ImVec2(sz * 0.5, -sz * 0.4), ImVec2(sz, sz) } -- Control points for curves local cp4 = { ImVec2(0.0, 0.0), ImVec2(sz * 1.3, sz * 0.3), ImVec2(sz - sz * 1.3, sz - sz * 0.3), ImVec2(sz, sz) } - local concave_shape = { { 0.0, 0.0 }, { 0.3, 0.0 }, { 0.3, 0.7 }, { 0.7, 0.7 }, { 0.7, 0.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 0.0, 1.0 } } + local concave_shape = { { 0.0, 0.0 }, { 0.3, 0.0 }, { 0.3, 0.7 }, { 0.7, 0.7 }, { 0.7, 0.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 0.0, 1.0 } } -- |_| looking shape. Normalized. local zigzag_shape = { { 0.0, 0.0 }, { 0.9, 0.0 }, { 1.0, 0.1 }, { 1.0, 0.9 }, { 0.9, 1.0 }, { 0.3, 1.0 }, { 0.3, 0.4 }, { 0.9, 0.4 } } local rotating_square = {} for side = 0, 3 do @@ -4771,17 +5333,25 @@ local function CustomRenderingPrimitives() local draw_fill = (row == 2 or row == 3) local draw_strokes = (row == 0 or row == 1 or row == 3) if draw_fill then + -- FILLED SHAPES local col = ImGui.ColorConvertFloat4ToU32(s.colf_fill) - draw_list:AddNgonFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments); x = x + step - draw_list:AddCircleFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments); x = x + step - draw_list:AddEllipseFilled(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments); x = x + step - draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x = x + step - draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding); x = x + step - draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br); x = x + step - draw_list:AddTriangleFilled(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col); x = x + step - draw_list:AddTriangleFilled(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col); x = x + step - math.floor(sz * 0.6) + draw_list:AddNgonFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments); x = x + step -- N-gon + draw_list:AddCircleFilled(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments); x = x + step -- Circle + draw_list:AddEllipseFilled(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments); x = x + step -- Ellipse + draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x = x + step -- Square + draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding); x = x + step -- Square with all rounded corners + draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, corners_tl_br); x = x + step -- Square with two rounded corners + draw_list:AddTriangleFilled(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col); x = x + step -- Triangle + draw_list:AddTriangleFilled(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col); x = x + step - math.floor(sz * 0.6) -- Thin triangle + + -- Concave shape: U Shape(concave_shape, x, y); draw_list:PathFillConcave(col); x = x + step + + -- Concave shape: Zig-Zag with sharp angles Shape(zigzag_shape, x, y); draw_list:PathFillConcave(col); x = x + step + + -- Horizontal/Vertical lines + -- (here for consistency with the strokes section. AddRectFilled() is roughly close to AddLineH(), AddLineV() draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x = x + step draw_list:AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x = x + step - math.floor(half_sz) if not (draw_fill and draw_strokes) then @@ -4793,10 +5363,16 @@ local function CustomRenderingPrimitives() end end x = x + step - math.floor(half_sz) + + -- Rotating square for n = 1, 4 do draw_list:PathLineTo(ImVec2(x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y)) end draw_list:PathFillConvex(col); x = x + step + + -- Path draw_list:PathArcTo(ImVec2(x + half_sz, y + half_sz), half_sz, pi * -0.5, pi * 1.1) draw_list:PathFillConvex(col); x = x + step + + -- Quadratic Bezier Curve (3 control points) draw_list:PathLineTo(ImVec2(x + cp3[1].x, y + cp3[1].y)) draw_list:PathBezierQuadraticCurveTo(ImVec2(x + cp3[2].x, y + cp3[2].y), ImVec2(x + cp3[3].x, y + cp3[3].y), curve_segments) draw_list:PathFillConvex(col); x = x + step @@ -4807,18 +5383,26 @@ local function CustomRenderingPrimitives() end if draw_fill and draw_strokes then x = start_pos.x end if draw_strokes then + -- STROKES + -- First row uses a thickness of 1.0f, second row uses the configurable thickness local col = ImGui.ColorConvertFloat4ToU32(s.colf_stroke) local th = (row == 0) and 1.0 or thickness - draw_list:AddNgon(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments, th); x = x + step - draw_list:AddCircle(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments, th); x = x + step - draw_list:AddEllipse(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments, th); x = x + step - draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0, th); x = x + step - draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th); x = x + step - draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, corners_tl_br); x = x + step - draw_list:AddTriangle(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col, th); x = x + step - draw_list:AddTriangle(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col, th); x = x + step - math.floor(sz * 0.6) + draw_list:AddNgon(ImVec2(x + half_sz, y + half_sz), half_sz, col, s.ngon_segments, th); x = x + step -- N-gon + draw_list:AddCircle(ImVec2(x + half_sz, y + half_sz), half_sz, col, circle_segments, th); x = x + step -- Circle + draw_list:AddEllipse(ImVec2(x + half_sz, y + half_sz), ImVec2(half_sz, sz * 0.3), col, -0.3, circle_segments, th); x = x + step -- Ellipse + draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0, th); x = x + step -- Square + draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th); x = x + step -- Square with all rounded corners + draw_list:AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, rounding, th, corners_tl_br); x = x + step -- Square with two rounded corners + draw_list:AddTriangle(ImVec2(x + sz * 0.5, y), ImVec2(x + sz, y + sz), ImVec2(x, y + sz), col, th); x = x + step -- Triangle + draw_list:AddTriangle(ImVec2(x + sz * 0.2, y), ImVec2(x + sz * 0.4, y + sz), ImVec2(x, y + sz), col, th); x = x + step - math.floor(sz * 0.6) -- Thin triangle + + -- Concave shape: U Shape(concave_shape, x, y); draw_list:PathStroke(col, th, ImDrawFlags.Closed); x = x + step + + -- Concave shape: Zig-Zag with sharp angles Shape(zigzag_shape, x, y); draw_list:PathStroke(col, th, ImDrawFlags.Closed); x = x + step + + -- Horizontal/Vertical/Diagonal lines local off = math.floor(sz * 0.4) draw_list:AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th) draw_list:AddLine(ImVec2(x, y + off), ImVec2(x + sz, y + off), col, th); x = x + step @@ -4829,11 +5413,19 @@ local function CustomRenderingPrimitives() draw_list:AddLine(ImVec2(x, y + sz), ImVec2(x + half_sz, y), col, th) end x = x + step - math.floor(half_sz) + + -- Rotating square for n = 1, 4 do draw_list:PathLineTo(ImVec2(x + half_sz + rotating_square[n].x, y + half_sz + rotating_square[n].y)) end draw_list:PathStroke(col, th, ImDrawFlags.Closed); x = x + step + + -- Path draw_list:PathArcTo(ImVec2(x + half_sz, y + half_sz), half_sz, pi * -0.5, pi * 1.1) draw_list:PathStroke(col, th); x = x + step + + -- Quadratic Bezier Curve (3 control points) draw_list:AddBezierQuadratic(ImVec2(x + cp3[1].x, y + cp3[1].y), ImVec2(x + cp3[2].x, y + cp3[2].y), ImVec2(x + cp3[3].x, y + cp3[3].y), col, th, curve_segments); x = x + step + + -- Cubic Bezier Curve (4 control points) if not (draw_fill and draw_strokes) then draw_list:AddBezierCubic(ImVec2(x + cp4[1].x, y + cp4[1].y), ImVec2(x + cp4[2].x, y + cp4[2].y), ImVec2(x + cp4[3].x, y + cp4[3].y), ImVec2(x + cp4[4].x, y + cp4[4].y), col, th, curve_segments) x = x + step @@ -4853,22 +5445,40 @@ local function CustomRenderingCanvas() _, s.opt_enable_grid = ImGui.Checkbox("Enable grid", s.opt_enable_grid) _, s.opt_enable_context_menu = ImGui.Checkbox("Enable context menu", s.opt_enable_context_menu) ImGui.Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu.") - local canvas_p0 = ImGui.GetCursorScreenPos() - local canvas_sz = ImGui.GetContentRegionAvail() + + -- Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling. + -- Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls. + -- To use a child window instead we could use, e.g: + -- ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0, 0)) -- Disable padding + -- ImGui.PushStyleColor(ImGuiCol.ChildBg, IM_COL32(50, 50, 50, 255)) -- Set a background color + -- ImGui.BeginChild("canvas", ImVec2(0.0, 0.0), ImGuiChildFlags.Borders, ImGuiWindowFlags.NoMove) + -- ImGui.PopStyleColor() + -- ImGui.PopStyleVar() + -- [...] + -- ImGui.EndChild() + + -- Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive() + local canvas_p0 = ImGui.GetCursorScreenPos() -- ImDrawList API uses screen coordinates! + local canvas_sz = ImGui.GetContentRegionAvail() -- Resize canvas to what's available if canvas_sz.x < 50.0 then canvas_sz.x = 50.0 end if canvas_sz.y < 50.0 then canvas_sz.y = 50.0 end local canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y) + + -- Draw border and background color local io = ImGui.GetIO() local draw_list = ImGui.GetWindowDrawList() draw_list:AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255)) draw_list:AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255)) + -- This will catch our interactions ImGui.InvisibleButton("canvas", canvas_sz, bit32.bor(ImGuiButtonFlags.MouseButtonLeft, ImGuiButtonFlags.MouseButtonRight)) - local is_hovered = ImGui.IsItemHovered() - local is_active = ImGui.IsItemActive() - local origin = ImVec2(canvas_p0.x + s.scrolling.x, canvas_p0.y + s.scrolling.y) + local is_hovered = ImGui.IsItemHovered() -- Hovered + local is_active = ImGui.IsItemActive() -- Held + local origin = ImVec2(canvas_p0.x + s.scrolling.x, canvas_p0.y + s.scrolling.y) -- Lock scrolled origin local mouse_pos_in_canvas = ImVec2(io.MousePos.x - origin.x, io.MousePos.y - origin.y) local points = s.points + + -- Add first and second point if is_hovered and not s.adding_line and ImGui.IsMouseClicked(ImGuiMouseButton.Left) then points[#points + 1] = ImVec2(mouse_pos_in_canvas.x, mouse_pos_in_canvas.y) points[#points + 1] = ImVec2(mouse_pos_in_canvas.x, mouse_pos_in_canvas.y) @@ -4878,11 +5488,16 @@ local function CustomRenderingCanvas() points[#points] = ImVec2(mouse_pos_in_canvas.x, mouse_pos_in_canvas.y) if not ImGui.IsMouseDown(ImGuiMouseButton.Left) then s.adding_line = false end end + + -- Pan (we use a zero mouse threshold when there's no context menu) + -- You may decide to make that threshold dynamic based on whether the mouse is hovering something etc. local mouse_threshold_for_pan = s.opt_enable_context_menu and -1.0 or 0.0 if is_active and ImGui.IsMouseDragging(ImGuiMouseButton.Right, mouse_threshold_for_pan) then s.scrolling.x = s.scrolling.x + io.MouseDelta.x s.scrolling.y = s.scrolling.y + io.MouseDelta.y end + + -- Context menu (under default mouse threshold) local drag_delta = ImGui.GetMouseDragDelta(ImGuiMouseButton.Right) if s.opt_enable_context_menu and drag_delta.x == 0.0 and drag_delta.y == 0.0 then ImGui.OpenPopupOnItemClick("context", ImGuiPopupFlags.MouseButtonRight) @@ -4894,6 +5509,8 @@ local function CustomRenderingCanvas() if ImGui.MenuItem("Remove all", nil, false, #points > 0) then table.clear(points) end ImGui.EndPopup() end + + -- Draw grid + all lines in the canvas draw_list:PushClipRect(canvas_p0, canvas_p1, true) if s.opt_enable_grid then local GRID_STEP = 64.0 @@ -4908,6 +5525,7 @@ local function CustomRenderingCanvas() draw_list:PopClipRect() end +-- Demonstrate using the low-level ImDrawList to draw custom shapes. function ShowExampleAppCustomRendering(p_open) local visible p_open, visible = ImGui.Begin("Example: Custom rendering", p_open) @@ -4927,23 +5545,33 @@ function ShowExampleAppCustomRendering(p_open) if s.draw_fg then ImGui.GetForegroundDrawList():AddCircle(window_center, window_size.y * 0.6, IM_COL32(0, 255, 0, 200), 0, 10) end ImGui.EndTabItem() end + + -- Demonstrate out-of-order rendering via channels splitting + -- We use functions in ImDrawList as each draw list contains a convenience splitter, + -- but you can also instantiate your own ImDrawListSplitter if you need to nest them. if ImGui.BeginTabItem("Draw Channels") then local draw_list = ImGui.GetWindowDrawList() ImGui.Text("Blue shape is drawn first: appears in back") ImGui.Text("Red shape is drawn after: appears in front") local p0 = ImGui.GetCursorScreenPos() - draw_list:AddRectFilled(ImVec2(p0.x, p0.y), ImVec2(p0.x + 50, p0.y + 50), IM_COL32(0, 0, 255, 255)) - draw_list:AddRectFilled(ImVec2(p0.x + 25, p0.y + 25), ImVec2(p0.x + 75, p0.y + 75), IM_COL32(255, 0, 0, 255)) + draw_list:AddRectFilled(ImVec2(p0.x, p0.y), ImVec2(p0.x + 50, p0.y + 50), IM_COL32(0, 0, 255, 255)) -- Blue + draw_list:AddRectFilled(ImVec2(p0.x + 25, p0.y + 25), ImVec2(p0.x + 75, p0.y + 75), IM_COL32(255, 0, 0, 255)) -- Red ImGui.Dummy(ImVec2(75, 75)) ImGui.Separator() ImGui.Text("Blue shape is drawn first, into channel 1: appears in front") ImGui.Text("Red shape is drawn after, into channel 0: appears in back") local p1 = ImGui.GetCursorScreenPos() + + -- Create 2 channels and draw a Blue shape THEN a Red shape. + -- You can create any number of channels. Tables API use 1 channel per column in order to better batch draw calls. draw_list:ChannelsSplit(2) draw_list:ChannelsSetCurrent(1) - draw_list:AddRectFilled(ImVec2(p1.x, p1.y), ImVec2(p1.x + 50, p1.y + 50), IM_COL32(0, 0, 255, 255)) + draw_list:AddRectFilled(ImVec2(p1.x, p1.y), ImVec2(p1.x + 50, p1.y + 50), IM_COL32(0, 0, 255, 255)) -- Blue draw_list:ChannelsSetCurrent(0) - draw_list:AddRectFilled(ImVec2(p1.x + 25, p1.y + 25), ImVec2(p1.x + 75, p1.y + 75), IM_COL32(255, 0, 0, 255)) + draw_list:AddRectFilled(ImVec2(p1.x + 25, p1.y + 25), ImVec2(p1.x + 75, p1.y + 75), IM_COL32(255, 0, 0, 255)) -- Red + + -- Flatten/reorder channels. Red shape is in channel 0 and it appears below the Blue shape in channel 1. + -- This works by copying draw indices only (vertices are not copied). draw_list:ChannelsMerge() ImGui.Dummy(ImVec2(75, 75)) ImGui.Text("After reordering, contents of channel 0 appears below channel 1.") @@ -4955,17 +5583,35 @@ function ShowExampleAppCustomRendering(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Docking, DockSpace / ShowExampleAppDockSpace() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- KeepWindowPadding: Keep WindowPadding to help understand that DockSpace() is a widget inside the window. local DSA = { IsFullscreen = true, KeepWindowPadding = false, DockSpaceFlags = 0, opt_demo_mode = 0, opt_demo_mode_changed = false } +-- THIS IS A DEMO FOR ADVANCED USAGE OF DockSpace(). +-- MOST REGULAR APPLICATIONS WANTING TO ALLOW DOCKING WINDOWS ON THE EDGE OF YOUR SCREEN CAN SIMPLY USE: +-- ImGui.NewFrame() + ImGui.DockSpaceOverViewport() -- Create a dockspace in main viewport +-- OR: +-- ImGui.NewFrame() + ImGui.DockSpaceOverViewport(0, nil, ImGuiDockNodeFlags.PassthruCentralNode) -- Create a dockspace in main viewport, where central node is transparent. +-- Demonstrate using DockSpace() to create an explicit docking node within an existing window, with various options. +-- Read https://github.com/ocornut/imgui/wiki/Docking for details. +-- The reasons we do not use DockSpaceOverViewport() in this demo is because: +-- - (1) we allow the host window to be floating/moveable instead of filling the viewport (when args.IsFullscreen == false) +-- which is mostly to showcase the idea that DockSpace() may be submitted anywhere. +-- Also see 'Demo->Examples->Documents' for a less abstract version of this. +-- - (2) we allow the host window to have padding (when args.UsePadding == true) +-- - (3) we expose variety of other flags. local function ShowExampleAppDockSpaceAdvanced(args, p_open) local dockspace_flags = args.DockSpaceFlags + + -- We are using the ImGuiWindowFlags_NoDocking flag to make the parent window not dockable into, + -- because it would be confusing to have two docking targets within each others. local W = ImGuiWindowFlags local window_flags = W.NoDocking if args.IsFullscreen then + -- Fullscreen dockspace: practically the same as calling DockSpaceOverViewport() local viewport = ImGui.GetMainViewport() ImGui.SetNextWindowPos(viewport.WorkPos) ImGui.SetNextWindowSize(viewport.WorkSize) @@ -4974,12 +5620,24 @@ local function ShowExampleAppDockSpaceAdvanced(args, p_open) ImGui.PushStyleVar(ImGuiStyleVar.WindowBorderSize, 0.0) window_flags = bit32.bor(window_flags, W.NoTitleBar, W.NoCollapse, W.NoResize, W.NoMove, W.NoBringToFrontOnFocus, W.NoNavFocus, W.NoBackground) else + -- Floating dockspace dockspace_flags = bit32.band(dockspace_flags, bit32.bnot(ImGuiDockNodeFlags.PassthruCentralNode)) end + + -- Important: note that we proceed even if Begin() returns false (aka window is collapsed). + -- This is because we want to keep our DockSpace() active. If a DockSpace() is inactive, + -- all active windows docked into it will lose their parent and become undocked. + -- We cannot preserve the docking relationship between an active window and an inactive docking, otherwise + -- any change of dockspace/settings would lead to windows being stuck in limbo and never being visible. if not args.KeepWindowPadding then ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, ImVec2(0.0, 0.0)) end p_open = ImGui.Begin("Window with a DockSpace", p_open, window_flags) if not args.KeepWindowPadding then ImGui.PopStyleVar() end + if args.IsFullscreen then ImGui.PopStyleVar(2) end + + -- Submit the DockSpace widget inside our window + -- - Note that the id here is different from the one used by DockSpaceOverViewport(), so docking state won't get transfered between "Basic" and "Advanced" demos. + -- - If we made the ShowExampleAppDockSpaceBasic() calculate its own ID and pass it to DockSpaceOverViewport() the ID could easily match. local dockspace_id = ImGui.GetID("MyDockSpace") ImGui.DockSpace(dockspace_id, ImVec2(0.0, 0.0), dockspace_flags) ImGui.End() @@ -4989,10 +5647,20 @@ end function ShowExampleAppDockSpace(p_open) local args = DSA if args.opt_demo_mode == 0 then + -- Basic version which you can use in many apps: + -- e.g: + -- ImGui.DockSpaceOverViewport() + -- or: + -- ImGui.DockSpaceOverViewport(0, nil, ImGuiDockNodeFlags.PassthruCentralNode) -- Central node will be transparent + -- or: + -- local viewport = ImGui.GetMainViewport() + -- ImGui.DockSpaceOverViewport(0, viewport, ImGuiDockNodeFlags.None) ImGui.DockSpaceOverViewport(0, nil, args.DockSpaceFlags) else p_open = ShowExampleAppDockSpaceAdvanced(args, p_open) end + + -- Refocus our window to minimize perceived loss of focus when changing mode (caused by the fact that each use a different window, which would not happen in a real app) if args.opt_demo_mode_changed then ImGui.SetNextWindowFocus() end p_open = ImGui.Begin("Examples: Dockspace", p_open, ImGuiWindowFlags.MenuBar) local c1, c2 @@ -5004,7 +5672,7 @@ function ShowExampleAppDockSpace(p_open) if bit32.band(ImGui.GetIO().ConfigFlags, ImGuiConfigFlags.DockingEnable) == 0 then ShowDockingDisabledMessage() elseif args.opt_demo_mode == 0 then - args.DockSpaceFlags = bit32.band(args.DockSpaceFlags, D.PassthruCentralNode) + args.DockSpaceFlags = bit32.band(args.DockSpaceFlags, D.PassthruCentralNode) -- Allowed flags _, args.DockSpaceFlags = ImGui.CheckboxFlags("Flag: PassthruCentralNode", args.DockSpaceFlags, D.PassthruCentralNode) else _, args.IsFullscreen = ImGui.Checkbox("Fullscreen", args.IsFullscreen) @@ -5018,6 +5686,8 @@ function ShowExampleAppDockSpace(p_open) if D[n] then _, args.DockSpaceFlags = ImGui.CheckboxFlags("Flag: " .. n, args.DockSpaceFlags, D[n]) end end end + + -- Show demo options and help if ImGui.BeginMenuBar() then if ImGui.BeginMenu("Help") then ImGui.TextUnformatted("This demonstrates the use of ImGui::DockSpace() which allows you to manually\ncreate a docking node _within_ another window.\nThe \"Basic\" version uses the ImGui::DockSpaceOverViewport() helper. Most applications can probably use this.") @@ -5034,10 +5704,17 @@ function ShowExampleAppDockSpace(p_open) return p_open end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Documents Handling / ShowExampleAppDocuments() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- Simplified structure to mimic a Document model +-- NameBuf: Document title +-- UID: Unique ID (necessary as we can change title) +-- Open: Set when open (we keep an array of all available documents to simplify demo code!) +-- OpenPrev: Copy of Open from last update. +-- Dirty: Set when the document has been modified +-- Color: An arbitrary variable associated to the document local function MyDocument(uid, name, open, color) if open == nil then open = true end local d = { UID = uid, NameBuf = Buf(name, 32), Open = open, OpenPrev = open, Dirty = false, Color = color or ImVec4(1.0, 1.0, 1.0, 1.0) } @@ -5063,13 +5740,16 @@ local function DocsInit() for _, d in ipairs(self.CloseQueue) do if d == doc then return end end self.CloseQueue[#self.CloseQueue + 1] = doc end + -- As we allow to change document name, we append a never-changing document ID so tabs are stable function app:GetTabName(doc) return string.format("%s###doc%d", doc:Name(), doc.UID) end + -- Display placeholder contents for the Document function app:DisplayDocContents(doc) ImGui.PushID("doc" .. doc.UID) ImGui.Text("Document \"%s\"", doc:Name()) ImGui.PushStyleColor(ImGuiCol.Text, doc.Color) ImGui.TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.") ImGui.PopStyleColor() + ImGui.SetNextItemShortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.R), ImGuiInputFlags.Tooltip) if ImGui.Button("Rename..") then self.RenamingDoc = doc; self.RenamingStarted = true end ImGui.SameLine() @@ -5081,9 +5761,10 @@ local function DocsInit() ImGui.SameLine() ImGui.SetNextItemShortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.W), ImGuiInputFlags.Tooltip) if ImGui.Button("Close") then self:QueueClose(doc) end - ImGui.ColorEdit3("color", doc.Color) + ImGui.ColorEdit3("color", doc.Color) -- Useful to test drag and drop and hold-dragged-to-open-tab behavior. ImGui.PopID() end + -- Display context menu for the Document function app:DisplayDocContextMenu(doc) if not ImGui.BeginPopupContextItem() then return end if ImGui.MenuItem("Save " .. doc:Name(), "Ctrl+S", false, doc.Open) then doc:DoSave() end @@ -5091,6 +5772,14 @@ local function DocsInit() if ImGui.MenuItem("Close", "Ctrl+W", false, doc.Open) then self:QueueClose(doc) end ImGui.EndPopup() end + -- [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface. + -- If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo, + -- as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for + -- the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has + -- disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively + -- give the impression of a flicker for one frame. + -- We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch. + -- Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags.Reorderable flag. function app:NotifyOfDocumentsClosedElsewhere() for _, doc in ipairs(self.Documents) do if not doc.Open and doc.OpenPrev then ImGui.SetTabItemClosed(doc:Name()) end @@ -5103,7 +5792,18 @@ end function ShowExampleAppDocuments(p_open) Docs = Docs or DocsInit() local app = Docs + -- Options + -- Target_Tab: Create documents as local tab into a local tab bar + -- Target_DockSpaceAndWindow: Create documents as regular windows, and create an embedded dockspace local Target_Tab, Target_DockSpaceAndWindow = 1, 2 + + -- When (opt_target == Target_DockSpaceAndWindow) there is the possibily that one of our child Document window (e.g. "Eggplant") + -- that we emit gets docked into the same spot as the parent window ("Example: Documents"). + -- This would create a problematic feedback loop because selecting the "Eggplant" tab would make the "Example: Documents" tab + -- not visible, which in turn would stop submitting the "Eggplant" window. + -- We avoid this problem by submitting our documents window even if our parent window is not currently visible. + -- Another solution may be to make the "Example: Documents" window use the ImGuiWindowFlags.NoDocking. + local window_contents_visible p_open, window_contents_visible = ImGui.Begin("Example: Documents", p_open, ImGuiWindowFlags.MenuBar) if not window_contents_visible and app.opt_target ~= Target_DockSpaceAndWindow then @@ -5111,6 +5811,7 @@ function ShowExampleAppDocuments(p_open) return p_open end + -- Menu if ImGui.BeginMenuBar() then if ImGui.BeginMenu("File") then local open_count = 0 @@ -5130,6 +5831,7 @@ function ShowExampleAppDocuments(p_open) ImGui.EndMenuBar() end + -- [Debug] List documents with one checkbox for each for doc_n, doc in ipairs(app.Documents) do if doc_n > 1 then ImGui.SameLine() end ImGui.PushID("doc" .. doc.UID) @@ -5146,15 +5848,31 @@ function ShowExampleAppDocuments(p_open) if app.opt_target == Target_DockSpaceAndWindow then ImGui.SameLine(); redock_all = ImGui.Button("Redock all") end ImGui.Separator() + -- About the ImGuiWindowFlags.UnsavedDocument / ImGuiTabItemFlags.UnsavedDocument flags. + -- They have multiple effects: + -- - Display a dot next to the title. + -- - Tab is selected when clicking the X close button. + -- - Closure is not assumed (will wait for user to stop submitting the tab). + -- Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + -- We need to assume closure by default otherwise waiting for "lack of submission" on the next frame would leave an empty + -- hole for one-frame, both in the tab-bar and in tab-contents when closing a tab/window. + -- The rarely used SetTabItemClosed() function is a way to notify of programmatic closure to avoid the one-frame hole. + + -- Tabs if app.opt_target == Target_Tab then local tab_bar_flags = bit32.bor(app.opt_fitting_flags, app.opt_reorderable and ImGuiTabBarFlags.Reorderable or 0, ImGuiTabBarFlags.DrawSelectedOverline) if ImGui.BeginTabBar("##tabs", tab_bar_flags) then if app.opt_reorderable then app:NotifyOfDocumentsClosedElsewhere() end + + -- Submit Tabs for _, doc in ipairs(app.Documents) do if doc.Open then + -- As we allow to change document name, we append a never-changing document id so tabs are stable local tab_flags = doc.Dirty and ImGuiTabItemFlags.UnsavedDocument or 0 local visible visible, doc.Open = ImGui.BeginTabItem(app:GetTabName(doc), doc.Open, tab_flags) + + -- Cancel attempt to close when unsaved add to save queue so we can display a popup. if not doc.Open and doc.Dirty then doc.Open = true app:QueueClose(doc) @@ -5171,14 +5889,20 @@ function ShowExampleAppDocuments(p_open) elseif app.opt_target == Target_DockSpaceAndWindow then if bit32.band(ImGui.GetIO().ConfigFlags, ImGuiConfigFlags.DockingEnable) ~= 0 then app:NotifyOfDocumentsClosedElsewhere() + + -- Create a DockSpace node where any window can be docked local dockspace_id = ImGui.GetID("MyDockSpace") ImGui.DockSpace(dockspace_id) + + -- Create Windows for _, doc in ipairs(app.Documents) do if doc.Open then ImGui.SetNextWindowDockID(dockspace_id, redock_all and ImGuiCond.Always or ImGuiCond.FirstUseEver) local window_flags = doc.Dirty and ImGuiWindowFlags.UnsavedDocument or 0 local visible doc.Open, visible = ImGui.Begin(doc:Name(), doc.Open, window_flags) + + -- Cancel attempt to close when unsaved add to save queue so we can display a popup. if not doc.Open and doc.Dirty then doc.Open = true app:QueueClose(doc) @@ -5193,11 +5917,13 @@ function ShowExampleAppDocuments(p_open) end end + -- Early out other contents if not window_contents_visible then ImGui.End() return p_open end + -- Display renaming UI if app.RenamingDoc ~= nil then if app.RenamingStarted then ImGui.OpenPopup("Rename") end if ImGui.BeginPopup("Rename") then @@ -5214,10 +5940,12 @@ function ShowExampleAppDocuments(p_open) app.RenamingStarted = false end + -- Display closing confirmation UI if #app.CloseQueue > 0 then local close_queue_unsaved_documents = 0 for _, doc in ipairs(app.CloseQueue) do if doc.Dirty then close_queue_unsaved_documents = close_queue_unsaved_documents + 1 end end if close_queue_unsaved_documents == 0 then + -- Close documents when all are unsaved for _, doc in ipairs(app.CloseQueue) do doc:DoForceClose() end app.CloseQueue = {} else @@ -5270,6 +5998,10 @@ local ExampleNames = { "Bitter Gourd", "Bok Choy", "Broccoli", "Brussels Sprouts", "Burdock Root", "Cabbage", "Calabash", "Capers", "Carrot", "Cassava", "Cauliflower", "Celery", "Celery Root", "Celcuce", "Chayote", "Chinese Broccoli", "Corn", "Cucumber" } +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsBasic() +------------------------------------------------------------------------------- + S.basic = { clicked = 0, check = true, e = 0, counter = 0, str0 = Buf("Hello, world!", 128), str1 = Buf("", 128), i0 = 123, f0 = 0.001, d0 = 999999.00000001, f1 = 1.e10, vec4a = { 0.10, 0.20, 0.30, 0.44 }, di1 = 50, di2 = 42, di3 = 128, df1 = 1.0, df2 = 0.0067, si1 = 0, sf1 = 0.123, sf2 = 0.0, angle = 0.0, elem = 0, @@ -5287,6 +6019,8 @@ function DemoWindowWidgetsBasic() _, s.e = ImGui.RadioButton("radio c", s.e, 2) ImGui.AlignTextToFramePadding() ImGui.TextLinkOpenURL("Hyperlink", "https://github.com/ocornut/imgui/wiki/Error-Handling") + + -- Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. for i = 0, 6 do if i > 0 then ImGui.SameLine() end ImGui.PushID(i) @@ -5297,9 +6031,15 @@ function DemoWindowWidgetsBasic() ImGui.PopStyleColor(3) ImGui.PopID() end + + -- Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements + -- (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!) + -- See 'Demo->Layout->Text Baseline Alignment' for details. ImGui.AlignTextToFramePadding() ImGui.Text("Hold to repeat:") ImGui.SameLine() + + -- Arrow buttons with Repeater local spacing = ImGui.GetStyle().ItemInnerSpacing.x ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true) if ImGui.ArrowButton("##left", ImGuiDir.Left) then s.counter = s.counter - 1 end @@ -5330,6 +6070,7 @@ function DemoWindowWidgetsBasic() s.di3 = ImGui.DragInt("drag int wrap 100..200", s.di3, 1, 100, 200, "%d", ImGuiSliderFlags.WrapAround) s.df1 = ImGui.DragFloat("drag float", s.df1, 0.005) s.df2 = ImGui.DragFloat("drag small float", s.df2, 0.0001, 0.0, 0.0, "%.06f ns") + -- ImGui.DragFloat("drag wrap -1..1", f3, 0.005, -1.0, 1.0, nil, ImGuiSliderFlags.WrapAround) ImGui.SeparatorText("Sliders") s.si1 = ImGui.SliderInt("slider int", s.si1, -1, 3) @@ -5337,23 +6078,38 @@ function DemoWindowWidgetsBasic() s.sf1 = ImGui.SliderFloat("slider float", s.sf1, 0.0, 1.0, "ratio = %.3f") s.sf2 = ImGui.SliderFloat("slider float (log)", s.sf2, -10.0, 10.0, "%.4f", ImGuiSliderFlags.Logarithmic) s.angle = ImGui.SliderAngle("slider angle", s.angle) + + -- Using the format string to display a name instead of an integer. + -- Here we completely omit '%d' from the format string, so it'll only display a name. + -- This technique can also be used with DragInt(). local elems_names = { "Fire", "Earth", "Air", "Water" } local elem_name = elems_names[s.elem + 1] or "Unknown" - s.elem = ImGui.SliderInt("slider enum", s.elem, 0, 3, elem_name) + s.elem = ImGui.SliderInt("slider enum", s.elem, 0, 3, elem_name) -- Use ImGuiSliderFlags.NoInput flag to disable Ctrl+Click here. ImGui.SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer.") ImGui.SeparatorText("Selectors/Pickers") ImGui.ColorEdit3("color 1", s.col1) ImGui.SameLine(); HelpMarker("Click on the color square to open a color picker.\nClick and hold to use drag and drop.\nRight-Click on the color square to show options.\nCtrl+Click on individual component to input value.\n") ImGui.ColorEdit4("color 2", s.col2) + + -- Using the _simplified_ one-liner Combo() api here + -- See "Combo" section for examples of how to use the more flexible BeginCombo()/EndCombo() api. s.combo = ImGui.Combo("combo", s.combo, { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" }) ImGui.SameLine(); HelpMarker("Using the simplified one-liner Combo API here.") + + -- Using the _simplified_ one-liner ListBox() api here + -- See "List boxes" section for examples of how to use the more flexible BeginListBox()/EndListBox() api. s.listbox = ImGui.ListBox("listbox", s.listbox, { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }, 9, 4) ImGui.SameLine(); HelpMarker("Using the simplified one-liner ListBox API here.") ImGui.TreePop() end S.chdr = { closable_group = true } + +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsBullets() +------------------------------------------------------------------------------- + function DemoWindowWidgetsBullets() if not ImGui.TreeNode("Bullets") then return end ImGui.BulletText("Bullet point 1") @@ -5364,6 +6120,10 @@ function DemoWindowWidgetsBullets() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsCollapsingHeaders() +------------------------------------------------------------------------------- + function DemoWindowWidgetsCollapsingHeaders() if not ImGui.TreeNode("Collapsing Headers") then return end local s = S.chdr @@ -5378,9 +6138,16 @@ function DemoWindowWidgetsCollapsingHeaders() ImGui.Text("IsItemHovered: %d", ImGui.IsItemHovered() and 1 or 0) for i = 0, 4 do ImGui.Text("More content %d", i) end end + -- if ImGui.CollapsingHeader("Header with a bullet", ImGuiTreeNodeFlags.Bullet) then + -- ImGui.Text("IsItemHovered: %d", ImGui.IsItemHovered()) + -- end ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsColorAndPickers() +------------------------------------------------------------------------------- + IMGUI_PAYLOAD_TYPE_COLOR_3F = IMGUI_PAYLOAD_TYPE_COLOR_3F or "_COL3F" IMGUI_PAYLOAD_TYPE_COLOR_4F = IMGUI_PAYLOAD_TYPE_COLOR_4F or "_COL4F" @@ -5418,9 +6185,11 @@ function DemoWindowWidgetsColorAndPickers() ImGui.ColorEdit4("MyColor##3", color, bit32.bor(CE.NoInputs, CE.NoLabel, base_flags)) ImGui.Text("Color button with Custom Picker Popup:") + + -- Generate a default palette. The palette will persist and can be edited. if s.palette == nil then s.palette = {} - for n = 0, 31 do s.palette[n] = HSV(n / 31.0, 0.8, 0.8, 1.0) end + for n = 0, 31 do s.palette[n] = HSV(n / 31.0, 0.8, 0.8, 1.0) end -- Alpha = 1.0 end local open_popup = ImGui.ColorButton("MyColor##3b", color, base_flags) ImGui.SameLine(0, ImGui.GetStyle().ItemInnerSpacing.x) @@ -5434,7 +6203,7 @@ function DemoWindowWidgetsColorAndPickers() ImGui.Separator() ImGui.ColorPicker4("##picker", color, bit32.bor(base_flags, CE.NoSidePreview, CE.NoSmallPreview)) ImGui.SameLine() - ImGui.BeginGroup() + ImGui.BeginGroup() -- Lock X position ImGui.Text("Current") ImGui.ColorButton("##current", color, bit32.bor(CE.NoPicker, CE.AlphaPreviewHalf), ImVec2(60, 40)) ImGui.Text("Previous") @@ -5450,6 +6219,9 @@ function DemoWindowWidgetsColorAndPickers() if ImGui.ColorButton("##palette", pal, bit32.bor(CE.NoAlpha, CE.NoPicker, CE.NoTooltip), ImVec2(20, 20)) then color.x = pal.x; color.y = pal.y; color.z = pal.z -- Preserve alpha! end + + -- Allow user to drop colors into each palette entry. Note that ColorButton() is already a + -- drag source by default, unless specifying the ImGuiColorEditFlags.NoDragDrop flag. if ImGui.BeginDragDropTarget() then local payload = ImGui.AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F) if payload and payload.Data then pal.x, pal.y, pal.z = payload.Data[1], payload.Data[2], payload.Data[3] end @@ -5488,8 +6260,8 @@ function DemoWindowWidgetsColorAndPickers() local flags = bit32.bor(base_flags, s.picker_flags) if s.picker_mode == 1 then flags = bit32.bor(flags, CE.PickerHueBar) end if s.picker_mode == 2 then flags = bit32.bor(flags, CE.PickerHueWheel) end - if s.display_mode == 1 then flags = bit32.bor(flags, CE.NoInputs) end - if s.display_mode == 2 then flags = bit32.bor(flags, CE.DisplayRGB) end + if s.display_mode == 1 then flags = bit32.bor(flags, CE.NoInputs) end -- Disable all RGB/HSV/Hex displays + if s.display_mode == 2 then flags = bit32.bor(flags, CE.DisplayRGB) end -- Override display mode if s.display_mode == 3 then flags = bit32.bor(flags, CE.DisplayHSV) end if s.display_mode == 4 then flags = bit32.bor(flags, CE.DisplayHex) end ImGui.ColorPicker4("MyColor##4", color, flags, s.ref_color and s.ref_color_v or nil) @@ -5503,6 +6275,8 @@ function DemoWindowWidgetsColorAndPickers() ImGui.GetIO().ConfigColorEditFlags = bit32.bor(CE.Float, CE.HDR, CE.PickerHueWheel, CE.DisplayRGB, CE.InputRGB) end + -- Always display a small version of both types of pickers + -- (that's in order to make it more visible in the demo to people who are skimming quickly through it) ImGui.Text("Both types:") local w = (ImGui.GetContentRegionAvail().x - ImGui.GetStyle().ItemSpacing.y) * 0.40 ImGui.SetNextItemWidth(w) @@ -5512,6 +6286,8 @@ function DemoWindowWidgetsColorAndPickers() ImGui.ColorPicker3("##MyColor##6", color, bit32.bor(CE.PickerHueWheel, CE.NoSidePreview, CE.NoInputs, CE.NoAlpha)) ImGui.PopID() + -- HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0) + -- (s.hsv is stored as HSV!) ImGui.Spacing() ImGui.Text("HSV encoded colors") ImGui.SameLine(); HelpMarker("By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV.") @@ -5522,36 +6298,53 @@ function DemoWindowWidgetsColorAndPickers() ImGui.TreePop() end -S.combo = { flags = 0, sel = 0, filter = nil, c2 = 0, c3 = -1, c4 = 0 } +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsComboBoxes() +------------------------------------------------------------------------------- + +S.combo = { flags = 0, sel = 0, filter = nil, c2 = 0, c3 = -1, c4 = 0 } -- sel: Here we store our selection data as an index. function DemoWindowWidgetsComboBoxes() if not ImGui.TreeNode("Combo") then return end local s = S.combo local CF = ImGuiComboFlags local p + -- Combo Boxes are also called "Dropdown" in other systems + -- Expose flags as checkbox for the demo _, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", s.flags, CF.PopupAlignLeft) ImGui.SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo") p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_NoArrowButton", s.flags, CF.NoArrowButton) - if p then s.flags = bit32.band(s.flags, bit32.bnot(CF.NoPreview)) end + if p then s.flags = bit32.band(s.flags, bit32.bnot(CF.NoPreview)) end -- Clear incompatible flags p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_NoPreview", s.flags, CF.NoPreview) - if p then s.flags = bit32.band(s.flags, bit32.bnot(bit32.bor(CF.NoArrowButton, CF.WidthFitPreview))) end + if p then s.flags = bit32.band(s.flags, bit32.bnot(bit32.bor(CF.NoArrowButton, CF.WidthFitPreview))) end -- Clear incompatible flags p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_WidthFitPreview", s.flags, CF.WidthFitPreview) if p then s.flags = bit32.band(s.flags, bit32.bnot(CF.NoPreview)) end + + -- Override default popup height for _, h in ipairs({ "HeightSmall", "HeightRegular", "HeightLargest" }) do p, s.flags = ImGui.CheckboxFlags("ImGuiComboFlags_" .. h, s.flags, CF[h]) if p then s.flags = bit32.band(s.flags, bit32.bnot(bit32.band(CF.HeightMask_, bit32.bnot(CF[h])))) end end + -- Using the generic BeginCombo() API, you have full control over how to display the combo contents. + -- (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + -- stored in the object itself, etc.) local items = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" } + + -- Pass in the preview value visible before opening the combo (it could technically be different contents or not pulled from items[]) local combo_preview_value = items[s.sel + 1] if ImGui.BeginCombo("combo 1", combo_preview_value, s.flags) then for n = 0, #items - 1 do local is_selected = (s.sel == n) if ImGui.Selectable(items[n + 1], is_selected) then s.sel = n end + + -- Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if is_selected then ImGui.SetItemDefaultFocus() end end ImGui.EndCombo() end + -- Show case embedding a filter using a simple trick: displaying the filter inside combo contents. + -- See https://github.com/ocornut/imgui/issues/718 for advanced/esoteric alternatives. if ImGui.BeginCombo("combo 2 (w/ filter)", combo_preview_value, s.flags) then s.filter = s.filter or ImGuiTextFilter() if ImGui.IsWindowAppearing() then @@ -5573,19 +6366,46 @@ function DemoWindowWidgetsComboBoxes() ImGui.Spacing() ImGui.SeparatorText("One-liner variants") HelpMarker("The Combo() function is not greatly useful apart from cases were you want to embed all options in a single strings.\nFlags above don't apply to this section.") + + -- Simplified one-liner Combo() API, using values packed in a single constant string + -- This is a convenience for when the selection set is small and known at compile-time. s.c2 = ImGui.Combo("combo 3 (one-liner)", s.c2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0") - s.c3 = ImGui.Combo("combo 4 (array)", s.c3, items, #items) + + -- Simplified one-liner Combo() using an array of strings + -- This is not very useful (may obsolete): prefer using BeginCombo()/EndCombo() for full control. + s.c3 = ImGui.Combo("combo 4 (array)", s.c3, items, #items) -- If the selection isn't within 0..count, Combo won't display a preview + + -- Simplified one-liner Combo() using an accessor function s.c4 = ImGui.Combo("combo 5 (function)", s.c4, function(data, n) return data[n + 1] end, items, #items) ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDataTypes() +------------------------------------------------------------------------------- + S.dt = { s8 = 127, u8 = 255, s16 = 32767, u16 = 65535, s32 = -1, u32 = 0xFFFFFFFF, s64 = -1, u64 = 0, f32 = 0.123, f64 = 90000.01234567890123456789, drag_clamp = false, inputs_step = true, flags = 0 } function DemoWindowWidgetsDataTypes() if not ImGui.TreeNode("Data Types") then return end local s = S.dt local DT = ImGuiDataType + -- DragScalar/InputScalar/SliderScalar functions allow various data types + -- - signed/unsigned + -- - 8/16/32/64-bits + -- - integer/float/double + -- To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum + -- to pass the type. + -- In practice, if you frequently use a given type that is not covered by the normal API entry points, + -- you can wrap it yourself inside a 1 line function which can take typed argument as value, + -- and then pass them to the generic function. For example: + -- local function MySliderU32(label, value, min, max, format) + -- return ImGui.SliderScalar(label, ImGuiDataType.U32, value, min or 0, max or 0, format or "%u") + -- end + -- ponytail: Luau numbers are doubles, so S64/U64 are shown with S32/Double here (no 64-bit integer type) + -- Setup limits + -- Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2. local s32_min, s32_max = math.floor(-2147483648 / 2), math.floor(2147483647 / 2) local u32_max = math.floor(4294967295 / 2) local drag_speed = 0.2 @@ -5649,6 +6469,10 @@ function DemoWindowWidgetsDataTypes() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDisableBlocks() +------------------------------------------------------------------------------- + function DemoWindowWidgetsDisableBlocks(demo_data) if not ImGui.TreeNode("Disable Blocks") then return end _, demo_data.DisableSections = ImGui.Checkbox("Disable entire section above", demo_data.DisableSections) @@ -5656,6 +6480,10 @@ function DemoWindowWidgetsDisableBlocks(demo_data) ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDragAndDrop() +------------------------------------------------------------------------------- + S.dnd = { col1 = { 1.0, 0.0, 0.2 }, col2 = { 0.4, 0.7, 0.0, 0.5 }, mode = 0, names = { "Bobby", "Beatrice", "Betty", "Brianna", "Barry", "Bernard", "Bibi", "Blaine", "Bryn" }, item_names = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" }, col4 = ImVec4(1.0, 0.0, 0.2, 1.0) } @@ -5663,6 +6491,10 @@ function DemoWindowWidgetsDragAndDrop() if not ImGui.TreeNode("Drag and Drop") then return end local s = S.dnd if ImGui.TreeNode("Drag and drop in standard widgets") then + -- ColorEdit widgets automatically act as drag source and drag target. + -- They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F + -- to allow your own widgets to use colors in their drag and drop interaction. + -- Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo. HelpMarker("You can drag from the color squares.") ImGui.ColorEdit3("color 1", s.col1) ImGui.ColorEdit4("color 2", s.col2) @@ -5679,8 +6511,14 @@ function DemoWindowWidgetsDragAndDrop() ImGui.PushID(n) if n % 3 ~= 0 then ImGui.SameLine() end ImGui.Button(names[n + 1], ImVec2(60, 60)) + + -- Our buttons are both drag sources and drag targets here! if ImGui.BeginDragDropSource(ImGuiDragDropFlags.None) then + -- Set payload to carry the index of our item (could be anything) ImGui.SetDragDropPayload("DND_DEMO_CELL", n, 4) + + -- Display preview (could be anything, e.g. when dragging an image we could decide to display + -- the filename and a small preview of the image, etc.) if s.mode == Mode_Copy then ImGui.Text("Copy %s", names[n + 1]) end if s.mode == Mode_Move then ImGui.Text("Move %s", names[n + 1]) end if s.mode == Mode_Swap then ImGui.Text("Swap %s", names[n + 1]) end @@ -5702,7 +6540,12 @@ function DemoWindowWidgetsDragAndDrop() end if ImGui.TreeNode("Drag to reorder items (simple)") then + -- FIXME: there is temporary (usually single-frame) ID Conflict during reordering as a same item may be submitting twice. + -- This code was always slightly faulty but in a way which was not easily noticeable. + -- Until we fix this, enable ImGuiItemFlags.AllowDuplicateId to disable detecting the issue. ImGui.PushItemFlag(ImGuiItemFlags.AllowDuplicateId, true) + + -- Simple reordering HelpMarker("We don't use the drag and drop api at all here! Instead we query when the item is held but not hovered, and order items accordingly.") local item_names = s.item_names for n = 1, #item_names do @@ -5723,6 +6566,7 @@ function DemoWindowWidgetsDragAndDrop() if ImGui.TreeNode("Tooltip at target location") then for n = 0, 1 do + -- Drop targets ImGui.Button((n == 1) and "drop here##1" or "drop here##0") if ImGui.BeginDragDropTarget() then local drop_target_flags = bit32.bor(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoPreviewTooltip) @@ -5732,6 +6576,8 @@ function DemoWindowWidgetsDragAndDrop() end ImGui.EndDragDropTarget() end + + -- Drop source if n == 0 then ImGui.ColorButton("drag me", s.col4) end end ImGui.TreePop() @@ -5739,9 +6585,14 @@ function DemoWindowWidgetsDragAndDrop() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsDragsAndSliders() +------------------------------------------------------------------------------- + S.ds = { flags = 0, drag_f = 0.5, drag_f4 = { 0, 0, 0, 0 }, drag_i = 50, slider_f = 0.5, slider_f4 = { 0, 0, 0, 0 }, slider_i = 50 } function DemoWindowWidgetsDragsAndSliders() if not ImGui.TreeNode("Drag/Slider Flags") then return end + -- Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same! local s = S.ds local SF = ImGuiSliderFlags local function F(name, help) @@ -5760,45 +6611,70 @@ function DemoWindowWidgetsDragsAndSliders() F("ColorMarkers") local flags = s.flags + -- Drags ImGui.Text("Underlying float value: %f", s.drag_f) s.drag_f = ImGui.DragFloat("DragFloat (0 -> 1)", s.drag_f, 0.005, 0.0, 1.0, "%.3f", flags) s.drag_f = ImGui.DragFloat("DragFloat (0 -> +inf)", s.drag_f, 0.005, 0.0, FLT_MAX, "%.3f", flags) s.drag_f = ImGui.DragFloat("DragFloat (-inf -> 1)", s.drag_f, 0.005, -FLT_MAX, 1.0, "%.3f", flags) s.drag_f = ImGui.DragFloat("DragFloat (-inf -> +inf)", s.drag_f, 0.005, -FLT_MAX, FLT_MAX, "%.3f", flags) + -- ImGui.DragFloat("DragFloat (0 -> 0)", drag_f, 0.005, 0.0, 0.0, "%.3f", flags) -- To test ClampZeroRange + -- ImGui.DragFloat("DragFloat (100 -> 100)", drag_f, 0.005, 100.0, 100.0, "%.3f", flags) s.drag_i = ImGui.DragInt("DragInt (0 -> 100)", s.drag_i, 0.5, 0, 100, "%d", flags) - ImGui.DragFloat4("DragFloat4 (0 -> 1)", s.drag_f4, 0.005, 0.0, 1.0, "%.3f", flags) + ImGui.DragFloat4("DragFloat4 (0 -> 1)", s.drag_f4, 0.005, 0.0, 1.0, "%.3f", flags) -- Multi-component item, mostly here to document the effect of ImGuiSliderFlags.ColorMarkers. + -- Sliders local flags_for_sliders = bit32.band(flags, bit32.bnot(SF.WrapAround)) ImGui.Text("Underlying float value: %f", s.slider_f) s.slider_f = ImGui.SliderFloat("SliderFloat (0 -> 1)", s.slider_f, 0.0, 1.0, "%.3f", flags_for_sliders) s.slider_i = ImGui.SliderInt("SliderInt (0 -> 100)", s.slider_i, 0, 100, "%d", flags_for_sliders) - ImGui.SliderFloat4("SliderFloat4 (0 -> 1)", s.slider_f4, 0.0, 1.0, "%.3f", flags_for_sliders) + ImGui.SliderFloat4("SliderFloat4 (0 -> 1)", s.slider_f4, 0.0, 1.0, "%.3f", flags_for_sliders) -- Multi-component item, mostly here to document the effect of ImGuiSliderFlags.ColorMarkers. ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsFonts() +------------------------------------------------------------------------------- + function DemoWindowWidgetsFonts() if not ImGui.TreeNode("Fonts") then return end if ImGui.ShowFontAtlas then ImGui.ShowFontAtlas(ImGui.GetIO().Fonts) else DemoNotPorted("ShowFontAtlas") end + -- FIXME-NEWATLAS: Provide a demo to add/create a procedural font? ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsImages() +------------------------------------------------------------------------------- + S.img = { viewer = nil, pressed_count = 0 } function DemoWindowWidgetsImages() if not ImGui.TreeNode("Images") then return end local s = S.img local io = ImGui.GetIO() ImGui.TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!") + + -- Below we are displaying the font texture because it is the only texture we have access to inside the demo! + -- Read description about ImTextureID/ImTextureRef and FAQ for details about texture identifiers. + -- - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer, + -- it will help you debug issues if you are confused about it. + -- - Consider using the lower-level ImDrawList:AddImage() API, via ImGui.GetWindowDrawList():AddImage(). + -- - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md + -- - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples + + -- Grab the current texture identifier used by the font atlas. local atlas = io.Fonts local my_tex_id = atlas.TexRef - local my_tex_w = atlas.TexData and atlas.TexData.Width or 0 + local my_tex_w = atlas.TexData and atlas.TexData.Width or 0 -- Regular user code should never have to care about TexData fields, but since we want to display the entire texture here, we pull Width/Height from it. local my_tex_h = atlas.TexData and atlas.TexData.Height or 0 ImGui.Text("%.0fx%.0f", my_tex_w, my_tex_h) + -- Basic drawing ImGui.SeparatorText("Image()/ImageWithBg() function") ImGui.PushStyleVar(ImGuiStyleVar.ImageBorderSize, math.max(1.0, ImGui.GetStyle().ImageBorderSize)) - ImGui.ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0.0, 0.0), ImVec2(1.0, 1.0), ImVec4(0.0, 0.0, 0.0, 1.0)) + ImGui.ImageWithBg(my_tex_id, ImVec2(my_tex_w, my_tex_h), ImVec2(0.0, 0.0), ImVec2(1.0, 1.0), ImVec4(0.0, 0.0, 0.0, 1.0)) -- uv_min: Top-left, uv_max: Lower-right ImGui.PopStyleVar() + -- Fancy widget ImGui.SeparatorText("Interactive Image Viewer") s.viewer = s.viewer or ExampleImageViewerData() local canvas_size = ImVec2(ImGui.GetContentRegionAvail().x, my_tex_h * 2.0) @@ -5808,11 +6684,15 @@ function DemoWindowWidgetsImages() ImGui.SeparatorText("Textured Buttons") ImGui.TextWrapped("And now some textured buttons..") for i = 0, 7 do + -- UV coordinates are often (0.0, 0.0) and (1.0, 1.0) to display an entire textures. + -- Here are trying to display only a 32x32 pixels area of the texture, hence the UV computation. + -- Read about UV coordinates here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples ImGui.PushID(i) if i > 0 then ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, ImVec2(i - 1.0, i - 1.0)) end - local size = ImVec2(32.0, 32.0) - local uv0 = ImVec2(0.0, 0.0) - local uv1 = ImVec2(32.0 / my_tex_w, 32.0 / my_tex_h) + local size = ImVec2(32.0, 32.0) -- Size of the image we want to make visible + local uv0 = ImVec2(0.0, 0.0) -- UV coordinates for lower-left + local uv1 = ImVec2(32.0 / my_tex_w, 32.0 / my_tex_h) -- UV coordinates for (32,32) in our texture + -- bg_col: Black background, tint_col: No tint if ImGui.ImageButton("", my_tex_id, size, uv0, uv1, ImVec4(0.0, 0.0, 0.0, 1.0), ImVec4(1.0, 1.0, 1.0, 1.0)) then s.pressed_count = s.pressed_count + 1 end @@ -5825,29 +6705,45 @@ function DemoWindowWidgetsImages() ImGui.TreePop() end -S.lb = { sel = 0, highlight = false } +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsListBoxes() +------------------------------------------------------------------------------- + +S.lb = { sel = 0, highlight = false } -- sel: Here we store our selected data as an index. function DemoWindowWidgetsListBoxes() if not ImGui.TreeNode("List Boxes") then return end + -- BeginListBox() is essentially a thin wrapper to using BeginChild()/EndChild() + -- using the ImGuiChildFlags.FrameStyle flag for stylistic changes + displaying a label. + -- You may be tempted to simply use BeginChild() directly. However note that BeginChild() requires EndChild() + -- to always be called (inconsistent with BeginListBox()/EndListBox()). + + -- Using the generic BeginListBox() API, you have full control over how to display the combo contents. + -- (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively + -- stored in the object itself, etc.) local s = S.lb local items = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" } - local item_highlighted_idx = -1 + local item_highlighted_idx = -1 -- Here we store our highlighted data as an index. _, s.highlight = ImGui.Checkbox("Highlight hovered item in second listbox", s.highlight) if ImGui.BeginListBox("listbox 1") then for n = 0, #items - 1 do local is_selected = (s.sel == n) if ImGui.Selectable(items[n + 1], is_selected) then s.sel = n end if s.highlight and ImGui.IsItemHovered() then item_highlighted_idx = n end + -- Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if is_selected then ImGui.SetItemDefaultFocus() end end ImGui.EndListBox() end ImGui.SameLine(); HelpMarker("Here we are sharing selection state between both boxes.") + + -- Custom size: use all width, 5 items tall ImGui.Text("Full-width:") if ImGui.BeginListBox("##listbox 2", ImVec2(-FLT_MIN, 5 * ImGui.GetTextLineHeightWithSpacing())) then for n = 0, #items - 1 do local is_selected = (s.sel == n) local flags = (item_highlighted_idx == n) and ImGuiSelectableFlags.Highlight or 0 if ImGui.Selectable(items[n + 1], is_selected, flags) then s.sel = n end + -- Set the initial focus when opening the combo (scrolling + keyboard navigation focus) if is_selected then ImGui.SetItemDefaultFocus() end end ImGui.EndListBox() @@ -5855,6 +6751,10 @@ function DemoWindowWidgetsListBoxes() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsLiveEdit() +------------------------------------------------------------------------------- + S.le = { str = Buf("", 32), i = 0, f = 0.0 } function DemoWindowWidgetsLiveEdit(demo_data) if not ImGui.TreeNode("Live Edit Flags") then return end @@ -5878,15 +6778,22 @@ function DemoWindowWidgetsLiveEdit(demo_data) ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsMixedValues() +------------------------------------------------------------------------------- + S.mv = { use_liveedit = false, items = { 12.0, 0.0, 0.0 } } function DemoWindowWidgetsMixedValues() if not ImGui.TreeNode("Mixed Values") then return end local s = S.mv local items = s.items + -- This is designed for advanced property editors which are generally reusable and data-driven. HelpMarker("Using ImGuiItemFlags_MixedValue.") _, s.use_liveedit = ImGui.Checkbox("ImGuiItemFlags_LiveEditOnInput", s.use_liveedit) ImGui.SeparatorText("Scalar/Text Widgets") local is_mixed = items[1] ~= items[2] or items[1] ~= items[3] + + -- Demonstrate Drags, Sliders, Inputs ImGui.PushItemFlag(ImGuiItemFlags.LiveEditOnInput, s.use_liveedit) ImGui.PushItemFlag(ImGuiItemFlags.MixedValue, is_mixed) local edited, e = false, false @@ -5901,27 +6808,32 @@ function DemoWindowWidgetsMixedValues() items[3] = ImGui.InputFloat("item 2", items[3]) ImGui.PopItemFlag() + -- Demonstrate Checkbox(), RadioButton(), Combo(), ColorEdit4() ImGui.SeparatorText("Others Widgets") - ImGui.Text("(note: edits are not applied in this demo)") + ImGui.Text("(note: edits are not applied in this demo)") -- <-- Would need more state tracking. ImGui.Checkbox("Checkbox On", true) ImGui.Checkbox("Checkbox Off", false) ImGui.PushItemFlag(ImGuiItemFlags.MixedValue, true) ImGui.Checkbox("Checkbox Mixed", false) ImGui.RadioButtonEx("RadioButton Mixed", true) ImGui.SameLine() - ImGui.RadioButtonEx("RadioButton Mixed##2", true) + ImGui.RadioButtonEx("RadioButton Mixed##2", true) -- Showing 2 radio buttons makes the example more clear ImGui.Combo("Combo", 0, "One\0Two\0Three\0") ImGui.ColorEdit4("ColorEdit4", ImVec4(0.5, 0.5, 0.5, 0.5)) ImGui.PopItemFlag() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsMultiComponents() +------------------------------------------------------------------------------- + S.mc = { vec4f = { 0.10, 0.20, 0.30, 0.44 }, vec4i = { 1, 5, 100, 255 }, flags = 0, b = 10, e = 90, bi = 100, ei = 1000 } function DemoWindowWidgetsMultiComponents() if not ImGui.TreeNode("Multi-component Widgets") then return end local s = S.mc local f, i = s.vec4f, s.vec4i - if ImGuiSliderFlags.ColorMarkers then _, s.flags = ImGui.CheckboxFlags("ImGuiSliderFlags_ColorMarkers", s.flags, ImGuiSliderFlags.ColorMarkers) end + if ImGuiSliderFlags.ColorMarkers then _, s.flags = ImGui.CheckboxFlags("ImGuiSliderFlags_ColorMarkers", s.flags, ImGuiSliderFlags.ColorMarkers) end -- Only passing this to Drag/Sliders local flags = s.flags for _, n in ipairs({ 2, 3, 4 }) do ImGui.SeparatorText(n .. "-wide") @@ -5939,6 +6851,13 @@ function DemoWindowWidgetsMultiComponents() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsPlotting() +------------------------------------------------------------------------------- + +-- Plot/Graph widgets are not very good. +-- Consider using a third-party library such as ImPlot: https://github.com/epezent/implot +-- (see others https://github.com/ocornut/imgui/wiki/Useful-Extensions) S.plot = { animate = true, arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }, values = {}, values_offset = 0, refresh_time = 0.0, phase = 0.0, func_type = 0, display_count = 70 } for n = 1, 90 do S.plot.values[n] = 0.0 end @@ -5949,22 +6868,32 @@ function DemoWindowWidgetsPlotting() ImGui.TextLinkOpenURL("https://github.com/epezent/implot") ImGui.Separator() _, s.animate = ImGui.Checkbox("Animate", s.animate) + + -- Plot as lines and plot as histogram ImGui.PlotLines("Frame Times", s.arr, nil, #s.arr) ImGui.PlotHistogram("Histogram", s.arr, nil, #s.arr, 0, nil, 0.0, 1.0, ImVec2(0, 80.0)) + -- ImGui.SameLine(); HelpMarker("Consider using ImPlot instead!") + -- Fill an array of contiguous float values to plot local values = s.values if not s.animate or s.refresh_time == 0.0 then s.refresh_time = ImGui.GetTime() end - while s.refresh_time < ImGui.GetTime() do + while s.refresh_time < ImGui.GetTime() do -- Create data at fixed 60 Hz rate for the demo values[s.values_offset + 1] = math.cos(s.phase) s.values_offset = (s.values_offset + 1) % #values s.phase = s.phase + 0.10 * s.values_offset s.refresh_time = s.refresh_time + 1.0 / 60.0 end + + -- Plots can display overlay texts + -- (in this example, we will display an average value) local average = 0.0 for n = 1, #values do average = average + values[n] end average = average / #values ImGui.PlotLines("Lines", values, nil, #values, s.values_offset, string.format("avg %f", average), -1.0, 1.0, ImVec2(0, 80.0)) + -- Use functions to generate output + -- FIXME: This is actually VERY awkward because current plot API only pass in indices. + -- We probably want an API passing floats and user provide sample rate/count. -- Getters receive a 1-based index in this port local function Sin(_, i) return math.sin((i - 1) * 0.1) end local function Saw(_, i) return ((i - 1) % 2 == 1) and 1.0 or -1.0 end @@ -5979,24 +6908,39 @@ function DemoWindowWidgetsPlotting() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsProgressBars() +------------------------------------------------------------------------------- + S.pb = { accum = 0.0, dir = 1.0 } function DemoWindowWidgetsProgressBars() if not ImGui.TreeNode("Progress Bars") then return end + -- Animate a simple progress bar local s = S.pb s.accum = s.accum + s.dir * 0.4 * ImGui.GetIO().DeltaTime if s.accum >= 1.1 then s.accum = 1.1; s.dir = -s.dir end if s.accum <= -0.1 then s.accum = -0.1; s.dir = -s.dir end local progress = DemoClamp(s.accum, 0.0, 1.0) + + -- Typically we would use ImVec2(-1.0,0.0) or ImVec2(-FLT_MIN,0.0) to use all available width, + -- or ImVec2(width,0.0) for a specified width. ImVec2(0.0,0.0) uses ItemWidth. ImGui.ProgressBar(progress, ImVec2(0.0, 0.0)) ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x) ImGui.Text("Progress Bar") ImGui.ProgressBar(progress, ImVec2(0.0, 0.0), string.format("%d/%d", math.floor(progress * 1753), 1753)) + + -- Pass an animated negative value, e.g. -1.0 * ImGui.GetTime() is the recommended value. + -- Adjust the factor if you want to adjust the animation speed. ImGui.ProgressBar(-1.0 * ImGui.GetTime(), ImVec2(0.0, 0.0), "Searching..") ImGui.SameLine(0.0, ImGui.GetStyle().ItemInnerSpacing.x) ImGui.Text("Indeterminate") ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsQueryingStatuses() +------------------------------------------------------------------------------- + -- Selectable(label, bool* p_selected) overload: toggles on press local function SelectableP(label, sel, flags, size) local pressed = ImGui.Selectable(label, sel, flags, size) @@ -6012,6 +6956,7 @@ S.qs = { item_type = 4, item_disabled = false, item_mixedvalue = false, liveedit function DemoWindowWidgetsQueryingStatuses() local s = S.qs if ImGui.TreeNode("Querying Item Status (Edited/Active/Hovered etc.)") then + -- Select an item type local item_names = { "Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputTextMultiline", "InputFloat", "InputFloat3", "ColorEdit4", "Selectable", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "Combo", "ListBox" } s.item_type = ImGui.Combo("Item Type", s.item_type, item_names, #item_names, #item_names) @@ -6034,24 +6979,25 @@ function DemoWindowWidgetsQueryingStatuses() ImGui.PushItemFlag(ImGuiItemFlags.LiveEditOnInputScalar, bit32.band(s.liveedit_flags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0) end + -- Submit selected items so we can query their status in the code following it. local ret = false local t = s.item_type if s.item_disabled then ImGui.BeginDisabled(true) end if s.item_mixedvalue then ImGui.PushItemFlag(ImGuiItemFlags.MixedValue, true) end - if t == 0 then ImGui.Text("ITEM: Text") end - if t == 1 then ret = ImGui.Button("ITEM: Button") end - if t == 2 then ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true); ret = ImGui.Button("ITEM: Button"); ImGui.PopItemFlag() end - if t == 3 then ret, s.b = ImGui.Checkbox("ITEM: Checkbox", s.b) end - if t == 4 then s.col4f[1], ret = ImGui.SliderFloat("ITEM: SliderFloat", s.col4f[1], 0.0, 1.0) end - if t == 5 then ret = ImGui.InputText("ITEM: InputText", s.str, 16) end - if t == 6 then ret = ImGui.InputTextMultiline("ITEM: InputTextMultiline", s.str, 16) end - if t == 7 then s.col4f[1], ret = ImGui.InputFloat("ITEM: InputFloat", s.col4f[1], 1.0) end - if t == 8 then ret = ImGui.InputFloat3("ITEM: InputFloat3", s.col4f) end - if t == 9 then ret = ImGui.ColorEdit4("ITEM: ColorEdit4", s.col4f) end - if t == 10 then ret = ImGui.Selectable("ITEM: Selectable") end - if t == 11 then ret = ImGui.MenuItem("ITEM: MenuItem") end - if t == 12 then ret = ImGui.TreeNode("ITEM: TreeNode"); if ret then ImGui.TreePop() end end - if t == 13 then ret = ImGui.TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", bit32.bor(ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.NoTreePushOnOpen)) end + if t == 0 then ImGui.Text("ITEM: Text") end -- Testing text items with no identifier/interaction + if t == 1 then ret = ImGui.Button("ITEM: Button") end -- Testing button + if t == 2 then ImGui.PushItemFlag(ImGuiItemFlags.ButtonRepeat, true); ret = ImGui.Button("ITEM: Button"); ImGui.PopItemFlag() end -- Testing button (with repeater) + if t == 3 then ret, s.b = ImGui.Checkbox("ITEM: Checkbox", s.b) end -- Testing checkbox + if t == 4 then s.col4f[1], ret = ImGui.SliderFloat("ITEM: SliderFloat", s.col4f[1], 0.0, 1.0) end -- Testing basic item + if t == 5 then ret = ImGui.InputText("ITEM: InputText", s.str, 16) end -- Testing input text (which handles tabbing) + if t == 6 then ret = ImGui.InputTextMultiline("ITEM: InputTextMultiline", s.str, 16) end -- Testing input text (which uses a child window) + if t == 7 then s.col4f[1], ret = ImGui.InputFloat("ITEM: InputFloat", s.col4f[1], 1.0) end -- Testing +/- buttons on scalar input + if t == 8 then ret = ImGui.InputFloat3("ITEM: InputFloat3", s.col4f) end -- Testing multi-component items (IsItemXXX flags are reported merged) + if t == 9 then ret = ImGui.ColorEdit4("ITEM: ColorEdit4", s.col4f) end -- Testing multi-component items (IsItemXXX flags are reported merged) + if t == 10 then ret = ImGui.Selectable("ITEM: Selectable") end -- Testing selectable item + if t == 11 then ret = ImGui.MenuItem("ITEM: MenuItem") end -- Testing menu item (they use ImGuiButtonFlags.PressedOnRelease button policy) + if t == 12 then ret = ImGui.TreeNode("ITEM: TreeNode"); if ret then ImGui.TreePop() end end -- Testing tree node + if t == 13 then ret = ImGui.TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", bit32.bor(ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.NoTreePushOnOpen)) end -- Testing tree node with ImGuiButtonFlags.PressedOnDoubleClick button policy. if t == 14 then s.combo, ret = ImGui.Combo("ITEM: Combo", s.combo, { "Apple", "Banana", "Cherry", "Kiwi" }) end if t == 15 then s.listbox, ret = ImGui.ListBox("ITEM: ListBox", s.listbox, { "Apple", "Banana", "Cherry", "Kiwi" }, 4, 4) end @@ -6060,7 +7006,12 @@ function DemoWindowWidgetsQueryingStatuses() local hovered_delay_stationary = ImGui.IsItemHovered(HF.Stationary) local hovered_delay_short = ImGui.IsItemHovered(HF.DelayShort) local hovered_delay_normal = ImGui.IsItemHovered(HF.DelayNormal) - local hovered_delay_tooltip = ImGui.IsItemHovered(HF.ForTooltip) + local hovered_delay_tooltip = ImGui.IsItemHovered(HF.ForTooltip) -- = Normal + Stationary + + -- Display the values of IsItemHovered() and other common item state functions. + -- Note that the ImGuiHoveredFlags.XXX flags can be combined. + -- Because BulletText is an item itself and that would affect the output of IsItemXXX functions, + -- we query every state in a single call to avoid storing them and to simplify the code. local rmin, rmax, rsize = ImGui.GetItemRectMin(), ImGui.GetItemRectMax(), ImGui.GetItemRectSize() ImGui.BulletText( "Return value = %d\nIsItemFocused() = %d\nIsItemHovered() = %d\nIsItemHovered(_AllowWhenBlockedByPopup) = %d\n" .. @@ -6094,6 +7045,7 @@ function DemoWindowWidgetsQueryingStatuses() if s.embed then ImGui.BeginChild("outer_child", ImVec2(0, ImGui.GetFontSize() * 20.0), ImGuiChildFlags.Borders) end local FF, HF = ImGuiFocusedFlags, ImGuiHoveredFlags local bor = bit32.bor + -- Testing IsWindowFocused() function with its various flags. ImGui.BulletText( "IsWindowFocused() = %d\nIsWindowFocused(_ChildWindows) = %d\nIsWindowFocused(_ChildWindows|_NoPopupHierarchy) = %d\n" .. "IsWindowFocused(_ChildWindows|_DockHierarchy) = %d\nIsWindowFocused(_ChildWindows|_RootWindow) = %d\n" .. @@ -6105,6 +7057,8 @@ function DemoWindowWidgetsQueryingStatuses() B(ImGui.IsWindowFocused(bor(FF.ChildWindows, FF.RootWindow, FF.NoPopupHierarchy))), B(ImGui.IsWindowFocused(bor(FF.ChildWindows, FF.RootWindow, FF.DockHierarchy))), B(ImGui.IsWindowFocused(FF.RootWindow)), B(ImGui.IsWindowFocused(bor(FF.RootWindow, FF.NoPopupHierarchy))), B(ImGui.IsWindowFocused(bor(FF.RootWindow, FF.DockHierarchy))), B(ImGui.IsWindowFocused(FF.AnyWindow))) + + -- Testing IsWindowHovered() function with its various flags. ImGui.BulletText( "IsWindowHovered() = %d\nIsWindowHovered(_AllowWhenBlockedByPopup) = %d\nIsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n" .. "IsWindowHovered(_ChildWindows) = %d\nIsWindowHovered(_ChildWindows|_NoPopupHierarchy) = %d\nIsWindowHovered(_ChildWindows|_DockHierarchy) = %d\n" .. @@ -6123,10 +7077,15 @@ function DemoWindowWidgetsQueryingStatuses() ImGui.EndChild() if s.embed then ImGui.EndChild() end + -- Calling IsItemHovered() after begin returns the hovered status of the title bar. + -- This is useful in particular if you want to create a context menu associated to the title bar of a window. + -- This will also work when docked into a Tab (the Tab replace the Title Bar and guarantee the same properties). _, s.test_window = ImGui.Checkbox("Hovered/Active tests after Begin() for title bar testing", s.test_window) if s.test_window then + -- FIXME-DOCK: This window cannot be docked within the ImGui Demo window, this will cause a feedback loop and get them stuck. + -- Could we fix this through an ImGuiWindowClass feature? Or an API call to tag our parent as "don't skip items"? s.test_window = ImGui.Begin("Title bar Hovered/Active tests", s.test_window) - if ImGui.BeginPopupContextItem() then + if ImGui.BeginPopupContextItem() then -- <-- This is using IsItemHovered() if ImGui.MenuItem("Close") then s.test_window = false end ImGui.EndPopup() end @@ -6138,13 +7097,25 @@ function DemoWindowWidgetsQueryingStatuses() end end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsSelectables() +------------------------------------------------------------------------------- + S.sel = { basic = { false, true, false, false }, multi = { false, false, false }, checked = { false, false, false, false, false }, selected_n = 0, tables = {}, grid = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }, align = { true, false, true, false, true, false, true, false, true } } for i = 1, 10 do S.sel.tables[i] = false end function DemoWindowWidgetsSelectables() + -- ImGui.SetNextItemOpen(true, ImGuiCond.Once) if not ImGui.TreeNode("Selectables") then return end local s = S.sel + -- Selectable() has 2 overloads: + -- - The one taking "bool selected" as a read-only selection information. + -- When Selectable() has been clicked it returns true and you can alter selection state accordingly. + -- - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases) + -- (in this port: the SelectableP() helper above, which returns (pressed, selected)) + -- The earlier is more flexible, as in real application your selection may be stored in many different ways + -- and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc). if ImGui.TreeNode("Basic") then local b = s.basic _, b[1] = SelectableP("1. I am selectable", b[1]) @@ -6157,10 +7128,17 @@ function DemoWindowWidgetsSelectables() end if ImGui.TreeNode("Multiple items on the same line") then + -- - Using SetNextItemAllowOverlap() + -- - Using the Selectable() override that takes "bool* p_selected" parameter, the bool value is toggled automatically. local m = s.multi ImGui.SetNextItemAllowOverlap(); _, m[1] = SelectableP("main.c", m[1]); ImGui.SameLine(); ImGui.SmallButton("Link 1") ImGui.SetNextItemAllowOverlap(); _, m[2] = SelectableP("hello.cpp", m[2]); ImGui.SameLine(); ImGui.SmallButton("Link 2") ImGui.SetNextItemAllowOverlap(); _, m[3] = SelectableP("hello.h", m[3]); ImGui.SameLine(); ImGui.SmallButton("Link 3") + + -- (2) + -- - Using ImGuiSelectableFlags.AllowOverlap is a shortcut for calling SetNextItemAllowOverlap() + -- - No visible label, display contents inside the selectable bounds. + -- - We don't maintain actual selection in this example to keep things simple. ImGui.Spacing() local color_marker_w = ImGui.CalcTextSize("x").x for n = 0, 4 do @@ -6185,7 +7163,7 @@ function DemoWindowWidgetsSelectables() if ImGui.BeginTable("split1", 3, bit32.bor(TF.Resizable, TF.NoSavedSettings, TF.Borders)) then for i = 0, 9 do ImGui.TableNextColumn() - _, sel[i + 1] = SelectableP(string.format("Item %d", i), sel[i + 1]) + _, sel[i + 1] = SelectableP(string.format("Item %d", i), sel[i + 1]) -- FIXME-TABLE: Selection overlap end ImGui.EndTable() end @@ -6207,9 +7185,11 @@ function DemoWindowWidgetsSelectables() if ImGui.TreeNode("Grid") then local g = s.grid + + -- Add in a bit of silly fun... local time = ImGui.GetTime() local winning_state = true - for y = 1, 4 do for x = 1, 4 do if g[y][x] == 0 then winning_state = false end end end + for y = 1, 4 do for x = 1, 4 do if g[y][x] == 0 then winning_state = false end end end -- If all cells are selected... if winning_state then ImGui.PushStyleVar(ImGuiStyleVar.SelectableTextAlign, ImVec2(0.5 + 0.5 * math.cos(time * 2.0), 0.5 + 0.5 * math.sin(time * 3.0))) end @@ -6219,6 +7199,7 @@ function DemoWindowWidgetsSelectables() if x > 1 then ImGui.SameLine() end ImGui.PushID((y - 1) * 4 + (x - 1)) if ImGui.Selectable("Sailor", g[y][x] ~= 0, 0, ImVec2(size, size)) then + -- Toggle clicked cell + toggle neighbors g[y][x] = 1 - g[y][x] if x > 1 then g[y][x - 1] = 1 - g[y][x - 1] end if x < 4 then g[y][x + 1] = 1 - g[y][x + 1] end @@ -6250,6 +7231,10 @@ function DemoWindowWidgetsSelectables() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTabs() +------------------------------------------------------------------------------- + local function EditTabBarFittingPolicyFlags(flags) local TB = ImGuiTabBarFlags if bit32.band(flags, TB.FittingPolicyMask_) == 0 then flags = bit32.bor(flags, TB.FittingPolicyDefault_) end @@ -6280,17 +7265,23 @@ function DemoWindowWidgetsTabs() end if ImGui.TreeNode("Advanced & Close Button") then + -- Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0). for _, n in ipairs({ "Reorderable", "AutoSelectNewTabs", "TabListPopupButton", "NoCloseWithMiddleMouseButton", "DrawSelectedOverline" }) do _, s.adv_flags = ImGui.CheckboxFlags("ImGuiTabBarFlags_" .. n, s.adv_flags, TB[n]) end s.adv_flags = EditTabBarFittingPolicyFlags(s.adv_flags) + + -- Tab Bar ImGui.AlignTextToFramePadding() ImGui.Text("Opened:") local names = { "Artichoke", "Beetroot", "Celery", "Daikon" } - for n = 1, 4 do + for n = 1, 4 do -- s.opened: Persistent user state ImGui.SameLine() _, s.opened[n] = ImGui.Checkbox(names[n], s.opened[n]) end + + -- Passing an open flag to BeginTabItem() is similar to passing one to Begin(): + -- the returned open value will be false when the tab is closed. if ImGui.BeginTabBar("MyTabBar", s.adv_flags) then for n = 1, 4 do if s.opened[n] then @@ -6310,14 +7301,22 @@ function DemoWindowWidgetsTabs() end if ImGui.TreeNode("TabItemButton & Leading/Trailing flags") then - if s.next_tab_id == 0 then + if s.next_tab_id == 0 then -- Initialize with some default tabs for _ = 1, 3 do s.active_tabs[#s.active_tabs + 1] = s.next_tab_id; s.next_tab_id = s.next_tab_id + 1 end end + + -- TabItemButton() and Leading/Trailing flags are distinct features which we will demo together. + -- (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags... + -- but they tend to make more sense together) _, s.show_leading = ImGui.Checkbox("Show Leading TabItemButton()", s.show_leading) _, s.show_trailing = ImGui.Checkbox("Show Trailing TabItemButton()", s.show_trailing) _, s.show_lt_tabs = ImGui.Checkbox("Show Leading+Trailing TabItem()", s.show_lt_tabs) + + -- Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs s.tib_flags = EditTabBarFittingPolicyFlags(s.tib_flags) + if ImGui.BeginTabBar("MyTabBar", s.tib_flags) then + -- Demo a Leading TabItemButton(): click the "?" button to open a menu if s.show_leading then if ImGui.TabItemButton("?", bit32.bor(TI.Leading, TI.NoTooltip)) then ImGui.OpenPopup("MyHelpMenu") end end @@ -6325,15 +7324,23 @@ function DemoWindowWidgetsTabs() ImGui.Selectable("Hello!") ImGui.EndPopup() end + + -- Demo Leading/Trailing Tabs if s.show_lt_tabs then if ImGui.BeginTabItem("Leading", nil, TI.Leading) then ImGui.EndTabItem() end if ImGui.BeginTabItem("Trailing", nil, TI.Trailing) then ImGui.EndTabItem() end end + + -- Demo Trailing Tabs: click the "+" button to add a new tab. + -- (In your app you may want to use a font icon instead of the "+") + -- We submit it before the regular tabs, but thanks to the ImGuiTabItemFlags.Trailing flag it will always appear at the end. if s.show_trailing then if ImGui.TabItemButton("+", bit32.bor(TI.Trailing, TI.NoTooltip)) then - s.active_tabs[#s.active_tabs + 1] = s.next_tab_id; s.next_tab_id = s.next_tab_id + 1 + s.active_tabs[#s.active_tabs + 1] = s.next_tab_id; s.next_tab_id = s.next_tab_id + 1 -- Add new tab end end + + -- Submit our regular tabs local n = 1 while n <= #s.active_tabs do local name = string.format("%04d", s.active_tabs[n]) @@ -6352,11 +7359,16 @@ function DemoWindowWidgetsTabs() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsText() +------------------------------------------------------------------------------- + S.text = { custom_size = 16.0, custom_scale = 1.0, wrap_width = 200.0, utf8 = Buf("\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e", 32) } function DemoWindowWidgetsText() if not ImGui.TreeNode("Text") then return end local s = S.text if ImGui.TreeNode("Colorful Text") then + -- Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. ImGui.TextColored(ImVec4(1.0, 0.0, 1.0, 1.0), "Pink") ImGui.TextColored(ImVec4(1.0, 1.0, 0.0, 1.0), "Yellow") ImGui.TextDisabled("Disabled") @@ -6369,8 +7381,9 @@ function DemoWindowWidgetsText() local global_scale = style.FontScaleMain * style.FontScaleDpi ImGui.Text("style.FontScaleMain = %0.2f", style.FontScaleMain) ImGui.Text("style.FontScaleDpi = %0.2f", style.FontScaleDpi) - ImGui.Text("global_scale = ~%0.2f", global_scale) + ImGui.Text("global_scale = ~%0.2f", global_scale) -- This is not technically accurate as internal scales may apply, but conceptually let's pretend it is. ImGui.Text("FontSize = %0.2f", ImGui.GetFontSize()) + ImGui.SeparatorText("") s.custom_size = ImGui.SliderFloat("custom_size", s.custom_size, 10.0, 100.0, "%.0f") ImGui.Text("ImGui::PushFont(nullptr, custom_size);") @@ -6395,6 +7408,7 @@ function DemoWindowWidgetsText() end if ImGui.TreeNode("Word Wrapping") then + -- Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. ImGui.TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages.") ImGui.Spacing() s.wrap_width = ImGui.SliderFloat("Wrap width", s.wrap_width, -20, 600, "%.0f") @@ -6410,6 +7424,8 @@ function DemoWindowWidgetsText() else ImGui.Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh") end + + -- Draw actual text bounding box, following by marker of our expected limit (should not overlap!) draw_list:AddRect(ImGui.GetItemRectMin(), ImGui.GetItemRectMax(), IM_COL32(255, 255, 0, 255)) draw_list:AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255)) ImGui.PopTextWrapPos() @@ -6418,6 +7434,12 @@ function DemoWindowWidgetsText() end if ImGui.TreeNode("UTF-8 Text") then + -- UTF-8 test with Japanese characters + -- (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.) + -- - FOR THIS DEMO FILE ONLY, WE ARE *NOT* INCLUDING RAW UTF-8 + -- CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal escapes. + -- Note that characters values are preserved even by InputText() if the font cannot be displayed, + -- so you can safely copy & paste garbled characters into another application. ImGui.TextWrapped("CJK text will only appear if the font was loaded with the appropriate CJK character ranges. Call io.Fonts->AddFontFromFileTTF() manually to load extra character ranges. Read docs/FONTS.md for details.") ImGui.Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)") ImGui.Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)") @@ -6427,9 +7449,15 @@ function DemoWindowWidgetsText() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTextFilter() +------------------------------------------------------------------------------- + S.tf = { filter = nil } function DemoWindowWidgetsTextFilter() if not ImGui.TreeNode("Text Filter") then return end + -- Helper class to easy setup a text filter. + -- You may want to implement a more feature-full filtering scheme in your own application. S.tf.filter = S.tf.filter or ImGuiTextFilter() local filter = S.tf.filter HelpMarker("Not a widget per-se, but ImGuiTextFilter is a helper to perform simple filtering on text strings.") @@ -6448,6 +7476,10 @@ function DemoWindowWidgetsTextFilter() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTextInput() +------------------------------------------------------------------------------- + S.ti = { text = Buf("/*\n The Pentium F00F bug, shorthand for F0 0F C7 C8,\n the hexadecimal encoding of one offending instruction,\n more formally, the invalid operand with locked CMPXCHG8B\n instruction bug, is a design flaw in the majority of\n Intel Pentium, Pentium MMX, and Pentium OverDrive\n processors (all in the P5 microarchitecture).\n*/\n\nlabel:\n\tlock cmpxchg8b eax\n", 1024 * 16), ml_flags = ImGuiInputTextFlags.AllowTabInput, @@ -6464,6 +7496,7 @@ function DemoWindowWidgetsTextInput() if IT[name] then _, s[key] = ImGui.CheckboxFlags("ImGuiInputTextFlags_" .. name, s[key], IT[name]) end end if ImGui.TreeNode("Multi-line Text Input") then + -- WE ARE USING A FIXED-SIZE BUFFER FOR SIMPLICITY HERE. HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type.") FlagBox("ml_flags", "ReadOnly") FlagBox("ml_flags", "WordWrap") @@ -6477,12 +7510,14 @@ function DemoWindowWidgetsTextInput() if ImGui.TreeNode("Filtered Text Input") then local a, z, A, Z = string.byte("a"), string.byte("z"), string.byte("A"), string.byte("Z") + -- Modify character input by altering 'data.EventChar' (ImGuiInputTextFlags.CallbackCharFilter callback) local function FilterCasingSwap(data) local c = data.EventChar - if c >= a and c <= z then data.EventChar = c - (a - A) - elseif c >= A and c <= Z then data.EventChar = c + (a - A) end + if c >= a and c <= z then data.EventChar = c - (a - A) -- Lowercase becomes uppercase + elseif c >= A and c <= Z then data.EventChar = c + (a - A) end -- Uppercase becomes lowercase return 0 end + -- Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i', otherwise return 1 (filter out) local function FilterImGuiLetters(data) local c = data.EventChar if c < 256 and string.find("imgui", string.char(c), 1, true) then return 0 end @@ -6494,8 +7529,8 @@ function DemoWindowWidgetsTextInput() ImGui.InputText("hexadecimal", f[3], 32, bit32.bor(IT.CharsHexadecimal, IT.CharsUppercase)) ImGui.InputText("uppercase", f[4], 32, IT.CharsUppercase) ImGui.InputText("no blank", f[5], 32, IT.CharsNoBlank) - ImGui.InputText("casing swap", f[6], 32, IT.CallbackCharFilter, FilterCasingSwap) - ImGui.InputText("\"imgui\"", f[7], 32, IT.CallbackCharFilter, FilterImGuiLetters) + ImGui.InputText("casing swap", f[6], 32, IT.CallbackCharFilter, FilterCasingSwap) -- Use CharFilter callback to replace characters. + ImGui.InputText("\"imgui\"", f[7], 32, IT.CallbackCharFilter, FilterImGuiLetters) -- Use CharFilter callback to disable some characters. ImGui.TreePop() end @@ -6522,9 +7557,12 @@ function DemoWindowWidgetsTextInput() data:SelectAll() end elseif data.EventFlag == IT.CallbackEdit then + -- Toggle casing of first character local c = data.Buf[1] if (c >= 97 and c <= 122) or (c >= 65 and c <= 90) then data.Buf[1] = bit32.bxor(c, 32) end data.BufDirty = true + + -- Increment a counter local p_int = data.UserData p_int[1] = p_int[1] + 1 end @@ -6564,12 +7602,25 @@ function DemoWindowWidgetsTextInput() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTooltips() +------------------------------------------------------------------------------- + S.tt = { arr = { 0.6, 0.1, 1.0, 0.5, 0.92, 0.1, 0.2 }, always_on = 0 } function DemoWindowWidgetsTooltips() if not ImGui.TreeNode("Tooltips") then return end local s = S.tt local HF = ImGuiHoveredFlags + -- Tooltips are windows following the mouse. They do not take focus away. ImGui.SeparatorText("General") + + -- Typical use cases: + -- - Short-form (text only): SetItemTooltip("Hello") + -- - Short-form (any contents): if BeginItemTooltip() then Text("Hello"); EndTooltip() end + + -- - Full-form (text only): if IsItemHovered(...) then SetTooltip("Hello") end + -- - Full-form (any contents): if IsItemHovered(...) and BeginTooltip() then Text("Hello"); EndTooltip() end + HelpMarker("Tooltip are typically created by using a IsItemHovered() + SetTooltip() sequence.\n\nWe provide a helper SetItemTooltip() function to perform the two with standards flags.") local sz = ImVec2(-FLT_MIN, 0.0) ImGui.Button("Basic", sz) @@ -6583,6 +7634,9 @@ function DemoWindowWidgetsTooltips() end ImGui.SeparatorText("Always On") + + -- Showcase NOT relying on a IsItemHovered() to emit a tooltip. + -- Here the tooltip is always emitted when 'always_on == true'. _, s.always_on = ImGui.RadioButton("Off", s.always_on, 0) ImGui.SameLine() _, s.always_on = ImGui.RadioButton("Always On (Simple)", s.always_on, 1) @@ -6597,6 +7651,11 @@ function DemoWindowWidgetsTooltips() ImGui.SeparatorText("Custom") HelpMarker("Passing ImGuiHoveredFlags_ForTooltip to IsItemHovered() is the preferred way to standardize tooltip activation details across your application. You may however decide to use custom flags for a specific tooltip instance.") + + -- The following examples are passed for documentation purpose but may not be useful to most users. + -- Passing ImGuiHoveredFlags.ForTooltip to IsItemHovered() will pull ImGuiHoveredFlags flags values from + -- 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' depending on whether mouse or keyboard/gamepad is being used. + -- With default settings, ImGuiHoveredFlags.ForTooltip is equivalent to ImGuiHoveredFlags.DelayShort + ImGuiHoveredFlags.Stationary. ImGui.Button("Manual", sz) if ImGui.IsItemHovered(HF.ForTooltip) then ImGui.SetTooltip("I am a manually emitted tooltip.") end ImGui.Button("DelayNone", sz) @@ -6607,6 +7666,9 @@ function DemoWindowWidgetsTooltips() if ImGui.IsItemHovered(bit32.bor(HF.DelayNormal, HF.NoSharedDelay)) then ImGui.SetTooltip("I am a tooltip with a long delay (%0.2f sec).", ImGui.GetStyle().HoverDelayNormal) end ImGui.Button("Stationary", sz) if ImGui.IsItemHovered(HF.Stationary) then ImGui.SetTooltip("I am a tooltip requiring mouse to be stationary before activating.") end + + -- Using ImGuiHoveredFlags.ForTooltip will pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav', + -- which default value include the ImGuiHoveredFlags.AllowWhenDisabled flag. ImGui.BeginDisabled() ImGui.Button("Disabled item", sz) if ImGui.IsItemHovered(HF.ForTooltip) then ImGui.SetTooltip("I am a tooltip for a disabled item.") end @@ -6614,6 +7676,10 @@ function DemoWindowWidgetsTooltips() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsTreeNodes() +------------------------------------------------------------------------------- + S.tn = { lines_flags = bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DefaultOpen), selection_mask = 0, adv_flags = bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.SpanAvailWidth), align_label = false, use_dnd = false } @@ -6621,9 +7687,16 @@ function DemoWindowWidgetsTreeNodes() if not ImGui.TreeNode("Tree Nodes") then return end local s = S.tn local TN = ImGuiTreeNodeFlags + -- See see "Examples -> Property Editor" (ShowExampleAppPropertyEditor() function) for a fancier, data-driven tree. if ImGui.TreeNode("Basic Trees") then for i = 0, 4 do + -- Use SetNextItemOpen() so set the default state of a node to be open. We could + -- also use TreeNodeEx() with the ImGuiTreeNodeFlags.DefaultOpen flag to achieve the same thing! if i == 0 then ImGui.SetNextItemOpen(true, ImGuiCond.Once) end + + -- Here we use PushID() to generate a unique base ID, and then the "" used as TreeNode id won't conflict. + -- An alternative to using 'PushID() + TreeNode("", ...)' to generate a unique ID is to use 'TreeNode(i, ...)', + -- aka pass a number value to be hashed. The demo below uses that technique. Both are fine. ImGui.PushID(i) if ImGui.TreeNode("", "Child %d", i) then ImGui.Text("blah blah") @@ -6659,8 +7732,18 @@ function DemoWindowWidgetsTreeNodes() if ImGui.TreeNode("Selectable Nodes") then HelpMarker("Manually implemented selectable nodes.\nClick to select, Ctrl+Click to toggle, click on arrows or double-click to open.") + + -- Hold in 'selection_mask' a simple representation of what may be user-side selection state. + -- - You may retain selection state inside or outside your objects in whatever format you see fit. + -- You may use ImGuiSelectionBasicStorage which is conceptually close to a set<> of identifiers. + -- - We record which node was clicked and then apply selection at the end of the loop. + -- - This is a manual and simplified reimplementation of multi-selection, which the full + -- BeginMultiSelect() API implements better, but which is not trivial to wire for trees. local node_clicked_idx = -1 for node_n = 0, 5 do + -- Disable the default "open on single-click behavior" + set Selected flag according to our selection. + -- To alter selection we use if 'IsItemClicked() and not IsItemToggledOpen()', so clicking on an arrow doesn't alter selection. + -- In a BeginMultiSelect()/EndMultiSelect() we could use IsItemToggledSelection() but here we reimplement and use our own logic. local flags = bit32.bor(TN.OpenOnArrow, TN.OpenOnDoubleClick, TN.SpanAvailWidth) if bit32.band(s.selection_mask, bit32.lshift(1, node_n)) ~= 0 then flags = bit32.bor(flags, TN.Selected) end local is_open = ImGui.TreeNodeEx(node_n, flags, "Selectable Node %d", node_n) @@ -6671,10 +7754,11 @@ function DemoWindowWidgetsTreeNodes() end end if node_clicked_idx ~= -1 then + -- Update selection state (process outside of tree loop to avoid visual inconsistencies during the clicking frame) if ImGui.GetIO().KeyCtrl then - s.selection_mask = bit32.bxor(s.selection_mask, bit32.lshift(1, node_clicked_idx)) - else - s.selection_mask = bit32.lshift(1, node_clicked_idx) + s.selection_mask = bit32.bxor(s.selection_mask, bit32.lshift(1, node_clicked_idx)) -- Ctrl+Click to toggle + else -- if not (selection_mask & (1 << node_clicked_idx)) -- Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection + s.selection_mask = bit32.lshift(1, node_clicked_idx) -- Click to single-select end end ImGui.TreePop() @@ -6701,6 +7785,7 @@ function DemoWindowWidgetsTreeNodes() for node_n = 0, 5 do local node_flags = s.adv_flags if node_n < 3 then + -- Items 0..2 are Tree Node local is_open = ImGui.TreeNodeEx(node_n, node_flags, "Selectable Node %d", node_n) if s.use_dnd and ImGui.BeginDragDropSource() then ImGui.SetDragDropPayload("MY_TREENODE_PAYLOAD_TYPE", nil, 0) @@ -6708,6 +7793,7 @@ function DemoWindowWidgetsTreeNodes() ImGui.EndDragDropSource() end if node_n == 2 and bit32.band(s.adv_flags, TN.SpanLabelWidth) ~= 0 then + -- Item 2 has an additional inline button to help demonstrate SpanLabelWidth. ImGui.SameLine() if ImGui.SmallButton("button") then end end @@ -6718,7 +7804,10 @@ function DemoWindowWidgetsTreeNodes() ImGui.TreePop() end else - node_flags = bit32.bor(node_flags, TN.Leaf, TN.NoTreePushOnOpen) + -- Items 3..5 are Tree Leaves + -- The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can + -- use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text(). + node_flags = bit32.bor(node_flags, TN.Leaf, TN.NoTreePushOnOpen) -- ImGuiTreeNodeFlags.Bullet ImGui.TreeNodeEx(node_n, node_flags, "Selectable Leaf %d", node_n) if s.use_dnd and ImGui.BeginDragDropSource() then ImGui.SetDragDropPayload("MY_TREENODE_PAYLOAD_TYPE", nil, 0) @@ -6733,6 +7822,10 @@ function DemoWindowWidgetsTreeNodes() ImGui.TreePop() end +------------------------------------------------------------------------------- +-- [SECTION] DemoWindowWidgetsVerticalSliders() +------------------------------------------------------------------------------- + S.vs = { int_value = 0, values = { 0.0, 0.60, 0.35, 0.9, 0.70, 0.20, 0.0 }, values2 = { 0.20, 0.80, 0.40, 0.25 } } function DemoWindowWidgetsVerticalSliders() if not ImGui.TreeNode("Vertical Sliders") then return end @@ -6789,11 +7882,16 @@ function DemoWindowWidgetsVerticalSliders() ImGui.TreePop() end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - ShowExampleAppMainMenuBar() +-- - ShowExampleMenuFile() +------------------------------------------------------------------------------- S.menu = { enabled = true, f = 0.5, n = 0, b = true } +-- Note that shortcuts are currently provided for display only +-- (future version will add explicit flags to BeginMenu() to request processing shortcuts) function ShowExampleMenuFile() local s = S.menu ImGui.MenuItem("(demo menu)", nil, false, false) @@ -6843,12 +7941,14 @@ function ShowExampleMenuFile() end -- Here we demonstrate appending again to the "Options" menu (which we already created above) - if ImGui.BeginMenu("Options") then + -- Of course in this demo it is a little bit silly that this function calls BeginMenu("Options") twice. + -- In a real code-base using it would make senses to use this feature from very different code locations. + if ImGui.BeginMenu("Options") then -- <-- Append! _, s.b = ImGui.Checkbox("SomeOption", s.b) ImGui.EndMenu() end - if ImGui.BeginMenu("Disabled", false) then + if ImGui.BeginMenu("Disabled", false) then -- Disabled IM_ASSERT(false) end if ImGui.MenuItem("Checked", nil, true) then end @@ -6856,6 +7956,10 @@ function ShowExampleMenuFile() if ImGui.MenuItem("Quit", "Alt+F4") then end end +-- Demonstrate creating a "main" fullscreen menu bar and populating it. +-- Note the difference between BeginMainMenuBar() and BeginMenuBar(): +-- - BeginMenuBar() = menu-bar inside current window (which needs the ImGuiWindowFlags.MenuBar flag!) +-- - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it. function ShowExampleAppMainMenuBar() if ImGui.BeginMainMenuBar() then if ImGui.BeginMenu("File") then @@ -6864,7 +7968,7 @@ function ShowExampleAppMainMenuBar() end if ImGui.BeginMenu("Edit") then if ImGui.MenuItem("Undo", "Ctrl+Z") then end - if ImGui.MenuItem("Redo", "Ctrl+Y", false, false) then end + if ImGui.MenuItem("Redo", "Ctrl+Y", false, false) then end -- Disabled item ImGui.Separator() if ImGui.MenuItem("Cut", "Ctrl+X") then end if ImGui.MenuItem("Copy", "Ctrl+C") then end @@ -6875,9 +7979,12 @@ function ShowExampleAppMainMenuBar() end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Style Editor / ShowStyleEditor() ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - ShowStyleSelector() +-- - ShowStyleEditor() +------------------------------------------------------------------------------- -- Deep copy of an ImGuiStyle (ImVec2/ImVec4 fields and Colors[] are copied by value) local function StyleCopy(dst, src) @@ -6902,7 +8009,10 @@ end local function ColorsEqual(a, b) return a[1] == b[1] and a[2] == b[2] and a[3] == b[3] and a[4] == b[4] end S.ss = { style_idx = -1 } +-- Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options. function ImGui.ShowStyleSelector(label) + -- FIXME: This is a bit tricky to get right as style are functions, they don't register a name nor the fact that one is active. + -- So we keep track of last active one among our limited selection. local s = S.ss local style_names = { "Dark", "Light", "Classic" } local ret = false @@ -6931,13 +8041,19 @@ end S.se = { ref_saved_style = nil, init = true, output_dest = 0, output_only_modified = true, alpha_flags = 0, filter = nil } function ImGui.ShowStyleEditor(ref) + -- You can pass in a reference ImGuiStyle structure to compare to, revert to and save to + -- (without a reference style, we will use one compared locally as a reference) local se = S.se local style = ImGui.GetStyle() if se.ref_saved_style == nil then se.ref_saved_style = {} end + + -- Default to using internal storage as reference if se.init and ref == nil then StyleCopy(se.ref_saved_style, style) end se.init = false if ref == nil then ref = se.ref_saved_style end + -- The logic behind dynamically changing 'max_border_size' is to not encourage people to increase border size too much: it'll likely reveal lots of subtle rendering artifacts and this isn't a priority right now. + -- Note that _MainScale is currently internal PLEASE DO NOT USE IN YOUR CODE. local default_border_size = math.floor(style._MainScale or 1.0) local max_border_size = math.max(default_border_size, 2.0) local function SF(name, mn, mx, fmt) if style[name] ~= nil then style[name] = ImGui.SliderFloat(name, style[name], mn, mx, fmt or "%.0f") end end @@ -6946,6 +8062,7 @@ function ImGui.ShowStyleEditor(ref) ImGui.PushItemWidth(ImGui.GetWindowWidth() * 0.50) + -- General ImGui.SeparatorText("General") if bit32.band(ImGui.GetIO().BackendFlags, ImGuiBackendFlags.RendererHasTextures) == 0 then ImGui.BulletText("Warning: Font scaling will NOT be smooth, because\nImGuiBackendFlags_RendererHasTextures is not set!") @@ -6957,7 +8074,7 @@ function ImGui.ShowStyleEditor(ref) if ImGui.ShowFontSelector then ImGui.ShowFontSelector("Fonts##Selector") end local changed style.FontSizeBase, changed = ImGui.DragFloat("FontSizeBase", style.FontSizeBase, 0.20, 5.0, 100.0, "%.0f") - if changed then style._NextFrameFontSizeBase = style.FontSizeBase end + if changed then style._NextFrameFontSizeBase = style.FontSizeBase end -- FIXME: Temporary hack until we finish remaining work. ImGui.SameLine(0.0, 0.0); ImGui.Text(" (out %.2f)", ImGui.GetFontSize()) style.FontScaleMain = ImGui.DragFloat("FontScaleMain", style.FontScaleMain, 0.02, 0.5, 4.0) ImGui.BeginDisabled(ImGui.GetIO().ConfigDpiScaleFonts == true) @@ -6965,8 +8082,9 @@ function ImGui.ShowStyleEditor(ref) ImGui.SetItemTooltip("When io.ConfigDpiScaleFonts is set, this value is automatically overwritten.") ImGui.EndDisabled() + -- Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0 or 1.0) style.FrameRounding, changed = ImGui.SliderFloat("FrameRounding", style.FrameRounding, 0.0, 12.0, "%.0f") - if changed then style.GrabRounding = style.FrameRounding end + if changed then style.GrabRounding = style.FrameRounding end -- Make GrabRounding always the same value as FrameRounding local p, border p, border = ImGui.Checkbox("WindowBorder", style.WindowBorderSize > 0.0); if p then style.WindowBorderSize = border and default_border_size or 0.0 end ImGui.SameLine() @@ -6974,6 +8092,7 @@ function ImGui.ShowStyleEditor(ref) ImGui.SameLine() p, border = ImGui.Checkbox("PopupBorder", style.PopupBorderSize > 0.0); if p then style.PopupBorderSize = border and default_border_size or 0.0 end + -- Save/Revert button if ImGui.Button("Save Ref") then StyleCopy(se.ref_saved_style, style); if ref ~= se.ref_saved_style then StyleCopy(ref, style) end end ImGui.SameLine() if ImGui.Button("Revert Ref") then StyleCopy(style, ref) end @@ -6995,6 +8114,7 @@ function ImGui.ShowStyleEditor(ref) ImGui.SeparatorText("Rounding") SF("WindowRounding", 0.0, 12.0); SF("ChildRounding", 0.0, 12.0); SF("FrameRounding", 0.0, 12.0) SF("PopupRounding", 0.0, 12.0); SF("GrabRounding", 0.0, 12.0); SF("MenuItemRounding", 0.0, 12.0) + -- NB: SelectableRounding is intentionally NOT made visible here. We don't want to encourage people using that. ImGui.SeparatorText("Scrollbar") SF("ScrollbarSize", 1.0, 20.0); SF("ScrollbarRounding", 0.0, 12.0); SF("ScrollbarPadding", 0.0, 10.0) @@ -7046,6 +8166,7 @@ function ImGui.ShowStyleEditor(ref) SF("LogSliderDeadzone", 0.0, 12.0); SF("ImageRounding", 0.0, 12.0); SF("ImageBorderSize", 0.0, max_border_size) ImGui.SeparatorText("Docking") + -- SetCursorPosX(GetCursorPosX() + CalcItemWidth() - GetFrameHeight()) _, style.DockingNodeHasCloseButton = ImGui.Checkbox("DockingNodeHasCloseButton", style.DockingNodeHasCloseButton) SF("DockingSeparatorSize", 0.0, 12.0) @@ -7115,6 +8236,9 @@ function ImGui.ShowStyleEditor(ref) end ImGui.ColorEdit4("##color", style.Colors[i], bit32.bor(CE.AlphaBar, se.alpha_flags)) if not ColorsEqual(style.Colors[i], ref.Colors[i]) then + -- Tips: in a real user application, you may want to merge and use an icon font into the main font, + -- so instead of "Save"/"Revert" you'd use icons! + -- Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient! ImGui.SameLine(0.0, style.ItemInnerSpacing.x); if ImGui.Button("Save") then ImVec4_Copy(ref.Colors[i], style.Colors[i]) end ImGui.SameLine(0.0, style.ItemInnerSpacing.x); if ImGui.Button("Revert") then ImVec4_Copy(style.Colors[i], ref.Colors[i]) end end @@ -7151,6 +8275,7 @@ function ImGui.ShowStyleEditor(ref) if curve_err < 0.10 then curve_err = 0.10 end style.CurveTessellationTol = curve_err * curve_err + -- When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles. style.CircleTessellationMaxError = ImGui.DragFloat("Circle Tessellation Max Error", style.CircleTessellationMaxError, 0.005, 0.10, 5.0, "%.2f", ImGuiSliderFlags.AlwaysClamp) local show_samples = ImGui.IsItemActive() if show_samples then ImGui.SetNextWindowPos(ImGui.GetCursorScreenPos()) end @@ -7163,6 +8288,8 @@ function ImGui.ShowStyleEditor(ref) local RAD_MIN, RAD_MAX = 5.0, 70.0 local rad = RAD_MIN + (RAD_MAX - RAD_MIN) * n / (8.0 - 1.0) ImGui.BeginGroup() + + -- N is not always exact here due to how PathArcTo() function work internally ImGui.Text("R: %.f\nN: %d", rad, draw_list:_CalcCircleAutoSegmentCount(rad)) local canvas_width = math.max(min_widget_width, rad * 2.0) local offset_x = math.floor(canvas_width * 0.5) @@ -7170,6 +8297,11 @@ function ImGui.ShowStyleEditor(ref) local p1 = ImGui.GetCursorScreenPos() draw_list:AddCircle(ImVec2(p1.x + offset_x, p1.y + offset_y), rad, ImGui.GetColorU32(ImGuiCol.Text)) ImGui.Dummy(ImVec2(canvas_width, RAD_MAX * 2)) + + -- local p2 = ImGui.GetCursorScreenPos() + -- draw_list:AddCircleFilled(ImVec2(p2.x + offset_x, p2.y + offset_y), rad, ImGui.GetColorU32(ImGuiCol.Text)) + -- ImGui.Dummy(ImVec2(canvas_width, RAD_MAX * 2)) + ImGui.EndGroup() ImGui.SameLine() end @@ -7177,7 +8309,7 @@ function ImGui.ShowStyleEditor(ref) end ImGui.SameLine() HelpMarker("When drawing circle primitives with \"num_segments == 0\" tessellation will be calculated automatically.") - style.Alpha = ImGui.DragFloat("Global Alpha", style.Alpha, 0.005, 0.20, 1.0, "%.2f") + style.Alpha = ImGui.DragFloat("Global Alpha", style.Alpha, 0.005, 0.20, 1.0, "%.2f") -- Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. style.DisabledAlpha = ImGui.DragFloat("Disabled Alpha", style.DisabledAlpha, 0.005, 0.0, 1.0, "%.2f") ImGui.SameLine(); HelpMarker("Additional alpha multiplier for disabled items (multiply over current value of Alpha).") ImGui.PopItemWidth() @@ -7193,9 +8325,10 @@ do --[[ About window ]] -- Demo tools: ShowAboutWindow(), ShowFontAtlas(), ShowFontSelector(), ShowDebugLogWindow(), ShowIDStackToolWindow() local _ ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] About Window / ShowAboutWindow() ----------------------------------------------------------------- +-- Access from Dear ImGui Demo -> Tools -> About +------------------------------------------------------------------------------- local show_config_info = false function ImGui.ShowAboutWindow(p_open) @@ -7226,7 +8359,7 @@ function ImGui.ShowAboutWindow(p_open) if copy_to_clipboard then ImGui.LogToClipboard() ImGui.LogText("// (Copy from the next line. Keep the ``` markers for formatting.)\n") - ImGui.LogText("```cpp\n") + ImGui.LogText("```cpp\n") -- Back quotes will make text appears without formatting when pasting on GitHub end ImGui.Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM) ImGui.Separator() diff --git a/imgui_draw.lua b/imgui_draw.lua index ada52ca..9176703 100644 --- a/imgui_draw.lua +++ b/imgui_draw.lua @@ -1,10 +1,32 @@ --- Dear ImGui WIP --- (Draw Code) +-- (drawing and font code) -FONT_ATLAS_DEFAULT_TEX_DATA_W = 122 +-- +-- Index of this file: +-- +-- [SECTION] STB libraries implementation +-- [SECTION] Style functions +-- [SECTION] ImDrawList +-- [SECTION] ImTriangulator, ImDrawList concave polygon fill +-- [SECTION] ImDrawListSplitter +-- [SECTION] ImDrawData +-- [SECTION] Helpers ShadeVertsXXX functions +-- [SECTION] ImFontConfig +-- [SECTION] ImFontAtlas, ImFontAtlasBuilder +-- [SECTION] ImFontAtlas: backend for stb_truetype +-- [SECTION] ImFontAtlas: glyph ranges helpers +-- [SECTION] ImFontGlyphRangesBuilder +-- [SECTION] ImFontBaked, ImFont +-- [SECTION] ImGui Internal Render Helpers +-- [SECTION] Decompression code +-- [SECTION] Default font data (ProggyClean.ttf) +-- [SECTION] Default font data (ProggyForever.ttf) +-- + +FONT_ATLAS_DEFAULT_TEX_DATA_W = 122 -- Actual texture will be 2 times that + 1 spacing. FONT_ATLAS_DEFAULT_TEX_DATA_H = 27 -local IM_DRAWLIST_TEX_LINES_WIDTH_MAX = 32 +local IM_DRAWLIST_TEX_LINES_WIDTH_MAX = 32 -- The maximum line width to bake anti-aliased textures for. local writef64, writeu32, readf64, readu32 = buffer.writef64, buffer.writeu32, buffer.readf64, buffer.readu32 -- Write vertex i (1-based) of a VtxBuffer.Buf @@ -14,8 +36,8 @@ local function WV(b, i, x, y, u, v, col) end local function WVP(b, i, p, uv, col) WV(b, i, p.x, p.y, uv.x, uv.y, col) end -local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE +local IM_FONTGLYPH_INDEX_UNUSED = 0xFFFF -- ((ImU16)-1) +local IM_FONTGLYPH_INDEX_NOT_FOUND = 0xFFFE -- ((ImU16)-2) --- @param str string --- @return table @@ -35,7 +57,9 @@ local function write_u32(buf, base, u32) buf[base + 3] = bit32.band(bit32.rshift(u32, 24), 0xFF) end ---- Original ImGui pixel art! +-- A work of art lies ahead! (. = white layer, X = black layer, others are blank) +-- The 2x2 white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes. +-- (This is used when io.MouseDrawCursor = true) local FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS = str_to_table( "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX - XX XX " .. "..- -X.....X- X.X - X.X -X.....X - X.....X- X..X -X..X X..X" .. @@ -83,15 +107,19 @@ local FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA = { local MT = ImGui.GetMetatables() +------------------------------------------------------------------------------- +-- [SECTION] STB libraries implementation (for stb_truetype and stb_rect_pack) +------------------------------------------------------------------------------- + --- @module "imstb_rectpack" local stbrp = IM_INCLUDE("imstb_rectpack.lua") --- @module "imstb_truetype" local stbtt = IM_INCLUDE("imstb_truetype.lua") ---------------------------------------------------------------------------------------- --- [SECTION] STYLE FUNCTIONS ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Style functions +------------------------------------------------------------------------------- --- @param a ImVec4 --- @param b ImVec4 @@ -152,8 +180,8 @@ function ImGui.StyleColorsDark(dst) colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00) colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00) colors[ImGuiCol.TableHeaderBg] = ImVec4(0.19, 0.19, 0.20, 1.00) - colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.35, 1.00) - colors[ImGuiCol.TableBorderLight] = ImVec4(0.23, 0.23, 0.25, 1.00) + colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.35, 1.00) -- Prefer using Alpha=1.0 here + colors[ImGuiCol.TableBorderLight] = ImVec4(0.23, 0.23, 0.25, 1.00) -- Prefer using Alpha=1.0 here colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00) colors[ImGuiCol.TableRowBgAlt] = ImVec4(1.00, 1.00, 1.00, 0.06) colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive] @@ -222,8 +250,8 @@ function ImGui.StyleColorsClassic(dst) colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00) colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00) colors[ImGuiCol.TableHeaderBg] = ImVec4(0.27, 0.27, 0.38, 1.00) - colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.45, 1.00) - colors[ImGuiCol.TableBorderLight] = ImVec4(0.26, 0.26, 0.28, 1.00) + colors[ImGuiCol.TableBorderStrong] = ImVec4(0.31, 0.31, 0.45, 1.00) -- Prefer using Alpha=1.0 here + colors[ImGuiCol.TableBorderLight] = ImVec4(0.26, 0.26, 0.28, 1.00) -- Prefer using Alpha=1.0 here colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00) colors[ImGuiCol.TableRowBgAlt] = ImVec4(1.00, 1.00, 1.00, 0.07) colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive] @@ -293,8 +321,8 @@ function ImGui.StyleColorsLight(dst) colors[ImGuiCol.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00) colors[ImGuiCol.PlotHistogramHovered] = ImVec4(1.00, 0.45, 0.00, 1.00) colors[ImGuiCol.TableHeaderBg] = ImVec4(0.78, 0.87, 0.98, 1.00) - colors[ImGuiCol.TableBorderStrong] = ImVec4(0.57, 0.57, 0.64, 1.00) - colors[ImGuiCol.TableBorderLight] = ImVec4(0.68, 0.68, 0.74, 1.00) + colors[ImGuiCol.TableBorderStrong] = ImVec4(0.57, 0.57, 0.64, 1.00) -- Prefer using Alpha=1.0 here + colors[ImGuiCol.TableBorderLight] = ImVec4(0.68, 0.68, 0.74, 1.00) -- Prefer using Alpha=1.0 here colors[ImGuiCol.TableRowBg] = ImVec4(0.00, 0.00, 0.00, 0.00) colors[ImGuiCol.TableRowBgAlt] = ImVec4(0.30, 0.30, 0.30, 0.09) colors[ImGuiCol.TextLink] = colors[ImGuiCol.HeaderActive] @@ -309,6 +337,11 @@ function ImGui.StyleColorsLight(dst) colors[ImGuiCol.ModalWindowDimBg] = ImVec4(0.20, 0.20, 0.20, 0.35) end +------------------------------------------------------------------------------- +-- [SECTION] Helpers ShadeVertsXXX functions +------------------------------------------------------------------------------- + +-- Generic linear color gradient, write to RGB fields, leave A untouched. --- @param draw_list ImDrawList --- @param vert_start_idx int --- @param vert_end_idx int @@ -441,10 +474,102 @@ local ImTextClassifierSetCharClassFromStr local ImTextureDataGetFormatBytesPerPixel +------------------------------------------------------------------------------- +-- [SECTION] ImFontAtlas, ImFontAtlasBuilder +------------------------------------------------------------------------------- +-- - Default texture data encoded in ASCII +-- - ImFontAtlas() +-- - ImFontAtlas:Clear() +-- - ImFontAtlas:ClearFonts() +-- - ImFontAtlas:ClearInputData() +-- - ImFontAtlas:ClearTexData() +-- - ImFontAtlas:CompactCache() +-- - ImFontAtlas:SetFontLoader() +------------------------------------------------------------------------------- +-- - ImFontAtlasUpdateNewFrame() +-- - ImFontAtlasTextureBlockConvert() +-- - ImFontAtlasTextureBlockPostProcess() +-- - ImFontAtlasTextureBlockPostProcessMultiply() +-- - ImFontAtlasTextureBlockFill() +-- - ImFontAtlasTextureBlockCopy() +-- - ImFontAtlasTextureBlockQueueUpload() +------------------------------------------------------------------------------- +-- - ImFontAtlas:GetTexDataAsAlpha8() [legacy] +-- - ImFontAtlas:GetTexDataAsRGBA32() [legacy] +-- - ImFontAtlas:Build() [legacy] +------------------------------------------------------------------------------- +-- - ImFontAtlas:AddFont() +-- - ImFontAtlas:AddFontDefault() +-- - ImFontAtlas:AddFontDefaultBitmap() +-- - ImFontAtlas:AddFontDefaultVector() +-- - ImFontAtlas:AddFontFromFileTTF() +-- - ImFontAtlas:AddFontFromMemoryTTF() +-- - ImFontAtlas:AddFontFromMemoryCompressedTTF() +-- - ImFontAtlas:AddFontFromMemoryCompressedBase85TTF() +-- - ImFontAtlas:RemoveFont() +-- - ImFontAtlasBuildNotifySetFont() +------------------------------------------------------------------------------- +-- - ImFontAtlas:AddCustomRect() +-- - ImFontAtlas:RemoveCustomRect() +-- - ImFontAtlas:GetCustomRect() +-- - ImFontAtlas:AddCustomRectFontGlyph() [legacy] +-- - ImFontAtlas:AddCustomRectFontGlyphForSize() [legacy] +-- - ImFontAtlasGetMouseCursorTexData() +------------------------------------------------------------------------------- +-- - ImFontAtlasBuildMain() +-- - ImFontAtlasBuildSetupFontLoader() +-- - ImFontAtlasBuildPreloadAllGlyphRanges() +-- - ImFontAtlasBuildUpdatePointers() +-- - ImFontAtlasBuildRenderBitmapFromString() +-- - ImFontAtlasBuildAddFont() +-- - ImFontAtlasBuildSetupFontBakedEllipsis() +-- - ImFontAtlasBuildSetupFontBakedBlanks() +-- - ImFontAtlasBuildSetupFontBakedFallback() +-- - ImFontAtlasBuildSetupFontSpecialGlyphs() +-- - ImFontAtlasBuildDiscardBakes() +-- - ImFontAtlasBuildDiscardFontBakedGlyph() +-- - ImFontAtlasBuildDiscardFontBaked() +-- - ImFontAtlasBuildDiscardFontBakes() +------------------------------------------------------------------------------- +-- - ImFontAtlasAddDrawListSharedData() +-- - ImFontAtlasRemoveDrawListSharedData() +-- - ImFontAtlasUpdateDrawListsTextures() +-- - ImFontAtlasUpdateDrawListsSharedData() +------------------------------------------------------------------------------- +-- - ImFontAtlasBuildSetTexture() +-- - ImFontAtlasBuildUpdateTexData() +-- - ImFontAtlasTextureAdd() +-- - ImFontAtlasTextureRepack() +-- - ImFontAtlasTextureGrow() +-- - ImFontAtlasTextureMakeSpace() +-- - ImFontAtlasTextureGetSizeEstimate() +-- - ImFontAtlasBuildClear() +-- - ImFontAtlasTextureCompact() +-- - ImFontAtlasBuildInit() +-- - ImFontAtlasBuildDestroy() +------------------------------------------------------------------------------- +-- - ImFontAtlasPackInit() +-- - ImFontAtlasPackAllocRectEntry() +-- - ImFontAtlasPackReuseRectEntry() +-- - ImFontAtlasPackDiscardRect() +-- - ImFontAtlasPackAddRect() +-- - ImFontAtlasPackGetRect() +------------------------------------------------------------------------------- +-- - ImFontBaked_BuildGrowIndex() +-- - ImFontBaked_BuildLoadGlyph() +-- - ImFontBaked_BuildLoadGlyphAdvanceX() +-- - ImFontAtlasDebugLogTextureRequests() +------------------------------------------------------------------------------- +-- - ImFontAtlasGetFontLoaderForStbTruetype() +------------------------------------------------------------------------------- + +-- You probably should not call this directly. It is not well specified. +-- If you want to replace all your fonts mid-frame, most likely you should instead call ClearFonts() then load the new fonts. +-- Calling this mid-frame will discard the CPU-side copy of the texture data which is generally unreliable as you may have textures queued for creation or updates. function MT.ImFontAtlas:Clear() IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlas:Clear()") local backup_renderer_has_textures = self.RendererHasTextures - self.RendererHasTextures = false + self.RendererHasTextures = false -- Full Clear() is supported, but ClearTexData() only isn't. self:ClearFonts() self:ClearTexData() self.RendererHasTextures = backup_renderer_has_textures @@ -464,12 +589,14 @@ function MT.ImFontAtlas:ClearInputData() ImFontAtlasFontDestroySourceData(self, font_cfg) end for _, font in self.Fonts:iter() do + -- When clearing this we lose access to the font name and other information used to build the font. font.Sources:clear() font.Flags = bit32.bor(font.Flags, ImFontFlags.NoLoadGlyphs) end self.Sources:clear() end +-- Clear CPU-side copy of the texture data. function MT.ImFontAtlas:ClearTexData() IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") IM_ASSERT(self.RendererHasTextures == false, "Not supported for dynamic atlases, but you may call Clear().") @@ -477,6 +604,7 @@ function MT.ImFontAtlas:ClearTexData() for _, tex in self.TexList:iter() do tex:DestroyPixels() end + --self.Locked = true -- Hoped to be able to lock this down but some reload patterns may not be happy with it. end function MT.ImFontAtlas:CompactCache() @@ -484,6 +612,7 @@ function MT.ImFontAtlas:CompactCache() end function MT.ImFontAtlas:ClearFonts() + -- FIXME-NEWATLAS: Illegal to remove currently bound font. IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlas:ClearFonts()") IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") @@ -514,25 +643,34 @@ function ImTextureDataUpdateNewFrame(tex) tex.UpdateRect.w = 0 tex.UpdateRect.h = 0 end + -- 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. if (tex.WantDestroyNextFrame and tex.Status ~= ImTextureStatus.Destroyed and tex.Status ~= ImTextureStatus.WantDestroy) then IM_ASSERT(tex.Status == ImTextureStatus.OK or tex.Status == ImTextureStatus.WantCreate or tex.Status == ImTextureStatus.WantUpdates) tex.Status = ImTextureStatus.WantDestroy end + -- If a texture has never reached the backend, they don't need to know about it. + -- (note: backends between 1.92.0 and 1.92.4 could set an already destroyed texture to ImTextureStatus.WantDestroy + -- when invalidating graphics objects twice, which would previously remove it from the list and crash.) if (tex.Status == ImTextureStatus.WantDestroy and tex.TexID == ImTextureID_Invalid and tex.BackendUserData == nil and tex.QueueUserData == nil) then tex.Status = ImTextureStatus.Destroyed end + -- Process texture being destroyed if (tex.Status == ImTextureStatus.Destroyed) then IM_ASSERT(tex.TexID == ImTextureID_Invalid and tex.BackendUserData == nil, "Backend set texture Status to Destroyed but did not clear TexID/BackendUserData!") IM_ASSERT(tex.QueueUserData == nil, "Texture queue set Status to Destroyed but did not clear QueueUserData!") if (tex.WantDestroyNextFrame) then - remove_from_list = true + remove_from_list = true -- Destroy was scheduled by us else - tex.Status = ImTextureStatus.WantCreate + tex.Status = ImTextureStatus.WantCreate -- Destroy was done was backend: recreate it (e.g. freed resources mid-run) end end + -- 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) then tex.UnusedFrames = tex.UnusedFrames + 1 end @@ -540,15 +678,24 @@ function ImTextureDataUpdateNewFrame(tex) return remove_from_list end +-- 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. --- @param atlas ImFontAtlas --- @param frame_count int --- @param renderer_has_textures any function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures) - IM_ASSERT(atlas.Builder == nil or atlas.Builder.FrameCount < frame_count) + IM_ASSERT(atlas.Builder == nil or atlas.Builder.FrameCount < frame_count) -- Protection against being called twice. atlas.RendererHasTextures = renderer_has_textures + -- Update texture status and discard old textures. + -- (we do this first thing to handle an edge case: if user mistakenly calls ClearFonts()+SetStatus(OK) during + -- rendering, it would ImFontAtlasBuildMain() rebuilding before tex.Updates[] gets a chance to be cleared) + -- (if somehow we need to move this back lower in the function, we could manually call the code to clear Updates[]). local tex_n = 1 while tex_n <= atlas.TexList.Size do + -- Update and remove if requested local tex = atlas.TexList.Data[tex_n] if (tex.Status == ImTextureStatus.WantCreate and atlas.RendererHasTextures) then @@ -567,13 +714,14 @@ function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures) tex_n = tex_n + 1 end + -- Check that font atlas was built or backend support texture reload in which case we can build now if (atlas.RendererHasTextures) then atlas.TexIsBuilt = true - if (atlas.Builder == nil) then + if (atlas.Builder == nil) then -- This will only happen if fonts were not already loaded. ImFontAtlasBuildMain(atlas) end end - + -- Legacy backend if (not atlas.RendererHasTextures) then 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().") end @@ -581,12 +729,15 @@ function ImFontAtlasUpdateNewFrame(atlas, frame_count, renderer_has_textures) 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().") end + -- Clear BakedCurrent cache, this is important because it ensure the uncached path gets taken once. + -- We also rely on ImFontBaked pointers never crossing frames. local builder = atlas.Builder builder.FrameCount = frame_count for _, font in atlas.Fonts:iter() do font.LastBaked = nil end + -- Garbage collect BakedPool if builder.BakedDiscardedCount > 0 then local dst_n = 1 @@ -667,8 +818,11 @@ function ImFontAtlasTextureBlockConvert(src_pixels, src_fmt, src_pitch, dst_pixe end end +-- Source buffer may be written to (used for in-place mods). +-- Post-process hooks may eventually be added here. --- @param data ImFontAtlasPostProcessData function ImFontAtlasTextureBlockPostProcess(data) + -- Multiply operator (legacy) if data.FontSrc.RasterizerMultiply ~= 1.0 then ImFontAtlasTextureBlockPostProcessMultiply(data, data.FontSrc.RasterizerMultiply) end @@ -709,6 +863,7 @@ function ImFontAtlasTextureBlockPostProcessMultiply(data, multiply_factor) end end +-- Copy block from one texture to another --- @param src_tex ImTextureData --- @param src_x int --- @param src_y int @@ -731,6 +886,7 @@ function ImFontAtlasTextureBlockCopy(src_tex, src_x, src_y, dst_tex, dst_x, dst_ end end +-- Queue texture block update for renderer backend --- @param tex ImTextureData --- @param x int --- @param y int @@ -752,6 +908,7 @@ local function ImTextureDataQueueUpload(tex, x, y, w, h) tex.UsedRect.w = (ImMax(tex.UsedRect.x + tex.UsedRect.w, req.x + req.w) - tex.UsedRect.x) -- (unsigned short) tex.UsedRect.h = (ImMax(tex.UsedRect.y + tex.UsedRect.h, req.y + req.h) - tex.UsedRect.y) -- (unsigned short) + -- No need to queue if status is == ImTextureStatus.WantCreate if (tex.Status == ImTextureStatus.OK or tex.Status == ImTextureStatus.WantUpdates) then tex.Status = ImTextureStatus.WantUpdates tex.Updates:push_back(req) @@ -769,6 +926,7 @@ function ImFontAtlasTextureBlockQueueUpload(atlas, tex, x, y, w, h) atlas.TexIsBuilt = false end +-- Copy to texture, post-process and queue update for backend --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @param src ImFontConfig @@ -789,6 +947,8 @@ local function ImFontAtlasBakedSetFontGlyphBitmap(atlas, baked, src, glyph, r, s end local function ImFontAtlasBuildGetOversampleFactors(src, baked) + -- (Only used by stb_truetype builder) + -- Automatically disable horizontal oversampling over size 36 local raster_size = baked.Size * baked.RasterizerDensity * src.RasterizerDensity local out_oversample_h if src.OversampleH ~= 0 then @@ -802,6 +962,7 @@ local function ImFontAtlasBuildGetOversampleFactors(src, baked) return out_oversample_h, out_oversample_v end +-- use unused_frames==0 to discard everything. local function ImFontAtlasBuildDiscardBakes(atlas, unused_frames) local builder = atlas.Builder @@ -822,6 +983,7 @@ local function ImFontAtlasBuildDiscardBakes(atlas, unused_frames) end end +-- Those functions are designed to facilitate changing the underlying structures for ImFontAtlas to store an array of ImDrawListSharedData --- @param atlas ImFontAtlas --- @param data ImDrawListSharedData function ImFontAtlasAddDrawListSharedData(atlas, data) @@ -848,7 +1010,16 @@ local function ImFontAtlasTextureRepack(atlas, w, h) new_tex.UseColors = old_tex.UseColors IMGUI_DEBUG_LOG_FONT("[font] Texture #%03d: resize+repack %dx%d => Texture #%03d: %dx%d", old_tex.UniqueID, old_tex.Width, old_tex.Height, new_tex.UniqueID, new_tex.Width, new_tex.Height) + --for baked_n = 1, builder.BakedPool.Size do + -- IMGUI_DEBUG_LOG_FONT("[font] - Baked %.2fpx, %d glyphs, want_destroy=%d", builder.BakedPool[baked_n].FontSize, builder.BakedPool[baked_n].Glyphs.Size, builder.BakedPool[baked_n].WantDestroy) + --end + --IMGUI_DEBUG_LOG_FONT("[font] - Old packed rects: %d, area %d px", 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) local old_rects = ImVector() local old_index = builder.RectsIndex:copy() @@ -867,13 +1038,15 @@ local function ImFontAtlasTextureRepack(atlas, w, h) local new_r_id = ImFontAtlasPackAddRect(atlas, old_r.w, old_r.h, index_entry) if new_r_id == ImFontAtlasRectId_Invalid then + -- 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.", new_tex.UniqueID) new_tex.WantDestroyNextFrame = true builder.Rects:swap(old_rects) builder.RectsIndex = old_index ImFontAtlasBuildSetTexture(atlas, old_tex) - ImFontAtlasTextureGrow(atlas, w, h) + ImFontAtlasTextureGrow(atlas, w, h) -- Recurse return end @@ -889,6 +1062,7 @@ local function ImFontAtlasTextureRepack(atlas, w, h) builder.RectsDiscardedCount = 0 builder.RectsDiscardedSurface = 0 + -- Patch glyphs UV for baked_n = 1, builder.BakedPool.Size do for _, glyph in builder.BakedPool[baked_n].Glyphs:iter() do if (glyph.PackId ~= ImFontAtlasRectId_Invalid) then @@ -901,14 +1075,16 @@ local function ImFontAtlasTextureRepack(atlas, w, h) end end + -- Update other cached UV ImFontAtlasBuildUpdateTexData(atlas) builder.LockDisableResize = false ImFontAtlasUpdateDrawListsSharedData(atlas) - -- ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack"); + --ImFontAtlasDebugWriteTexToDisk(new_tex, "After Pack") end function ImFontAtlasTextureGrow(atlas, old_tex_w, old_tex_h) + --ImFontAtlasDebugWriteTexToDisk(atlas.TexData, "Before Grow") local builder = atlas.Builder old_tex_w = old_tex_w or -1 @@ -921,12 +1097,18 @@ function ImFontAtlasTextureGrow(atlas, old_tex_w, old_tex_h) old_tex_h = atlas.TexData.Height end + -- 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) and ImIsPowerOfTwo(old_tex_h)) IM_ASSERT(ImIsPowerOfTwo(atlas.TexMinWidth) and ImIsPowerOfTwo(atlas.TexMaxWidth) and ImIsPowerOfTwo(atlas.TexMinHeight) and 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. local new_tex_w = (old_tex_h <= old_tex_w) and old_tex_w or old_tex_w * 2 local new_tex_h = (old_tex_h <= old_tex_w) and old_tex_h * 2 or old_tex_h + -- Handle minimum size first (for pathologically large packed rects) local 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)) @@ -941,9 +1123,12 @@ end --- @param atlas ImFontAtlas local function ImFontAtlasTextureMakeSpace(atlas) + -- Can some baked contents be ditched? + --IMGUI_DEBUG_LOG_FONT("[font] ImFontAtlasBuildMakeSpace()") local builder = atlas.Builder ImFontAtlasBuildDiscardBakes(atlas, 2) + -- Currently using a heuristic for repack without growing. if (builder.RectsDiscardedSurface < builder.RectsPackedSurface * 0.20) then ImFontAtlasTextureGrow(atlas) else @@ -951,6 +1136,7 @@ local function ImFontAtlasTextureMakeSpace(atlas) end end +-- This is essentially a free-list pattern, it may be nice to wrap it into a dedicated type. --- @param atlas ImFontAtlas --- @param rect_idx ImFontAtlasRectId local function ImFontAtlasPackAllocRectEntry(atlas, rect_idx) @@ -964,7 +1150,7 @@ local function ImFontAtlasPackAllocRectEntry(atlas, rect_idx) else index_idx = builder.RectsIndexFreeListStart index_entry = builder.RectsIndex[index_idx + 1] - IM_ASSERT(index_entry.IsUsed == false and index_entry.Generation > 0) + IM_ASSERT(index_entry.IsUsed == false and index_entry.Generation > 0) -- Generation is incremented during DiscardRect builder.RectsIndexFreeListStart = index_entry.TargetIndex end @@ -974,6 +1160,7 @@ local function ImFontAtlasPackAllocRectEntry(atlas, rect_idx) return ImFontAtlasRectId_Make(index_idx, index_entry.Generation) end +-- Overwrite existing entry --- @param atlas ImFontAtlas --- @param index_entry ImFontAtlasRectEntry local function ImFontAtlasPackReuseRectEntry(atlas, index_entry) @@ -983,6 +1170,7 @@ local function ImFontAtlasPackReuseRectEntry(atlas, index_entry) return ImFontAtlasRectId_Make(index_idx, index_entry.Generation) end +-- This is expected to be called in batches and followed by a repack --- @param atlas ImFontAtlas --- @param id ImFontAtlasRectId function ImFontAtlasPackDiscardRect(atlas, id) @@ -1001,16 +1189,18 @@ function ImFontAtlasPackDiscardRect(atlas, id) index_entry.TargetIndex = builder.RectsIndexFreeListStart index_entry.Generation = index_entry.Generation + 1 if (index_entry.Generation == 0) then - index_entry.Generation = index_entry.Generation + 1 + index_entry.Generation = index_entry.Generation + 1 -- Keep non-zero on overflow end local pack_padding = atlas.TexGlyphPadding builder.RectsIndexFreeListStart = index_idx builder.RectsDiscardedCount = builder.RectsDiscardedCount + 1 builder.RectsDiscardedSurface = builder.RectsDiscardedSurface + ((rect.w + pack_padding) * (rect.h + pack_padding)) - rect.w = 0 rect.h = 0 + rect.w = 0 rect.h = 0 -- Clear rectangle so it won't be packed again end +-- 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 function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) IM_ASSERT(w > 0 and w <= 0xFFFF) IM_ASSERT(h > 0 and h <= 0xFFFF) @@ -1020,8 +1210,10 @@ function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) builder.MaxRectSize.x = ImMax(builder.MaxRectSize.x, w) builder.MaxRectSize.y = ImMax(builder.MaxRectSize.y, h) + -- Pack local r = ImTextureRect(0, 0, w, h) for attempts_remaining = 3, 0, -1 do + -- Try packing local pack_r = stbrp.rect() pack_r.w = w + pack_padding pack_r.h = h + pack_padding @@ -1032,12 +1224,14 @@ function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) break end + -- If we ran out of attempts, return fallback if (attempts_remaining == 0 or builder.LockDisableResize) then IMGUI_DEBUG_LOG_FONT("[font] Failed packing %dx%d rectangle. Returning fallback.", w, h) return ImFontAtlasRectId_Invalid end + -- Resize or repack atlas! (this should be a rare event) ImFontAtlasTextureMakeSpace(atlas) end @@ -1048,12 +1242,13 @@ function ImFontAtlasPackAddRect(atlas, w, h, overwrite_entry) builder.Rects:push_back(r) if (overwrite_entry ~= nil) then - return ImFontAtlasPackReuseRectEntry(atlas, overwrite_entry) + 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) end end +-- Generally for non-user facing functions: assert on invalid ID. --- @param atlas ImFontAtlas --- @param id ImFontAtlasRectId --- @return ImTextureRect @@ -1068,6 +1263,8 @@ function ImFontAtlasPackGetRect(atlas, id) return builder.Rects.Data[index_entry.TargetIndex + 1] end +-- For user-facing functions: return nil on invalid ID. +-- Important: return value is valid until next call to AddRect(), e.g. FindGlyph(), CalcTextSize() can all potentially invalidate previous rects. --- @param atlas ImFontAtlas --- @param id ImFontAtlasRectId function ImFontAtlasPackGetRectSafe(atlas, id) @@ -1090,6 +1287,8 @@ function ImFontAtlasPackGetRectSafe(atlas, id) return builder.Rects.Data[index_entry.TargetIndex + 1] end +-- 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. --- @param src ImFontConfig --- @param codepoint ImWchar --- @return bool @@ -1120,6 +1319,13 @@ function ImFontBaked_BuildGrowIndex(baked, new_size) baked.IndexLookup:resize(new_size, IM_FONTGLYPH_INDEX_UNUSED) end +------------------------------------------------------------------------------- +-- [SECTION] ImFontAtlas: backend for stb_truetype +------------------------------------------------------------------------------- +-- (imstb_truetype.lua in included near the top of this file) +------------------------------------------------------------------------------- + +-- One for each ConfigData --- @class ImGui_ImplStbTrueType_FontSrcData --- @field FontInfo stbtt_fontinfo --- @field ScaleFactor float @@ -1147,6 +1353,7 @@ local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) local bd_font_data = ImGui_ImplStbTrueType_FontSrcData() IM_ASSERT(src.FontLoaderData == nil) + -- Initialize helper structure for font loading and verify that the TTF/OTF data is correct local font_offset = stbtt.GetFontOffsetForIndex(src.FontData, src.FontNo) if font_offset < 0 then bd_font_data = nil @@ -1167,7 +1374,7 @@ local function ImGui_ImplStbTrueType_FontSrcInit(atlas, src) bd_font_data.ScaleFactor = stbtt.ScaleForPixelHeight(bd_font_data.FontInfo, 1.0) if (src.MergeMode and src.SizePixels ~= 0.0 and ref_size ~= 0.0) then - bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * (src.SizePixels / ref_size) + bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * (src.SizePixels / ref_size) -- FIXME-NEWATLAS: Should tidy up that a bit end bd_font_data.ScaleFactor = bd_font_data.ScaleFactor * src.ExtraSizeScale @@ -1193,11 +1400,14 @@ local function ImGui_ImplStbTrueType_FontBakedInit(atlas, src, baked) local bd_font_data = src.FontLoaderData if (src.MergeMode == false) then + -- FIXME-NEWFONTS: reevaluate how to use sizing metrics + -- FIXME-NEWFONTS: make use of line gap value local scale_for_layout = bd_font_data.ScaleFactor * baked.Size / src.ExtraSizeScale local unscaled_ascent, unscaled_descent, unscaled_line_gap = stbtt.GetFontVMetrics(bd_font_data.FontInfo) baked.Ascent = ImCeil(unscaled_ascent * scale_for_layout) baked.Descent = ImFloor(unscaled_descent * scale_for_layout) + -- FIXME: round to rasterizer density? (#9348) end return true @@ -1213,6 +1423,7 @@ end --- @return bool --- @return float? out_advance_x # Updated `advance_x` local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, codepoint, out_glyph, advance_x) + -- Search for first font which has the glyph local bd_font_data = src.FontLoaderData IM_ASSERT(bd_font_data ~= nil) local glyph_index = stbtt.FindGlyphIndex(bd_font_data.FontInfo, codepoint) @@ -1220,15 +1431,18 @@ local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, co return false, advance_x end + -- Fonts unit to pixels local oversample_h, oversample_v = ImFontAtlasBuildGetOversampleFactors(src, baked) local scale_for_layout = bd_font_data.ScaleFactor * baked.Size local rasterizer_density = src.RasterizerDensity * baked.RasterizerDensity local scale_for_raster_x = bd_font_data.ScaleFactor * baked.Size * rasterizer_density * oversample_h local scale_for_raster_y = bd_font_data.ScaleFactor * baked.Size * rasterizer_density * oversample_v + -- Obtain size and advance local x0, y0, x1, y1 = stbtt.GetGlyphBitmapBoxSubpixel(bd_font_data.FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y, 0, 0) local advance, lsb = stbtt.GetGlyphHMetrics(bd_font_data.FontInfo, glyph_index) + -- Load metrics only mode if (advance_x ~= nil) then IM_ASSERT(out_glyph == nil) advance_x = advance * scale_for_layout @@ -1236,9 +1450,12 @@ local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, co return true, advance_x end + -- Prepare glyph out_glyph.Codepoint = codepoint out_glyph.AdvanceX = advance * scale_for_layout + -- Pack and retrieve position inside texture atlas + -- (generally based on stbtt_PackFontRangesRenderIntoRects) local is_visible = (x0 ~= x1 and y0 ~= y1) if is_visible then local w = (x1 - x0 + oversample_h - 1) @@ -1252,23 +1469,30 @@ local function ImGui_ImplStbTrueType_FontBakedLoadGlyph(atlas, src, baked, _, co local r = ImFontAtlasPackGetRect(atlas, pack_id) + -- Render x0, y0, x1, y1 = stbtt.GetGlyphBitmapBox(bd_font_data.FontInfo, glyph_index, scale_for_raster_x, scale_for_raster_y) local builder = atlas.Builder builder.TempBuffer:resize(w * h * 1) local bitmap_pixels = builder.TempBuffer.Data ImStd.memset(bitmap_pixels, 0, w * h * 1) + + -- Render with oversampling + -- (those functions conveniently assert if pixels are not cleared, which is another safety layer) local 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, glyph_index) local ref_size = baked.OwnerFont.Sources[1].SizePixels local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0 - local font_off_x = ImFloor(src.GlyphOffset.x * offsets_scale + 0.5) + local font_off_x = ImFloor(src.GlyphOffset.x * offsets_scale + 0.5) -- Snap scaled offset. local font_off_y = ImFloor(src.GlyphOffset.y * offsets_scale + 0.5) font_off_x = font_off_x + sub_x font_off_y = font_off_y + (sub_y + IM_ROUND(baked.Ascent)) local recip_h = 1.0 / (oversample_h * rasterizer_density) local recip_v = 1.0 / (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 + r.w) * recip_h + font_off_x @@ -1300,11 +1524,14 @@ end --- @param atlas ImFontAtlas --- @param baked ImFontBaked function ImFontAtlasBuildSetupFontBakedBlanks(atlas, 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) local space_glyph = baked:FindGlyphNoFallback(32) if space_glyph ~= nil then space_glyph.Visible = false end + -- 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(9) == nil and space_glyph ~= nil then local tab_glyph = ImFontGlyph() tab_glyph.Codepoint = 9 @@ -1330,8 +1557,9 @@ function ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, ba baked.OwnerFont = font baked.LastUsedFrame = atlas.Builder.FrameCount + -- Initialize backend data local loader_data_size = 0 - for _, src in font.Sources:iter() do + for _, src in font.Sources:iter() do -- Cannot easily be cached as we allow changing backend local loader = src.FontLoader and src.FontLoader or atlas.FontLoader loader_data_size = loader_data_size + loader.FontBakedSrcLoaderDataSize end @@ -1349,6 +1577,7 @@ function ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, ba return baked end +-- 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. --- @param atlas ImFontAtlas --- @param font ImFont --- @param font_size float @@ -1367,7 +1596,7 @@ function ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer break end - if (step_n == 0 and baked.RasterizerDensity ~= font_rasterizer_density) then + if (step_n == 0 and baked.RasterizerDensity ~= font_rasterizer_density) then -- First try with same density break end @@ -1424,9 +1653,10 @@ function ImFontAtlasBakedDiscard(atlas, font, baked) font.LastBaked = nil end +-- use unused_frames==0 to discard everything. function ImFontAtlasFontDiscardBakes(atlas, font, unused_frames) local builder = atlas.Builder - if builder then + if builder then -- This can be called from font destructor for baked_n = 1, builder.BakedPool.Size do repeat local baked = builder.BakedPool[baked_n] @@ -1445,6 +1675,7 @@ function ImFontAtlasFontDiscardBakes(atlas, font, unused_frames) end end +-- Was tempted to lazily init FontSrc but wouldn't save much + makes it more complicated to detect invalid data at AddFont() function ImFontAtlasFontInitOutput(atlas, font) local ret = true for _, src in font.Sources:iter() do @@ -1452,10 +1683,11 @@ function ImFontAtlasFontInitOutput(atlas, font) ret = false end end - IM_ASSERT(ret) + IM_ASSERT(ret) -- Unclear how to react to this meaningfully. Assume that result will be same as initial AddFont() call. return ret end +-- Keep source/input FontData function ImFontAtlasFontDestroyOutput(atlas, font) font:ClearOutputData() for _, src in font.Sources:iter() do @@ -1483,10 +1715,11 @@ end function ImFontAtlasFontSourceAddToFont(atlas, font, src) if src.MergeMode == false then font:ClearOutputData() + --font.FontSize = src.SizePixels font.OwnerAtlas = atlas IM_ASSERT(font.Sources[1] == src) end - atlas.TexIsBuilt = false + atlas.TexIsBuilt = false -- For legacy backends ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) end @@ -1505,6 +1738,8 @@ function ImFontAtlasFontDestroySourceData(atlas, src) src.GlyphExcludeRanges = nil end +-- Load/identify special glyphs +-- (note that this is called again for fonts with MergeMode) --- @param atlas ImFontAtlas --- @param font ImFont --- @param src ImFontConfig @@ -1512,6 +1747,7 @@ function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) -- IM_UNUSED(atlas) IM_ASSERT(font.Sources:contains(src)) + -- Find Fallback character. Actual glyph loaded in GetFontBaked(). --- @type ImWchar[] local fallback_chars = {font.FallbackChar, IM_UNICODE_CODEPOINT_INVALID, 63, 32} if font.FallbackChar == 0 then @@ -1524,6 +1760,9 @@ function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) end end + -- 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. --- @type ImWchar[] local ellipsis_chars = {src.EllipsisChar, 0x2026, 0x0085} if font.EllipsisChar == 0 then @@ -1542,6 +1781,9 @@ function ImFontAtlasBuildSetupFontSpecialGlyphs(atlas, font, src) end end +-- 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. --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @return ImFontGlyph? @@ -1556,7 +1798,7 @@ function ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) if (dot_glyph == nil) then return nil end - local dot_r_id = dot_glyph.PackId + local dot_r_id = dot_glyph.PackId -- Deep copy to avoid invalidation of glyphs and rect pointers local dot_r = ImFontAtlasPackGetRect(atlas, dot_r_id) local dot_spacing = 1 local dot_step = (dot_glyph.X1 - dot_glyph.X0) + dot_spacing @@ -1566,7 +1808,7 @@ function ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) local glyph = ImFontGlyph() glyph.Codepoint = font.EllipsisChar - glyph.AdvanceX = ImMax(dot_glyph.AdvanceX, dot_glyph.X0 + dot_step * 3.0 - dot_spacing) + glyph.AdvanceX = ImMax(dot_glyph.AdvanceX, dot_glyph.X0 + dot_step * 3.0 - 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 @@ -1586,6 +1828,8 @@ function ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) return glyph end +-- 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) --- @param baked ImFontBaked function ImFontAtlasBuildSetupFontBakedFallback(baked) IM_ASSERT(baked.FallbackGlyphIndex == -1) @@ -1602,10 +1846,12 @@ function ImFontAtlasBuildSetupFontBakedFallback(baked) glyph.AdvanceX = space_glyph and space_glyph.AdvanceX or IM_ROUND(baked.Size * 0.40) fallback_glyph = ImFontAtlasBakedAddFontGlyph(font.OwnerAtlas, baked, nil, glyph) end - baked.FallbackGlyphIndex = baked.Glyphs:index_from_ptr(fallback_glyph) + 1 + baked.FallbackGlyphIndex = baked.Glyphs:index_from_ptr(fallback_glyph) + 1 -- Storing index avoid need to update pointer on growth and simplify inner loop code baked.FallbackAdvanceX = fallback_glyph.AdvanceX end +-- Setup main font loader for the atlas +-- Every font source (ImFontConfig) will use this unless ImFontConfig.FontLoader specify a custom loader. function ImFontAtlasBuildSetupFontLoader(atlas, font_loader) if atlas.FontLoader == font_loader then return @@ -1637,6 +1883,11 @@ function ImFontAtlasBuildSetupFontLoader(atlas, font_loader) end local function ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas) + -- [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 _, shared_data in atlas.DrawListSharedDatas:iter() do local imgui_ctx = shared_data.Context if (imgui_ctx) then @@ -1656,21 +1907,27 @@ local function ImFontAtlasBuildUpdatePointers(atlas) -- end end +-- Update texture identifier in all active draw lists --- @param atlas ImFontAtlas --- @param old_tex ImTextureRef --- @param new_tex ImTextureRef local function ImFontAtlasUpdateDrawListsTextures(atlas, old_tex, new_tex) for _, shared_data in atlas.DrawListSharedDatas:iter() do repeat + -- If Context 2 uses font owned by Context 1 which already called EndFrame()/Render(), we don't want to mess with draw commands for Context 1 if (shared_data.Context and not shared_data.Context.WithinFrameScope) then break end for _, draw_list in shared_data.DrawLists:iter() do + -- 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 and draw_list._CmdHeader.TexRef == old_tex) then draw_list:_SetTexture(new_tex) end + -- Replace in stack for i, stacked_tex in draw_list._TextureStack:iter() do if (stacked_tex == old_tex) then draw_list._TextureStack.Data[i] = new_tex @@ -1682,12 +1939,13 @@ local function ImFontAtlasUpdateDrawListsTextures(atlas, old_tex, new_tex) end end +-- Set current texture. This is mostly called from AddTexture() + to handle a failed resize. function ImFontAtlasBuildSetTexture(atlas, tex) local old_tex_ref = atlas.TexRef atlas.TexData = tex atlas.TexUvScale = ImVec2(1.0 / tex.Width, 1.0 / 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. + --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) end @@ -1697,17 +1955,28 @@ function ImFontAtlasBuildUpdateTexData(atlas) ImFontAtlasBuildUpdateTexDataBasic(atlas) end +-- Create a new texture, discard previous one function ImFontAtlasTextureAdd(atlas, w, h) local old_tex = atlas.TexData local new_tex -- FIXME: Cannot reuse texture because old UV may have been used already (unless we remap UV). + --if (old_tex ~= nil and old_tex.Status == ImTextureStatus.WantCreate) then + -- -- Reuse texture not yet used by backend. + -- IM_ASSERT(old_tex.TexID == ImTextureID_Invalid and old_tex.BackendUserData == nil) + -- old_tex:DestroyPixels() + -- old_tex.Updates:clear() + -- new_tex = old_tex + -- old_tex = nil + --else + -- Add new new_tex = ImTextureData() new_tex.UniqueID = atlas.TexNextUniqueID atlas.TexNextUniqueID = atlas.TexNextUniqueID + 1 atlas.TexList:push_back(new_tex) if old_tex ~= nil then + -- Queue old as to destroy next frame old_tex.WantDestroyNextFrame = true IM_ASSERT(old_tex.Status == ImTextureStatus.OK or old_tex.Status == ImTextureStatus.WantCreate or old_tex.Status == ImTextureStatus.WantUpdates) end @@ -1732,7 +2001,7 @@ function ImFontAtlasTextureGetSizeEstimate(atlas) local builder = atlas.Builder min_w = ImMax(ImUpperPowerOfTwo(builder.MaxRectSize.x), min_w) min_h = ImMax(ImUpperPowerOfTwo(builder.MaxRectSize.y), min_h) - local surface_approx = builder.RectsPackedSurface - builder.RectsDiscardedSurface + local surface_approx = builder.RectsPackedSurface - builder.RectsDiscardedSurface -- Expected surface after repack local surface_sqrt = ImFloor(ImSqrt(surface_approx)) local new_tex_w @@ -1755,6 +2024,7 @@ function ImFontAtlasTextureGetSizeEstimate(atlas) return ImVec2(new_tex_w, new_tex_h) -- ImVec2i end +-- Clear all output. Invalidates all AddCustomRect() return values! --- @param atlas ImFontAtlas function ImFontAtlasBuildClear(atlas) local new_tex_size = ImFontAtlasTextureGetSizeEstimate(atlas) -- ImVec2i @@ -1771,6 +2041,8 @@ function ImFontAtlasBuildClear(atlas) end end +-- You should not need to call this manually! +-- If you think you do, let us know and we can advise about policies auto-compact. --- @param atlas ImFontAtlas function ImFontAtlasTextureCompact(atlas) local builder = atlas.Builder @@ -1791,6 +2063,7 @@ function ImFontAtlasPackInit(atlas) local tex = atlas.TexData local 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. local pack_node_count = ImFloor(tex.Width / 2) builder.PackNodes:resize(pack_node_count) for i = 1, builder.PackNodes.Size do builder.PackNodes.Data[i] = stbrp.node() end @@ -1808,18 +2081,22 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) return end + -- Pack and store identifier so we can refresh UV coordinates on texture resize. local tex = atlas.TexData local builder = atlas.Builder local r = ImFontAtlasRect() local add_and_draw = (atlas:GetCustomRect(builder.PackIdLinesTexData, r) == false) if add_and_draw then + -- 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 local pack_size = ImVec2(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1) -- ImVec2i builder.PackIdLinesTexData = atlas:AddCustomRect(pack_size.x, pack_size.y, r) IM_ASSERT(builder.PackIdLinesTexData ~= ImFontAtlasRectId_Invalid) end - for n = 0, IM_DRAWLIST_TEX_LINES_WIDTH_MAX do + for n = 0, IM_DRAWLIST_TEX_LINES_WIDTH_MAX do -- +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 local y = n local line_width = n @@ -1828,8 +2105,9 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) --- @type int local pad_right = r.w - (pad_left + line_width) - IM_ASSERT(pad_left + line_width + pad_right == r.w and y < r.h) + IM_ASSERT(pad_left + line_width + pad_right == r.w and y < r.h) -- Make sure we're inside the texture bounds before we start writing pixels + -- Write each slice if (add_and_draw and tex.Format == ImTextureFormat.Alpha8) then local write_ptr, write_ptr_base = tex:GetPixelsAt(r.x, r.y + y) @@ -1860,13 +2138,15 @@ function ImFontAtlasBuildUpdateTexDataLines(atlas) end end + -- Refresh UV coordinates local uv0 = ImVec2(r.x + pad_left - 1, r.y + y) * atlas.TexUvScale local uv1 = ImVec2(r.x + pad_left + line_width + 1, r.y + y + 1) * atlas.TexUvScale - local half_v = (uv0.y + uv1.y) * 0.5 + local half_v = (uv0.y + uv1.y) * 0.5 -- 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) end end +-- Render a white-colored bitmap encoded in a string --- @param atlas ImFontAtlas --- @param x int --- @param y int @@ -1906,6 +2186,8 @@ end --- @param atlas ImFontAtlas function ImFontAtlasBuildUpdateTexDataBasic(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. local builder = atlas.Builder local pack_size = (bit32.band(atlas.Flags, ImFontAtlasFlags.NoMouseCursors) ~= 0) and ImVec2(2, 2) or ImVec2(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H) @@ -1915,9 +2197,12 @@ function ImFontAtlasBuildUpdateTexDataBasic(atlas) builder.PackIdMouseCursors = atlas:AddCustomRect(pack_size.x, pack_size.y, r) IM_ASSERT(builder.PackIdMouseCursors ~= ImFontAtlasRectId_Invalid) + -- Draw to texture if bit32.band(atlas.Flags, ImFontAtlasFlags.NoMouseCursors) ~= 0 then + -- 2x2 white pixels ImFontAtlasBuildRenderBitmapFromString(atlas, r.x, r.y, 2, 2, {"X", "X", "X", "X"}, "X") else + -- 2x2 white pixels + mouse cursors local x_for_white = r.x local 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, ".") @@ -1925,9 +2210,12 @@ function ImFontAtlasBuildUpdateTexDataBasic(atlas) end end + -- Refresh UV coordinates atlas.TexUvWhitePixel = ImVec2((r.x + 0.5) * atlas.TexUvScale.x, (r.y + 0.5) * atlas.TexUvScale.y) end +-- 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? function ImFontAtlasUpdateDrawListsSharedData(atlas) for _, shared_data in atlas.DrawListSharedDatas:iter() do if (shared_data.FontAtlas == atlas) then @@ -1937,12 +2225,19 @@ function ImFontAtlasUpdateDrawListsSharedData(atlas) end end +-- Start packing over current empty texture function ImFontAtlasBuildInit(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 == nil then -- IMGUI_ENABLE_STB_TRUETYPE atlas:SetFontLoader(ImFontAtlasGetFontLoaderForStbTruetype()) end + -- Create initial texture size if atlas.TexData == nil or atlas.TexData.Pixels == nil then ImFontAtlasTextureAdd(atlas, ImUpperPowerOfTwo(atlas.TexMinWidth), ImUpperPowerOfTwo(atlas.TexMinHeight)) end @@ -1955,15 +2250,23 @@ function ImFontAtlasBuildInit(atlas) ImFontAtlasPackInit(atlas) + -- Add required texture data ImFontAtlasBuildUpdateTexData(atlas) + -- Register fonts ImFontAtlasBuildUpdatePointers(atlas) + -- Update UV coordinates etc. stored in bound ImDrawListSharedData instance ImFontAtlasUpdateDrawListsSharedData(atlas) + --atlas.TexIsBuilt = true + + -- Lazily initialize char/text classifier + -- FIXME: This could be practically anywhere, and should eventually be parameters to CalcTextSize/word-wrapping code, but there's no obvious spot now. ImTextInitClassifiers() end +-- Destroy builder and all cached glyphs. Do not destroy actual fonts. --- @param atlas ImFontAtlas function ImFontAtlasBuildDestroy(atlas) for _, font in atlas.Fonts:iter() do @@ -1976,6 +2279,8 @@ function ImFontAtlasBuildDestroy(atlas) atlas.Builder = nil end +-- 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) --- @param atlas ImFontAtlas --- @param old_font ImFont? --- @param new_font ImFont? @@ -1987,9 +2292,9 @@ function ImFontAtlasBuildNotifySetFont(atlas, old_font, new_font) local ctx = shared_data.Context if ctx then repeat + -- While this should work either way, we save ourselves the bother / debugging confusion of running ImGui code so early when it is not needed. + -- Also fixes erroneously rewriting style.FontSizeBase during init if adding default fonts. if old_font == nil and ctx.Font == nil and ctx.FontSizeBase == 0.0 then - -- While this should work either way, we save ourselves the bother / debugging confusion of running ImGui code so early when it is not needed. - -- Also fixes erroneously rewriting style.FontSizeBase during init if adding default fonts. break end @@ -2019,6 +2324,7 @@ function ImFontAtlasBuildNotifySetFont(atlas, old_font, new_font) end end +-- When atlas.RendererHasTextures = true, this is only called if no font were loaded. --- @param atlas ImFontAtlas function ImFontAtlasBuildMain(atlas) IM_ASSERT(not atlas.Locked, "Cannot modify a locked ImFontAtlas!") @@ -2037,13 +2343,20 @@ function ImFontAtlasBuildMain(atlas) -- [LEGACY] For backends not supporting RendererHasTextures: preload all glyphs -- ImFontAtlasBuildUpdateRendererHasTexturesFromContext(atlas); - -- if atlas.RendererHasTextures == false then + -- if atlas.RendererHasTextures == false then -- ~ImGuiBackendFlags.RendererHasTextures -- ImFontAtlasBuildLegacyPreloadAllGlyphRanges(atlas) -- end atlas.TexIsBuilt = true end +------------------------------------------------------------------------------- +-- [SECTION] ImTextureData +------------------------------------------------------------------------------- +-- - ImTextureData:Create() +-- - ImTextureData:DestroyPixels() +------------------------------------------------------------------------------- + function MT.ImTextureData:DestroyPixels() self.Pixels = nil self.UseColors = false @@ -2080,6 +2393,10 @@ function MT.ImTextureData:Create(format, w, h) self.UpdateRect.h = 0 end +------------------------------------------------------------------------------- +-- [SECTION] ImFontBaked, ImFont +------------------------------------------------------------------------------- + function MT.ImFontBaked:ClearOutputData() self.FallbackAdvanceX = 0.0 self.Glyphs:clear() @@ -2091,6 +2408,7 @@ function MT.ImFontBaked:ClearOutputData() self.MetricsTotalSurface = 0 end +-- Find glyph, load if necessary, return fallback if missing --- @param c ImWchar --- @return ImFontGlyph? function MT.ImFontBaked:FindGlyph(c) @@ -2113,6 +2431,7 @@ function MT.ImFontBaked:IsGlyphLoaded(c) return self.IndexLookup.Data[c + 1] ~= IM_FONTGLYPH_INDEX_UNUSED end +-- Attempt to load but when missing, return nil instead of FallbackGlyph --- @param c ImWchar --- @return ImFontGlyph? function MT.ImFontBaked:FindGlyphNoFallback(c) @@ -2126,7 +2445,7 @@ function MT.ImFontBaked:FindGlyphNoFallback(c) end end - self.LoadNoFallback = true + self.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. local glyph = ImFontBaked_BuildLoadGlyph(self, c, nil) self.LoadNoFallback = false return glyph @@ -2137,6 +2456,7 @@ function MT.ImFont:ClearOutputData() if atlas ~= nil then ImFontAtlasFontDiscardBakes(atlas, self, 0) end + --self.FallbackChar = 0 self.EllipsisChar = 0 for i = 1, (IM_UNICODE_CODEPOINT_MAX + 1) / 8192 / 8 do self.Used8kPagesMap[i] = 0 end self.LastBaked = nil @@ -2157,6 +2477,8 @@ end --- @param font_rasterizer_density float --- @return ImFontBaked? function ImFontAtlasBakedGetOrAdd(atlas, font, font_size, font_rasterizer_density) + -- 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.0 and font_rasterizer_density > 0.0) local baked_id = ImFontAtlasBakedGetId(font.FontId, font_size, font_rasterizer_density) local builder = atlas.Builder @@ -2167,23 +2489,29 @@ function ImFontAtlasBakedGetOrAdd(atlas, font, font_size, font_rasterizer_densit return baked end + -- If atlas is locked, find closest match + -- FIXME-OPT: This is not an optimal query. if (bit32.band(font.Flags, ImFontFlags.LockBakedSizes) ~= 0 or atlas.Locked) then baked = ImFontAtlasBakedGetClosestMatch(atlas, font, font_size, font_rasterizer_density) if baked ~= nil then return baked end if atlas.Locked then - IM_ASSERT(not atlas.Locked, "Cannot use dynamic font size with a locked ImFontAtlas!") + IM_ASSERT(not atlas.Locked, "Cannot use dynamic font size with a locked ImFontAtlas!") -- Locked because rendering backend does not support ImGuiBackendFlags.RendererHasTextures! return nil end end + -- Create new baked = ImFontAtlasBakedAdd(atlas, font, font_size, font_rasterizer_density, baked_id) builder.BakedMap[baked_id] = baked return baked end +-- 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 == 'self.Sources' because multiple source fonts+configs can be used to build one target font. --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @param src? ImFontConfig @@ -2193,8 +2521,9 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) local glyph_idx = baked.Glyphs.Size + 1 baked.Glyphs:push_back(in_glyph) local glyph = baked.Glyphs.Data[glyph_idx] - IM_ASSERT(baked.Glyphs.Size < 0xFFFE) + 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) then local r = ImFontAtlasPackGetRect(atlas, glyph.PackId) IM_ASSERT(glyph.U0 == 0.0 and glyph.V0 == 0.0 and glyph.U1 == 0.0 and glyph.V1 == 0.0) @@ -2206,6 +2535,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) end if (src ~= nil) then + -- Clamp & recenter if needed local ref_size = baked.OwnerFont.Sources[1].SizePixels local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0 local advance_x = ImClamp(glyph.AdvanceX, src.GlyphMinAdvanceX * offsets_scale, src.GlyphMaxAdvanceX * offsets_scale) @@ -2215,10 +2545,12 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) glyph.X1 = glyph.X1 + char_off_x end + -- Snap to pixel if (src.PixelSnapH) then advance_x = IM_ROUND(advance_x) end + -- Bake spacing glyph.AdvanceX = advance_x + src.GlyphExtraAdvanceX end if (glyph.Colored) then @@ -2226,6 +2558,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) atlas.TexPixelsUseColors = true end + -- Update lookup tables local codepoint = glyph.Codepoint ImFontBaked_BuildGrowIndex(baked, codepoint + 1) baked.IndexAdvanceX.Data[codepoint + 1] = glyph.AdvanceX @@ -2236,6 +2569,7 @@ function ImFontAtlasBakedAddFontGlyph(atlas, baked, src, in_glyph) return glyph end +-- FIXME: Code is duplicated with code above. --- @param atlas ImFontAtlas --- @param baked ImFontBaked --- @param src? ImFontConfig @@ -2244,14 +2578,17 @@ end function ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, advance_x) -- IM_UNUSED(atlas) if (src ~= nil) then + -- Clamp & recenter if needed local ref_size = baked.OwnerFont.Sources[1].SizePixels local offsets_scale = (ref_size ~= 0.0) and (baked.Size / ref_size) or 1.0 advance_x = ImClamp(advance_x, src.GlyphMinAdvanceX * offsets_scale, src.GlyphMaxAdvanceX * offsets_scale) + -- Snap to pixel if (src.PixelSnapH) then advance_x = IM_ROUND(advance_x) end + -- Bake spacing advance_x = advance_x + src.GlyphExtraAdvanceX end @@ -2259,6 +2596,7 @@ function ImFontAtlasBakedAddFontGlyphAdvancedX(atlas, baked, src, codepoint, adv baked.IndexAdvanceX.Data[codepoint + 1] = advance_x end +-- ImFontBaked are valid for the entire frame but shall never be kept between frames. --- @param size float --- @param density float? --- @return ImFontBaked? @@ -2268,6 +2606,8 @@ function MT.ImFont:GetFontBaked(size, density) --- @type ImFontBaked? local baked = self.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.0 then @@ -2313,6 +2653,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) local font = baked.OwnerFont local atlas = font.OwnerAtlas if atlas.Locked or bit32.band(font.Flags, ImFontFlags.NoLoadGlyphs) ~= 0 then + -- Lazily load fallback glyph if baked.FallbackGlyphIndex == -1 and baked.LoadNoFallback == false then ImFontAtlasBuildSetupFontBakedFallback(baked) end @@ -2320,9 +2661,14 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) return nil, only_load_advance_x end + -- User remapping hooks local src_codepoint = codepoint codepoint = ImFontAtlas_FontHookRemapCodepoint(atlas, font, codepoint) + --IMGUI_DEBUG_LOG("[font] BuildLoadGlyph U+%04X (%s)", codepoint, ImTextCharToUtf8(codepoint)) + + -- Special hook + -- FIXME-NEWATLAS: it would be nicer if this used a more standardized way of hooking if (codepoint == font.EllipsisChar and font.EllipsisAutoBake) then local glyph = ImFontAtlasBuildSetupFontBakedEllipsis(atlas, baked) if (glyph) then @@ -2330,6 +2676,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) end end + -- Call backend local loader_user_data_p = baked.FontLoaderDatas local src_n = 1 for _, src in font.Sources:iter() do @@ -2340,12 +2687,14 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) local glyph_buf = ImFontGlyph() if loader.FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, glyph_buf, nil) then + -- FIXME: Add hooks for e.g. #7962 glyph_buf.Codepoint = src_codepoint glyph_buf.SourceIdx = src_n return ImFontAtlasBakedAddFontGlyph(atlas, baked, src, glyph_buf) end else + -- Special mode but only loading glyphs metrics. Will rasterize and pack later. local ret --[[@as bool]] ret, only_load_advance_x = loader.FontBakedLoadGlyph(atlas, src, baked, loader_user_data_p, codepoint, nil, only_load_advance_x) if ret then @@ -2361,6 +2710,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) src_n = src_n + 1 end + -- Lazily load fallback glyph if (baked.LoadNoFallback) then return nil, only_load_advance_x end @@ -2368,6 +2718,7 @@ function ImFontBaked_BuildLoadGlyph(baked, codepoint, only_load_advance_x) ImFontAtlasBuildSetupFontBakedFallback(baked) end + -- Mark index as not found, so we don't attempt the search twice ImFontBaked_BuildGrowIndex(baked, codepoint + 1); baked.IndexAdvanceX.Data[codepoint + 1] = baked.FallbackAdvanceX baked.IndexLookup.Data[codepoint + 1] = IM_FONTGLYPH_INDEX_NOT_FOUND @@ -2380,6 +2731,7 @@ end --- @return float function ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint) if (baked.Size >= IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE) or baked.LoadNoRenderOnLayout then + -- First load AdvanceX value used by CalcTextSize() API then load the rest when loaded by drawing API. local only_advance_x local glyph glyph, only_advance_x = ImFontBaked_BuildLoadGlyph(baked, codepoint, only_advance_x) @@ -2391,6 +2743,7 @@ function ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint) end end +-- This is not fast query --- @param c ImWchar --- @return bool function MT.ImFont:IsGlyphInFont(c) @@ -2406,10 +2759,12 @@ function MT.ImFont:IsGlyphInFont(c) return false end +-- This is manually inlined in CalcTextSizeA() and CalcWordWrapPosition(), with a non-inline call to BuildLoadGlyphGetAdvanceOrFallback(). --- @param c ImWchar --- @return float function MT.ImFontBaked:GetCharAdvance(c) if c < self.IndexAdvanceX.Size then + -- Missing glyphs fitting inside index will have stored FallbackAdvanceX already. local x = self.IndexAdvanceX.Data[c + 1] if x >= 0.0 then return x @@ -2418,10 +2773,12 @@ function MT.ImFontBaked:GetCharAdvance(c) return ImFontBaked_BuildLoadGlyphAdvanceX(self, c) end +-- The point of this indirection is to not be inlined in debug mode in order to not bloat inner loop.b function BuildLoadGlyphGetAdvanceOrFallback(baked, codepoint) return ImFontBaked_BuildLoadGlyphAdvanceX(baked, codepoint) end +-- Trim trailing space and find beginning of next line --- @param text ImString --- @param text_begin int --- @param text_end int @@ -2480,14 +2837,17 @@ function ImTextClassifierGet(_BITS, _CHAR_OFFSET) return bit32.band(bit32.rshift(_BITS[bit32.rshift(_CHAR_OFFSET, 4) + 1], bit32.lshift(bit32.band(_CHAR_OFFSET, 15), 1)), 0x03) end +-- 2-bit per character local g_CharClassifierIsSeparator_0000_007f = {} for i = 1, 128 / 16 do g_CharClassifierIsSeparator_0000_007f[i] = 0 end local g_CharClassifierIsSeparator_3000_300f = {} for i = 1, 16 / 16 do g_CharClassifierIsSeparator_3000_300f[i] = 0 end function ImTextInitClassifiers() - if (ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, 44) ~= 0) then + if (ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, 44) ~= 0) then -- ',' return end + -- List of hardcoded separators: .,;!?'" + -- Making this dynamic given known ranges is trivial BUT requires us to standardize where you pass them as parameters. (#3002, #8503) ImTextClassifierClear(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Other) ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Blank, " \t") ImTextClassifierSetCharClassFromStr(g_CharClassifierIsSeparator_0000_007f, 0, 128, ImWcharClass.Punct, ".,;!?\"") @@ -2498,6 +2858,9 @@ function ImTextInitClassifiers() ImTextClassifierSetCharClass(g_CharClassifierIsSeparator_3000_300f, 0x3000, 0x300F, ImWcharClass.Punct, 0x3002) end +-- 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. +-- Refer to imgui_test_suite's "drawlist_text_wordwrap_1" for tests. --- @param font ImFont --- @param size float --- @param text ImString @@ -2507,12 +2870,22 @@ end --- @param flags ImDrawTextFlags --- @return int function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_width, flags) + -- For references, possible wrap point marked with ^ + -- "aaa bbb, ccc,ddd. eee fff. ggg!" + -- ^ ^ ^ ^ ^__ ^ ^ + + -- Skip extra blanks after a line returns (that includes not counting them in width computation) + -- e.g. "Hello world" --> "Hello" "World" + + -- Cut words that cannot possibly fit within one line. + -- e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + local baked = font:GetFontBaked(size) local scale = size / baked.Size local line_width = 0.0 local blank_width = 0.0 - wrap_width = wrap_width / scale + wrap_width = wrap_width / scale -- We work with unscaled widths to avoid scaling every characters local s = pos IM_ASSERT(text_end ~= nil) @@ -2520,6 +2893,8 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt local prev_type = ImWcharClass.Other local keep_blanks = bit32.band(flags, ImDrawTextFlags.WrapKeepBlanks) ~= 0 + -- Find next wrapping point + --local span_begin = s local span_end = s local span_width = 0.0 @@ -2539,20 +2914,22 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt if c < 32 then if c == 10 then -- '\n' - return s + return s -- Direct return, skip "Wrap_width is too small to fit anything" path. end if c == 13 then -- '\r' - s = next_s + s = next_s -- Fast-skip break end end + -- Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' local char_width = (c < baked.IndexAdvanceX.Size) and baked.IndexAdvanceX.Data[c + 1] or -1.0 if char_width < 0.0 then char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c) end + -- Classify current character local curr_type if c < 128 then curr_type = ImTextClassifierGet(g_CharClassifierIsSeparator_0000_007f, c) @@ -2563,6 +2940,7 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt end if curr_type == ImWcharClass.Blank then + -- End span: 'A ' or '. ' if (prev_type ~= ImWcharClass.Blank and not keep_blanks) then span_end = s line_width = line_width + span_width @@ -2571,11 +2949,13 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt blank_width = blank_width + char_width else - if (prev_type == ImWcharClass.Punct and curr_type ~= ImWcharClass.Punct and not (c >= 48 and c <= 57)) then + -- End span: '.X' unless X is a digit + if (prev_type == ImWcharClass.Punct and curr_type ~= ImWcharClass.Punct and not (c >= 48 and c <= 57)) then -- FIXME: Digit checks might be removed if allow custom separators (#8503) span_end = s line_width = line_width + (span_width + blank_width) blank_width = 0.0 span_width = 0.0 + -- End span: 'A ' or '. ' elseif (prev_type == ImWcharClass.Blank and keep_blanks) then span_end = s line_width = line_width + (span_width + blank_width) @@ -2590,7 +2970,10 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt if span_width + blank_width > wrap_width then stop = true; break end - + -- FIXME: Narrow wrapping e.g. "A quick brown" -> "Quic|k br|own", would require knowing if span is going to be longer than wrap_width. + --if (span_width > wrap_width and not is_blank and not was_blank) then + -- return s + --end return span_end end @@ -2601,6 +2984,8 @@ function ImFontCalcWordWrapPositionEx(font, size, text, pos, text_end, wrap_widt if stop then break end end + -- 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 == pos and s < text_end then local bytes = ImStd.ImTextCountUtf8BytesFromChar(text, s, text_end) @@ -2643,7 +3028,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi cache_key = text end if not text_end then - text_end = #text + 1 + text_end = #text + 1 -- FIXME-OPT: Need to avoid this. end if not text_end_display then text_end_display = text_end @@ -2663,7 +3048,9 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi local stop = false while s < text_end_display do repeat + -- Word-wrapping if word_wrap_enabled then + -- 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 not word_wrap_eol then word_wrap_eol = ImFontCalcWordWrapPositionEx(font, size, text, s, text_end, wrap_width - line_width, flags) end @@ -2674,7 +3061,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end text_size.y = text_size.y + line_height line_width = 0.0 - s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) + s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks if bit32.band(flags, ImDrawTextFlags.StopOnNewLine) ~= 0 then stop = true; break end @@ -2684,6 +3071,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi end end + -- Decode and advance source local prev_s = s local c = ImStrByte(text, s) if c < 0x80 then @@ -2709,6 +3097,7 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi break end + -- Optimized inline version of 'float char_width = GetCharAdvance((ImWchar)c);' local char_width = (c < baked.IndexAdvanceX.Size) and baked.IndexAdvanceX.Data[c + 1] or -1.0 if (char_width < 0.0) then char_width = BuildLoadGlyphGetAdvanceOrFallback(baked, c) @@ -2730,12 +3119,12 @@ function ImFontCalcTextSizeEx(font, size, max_width, wrap_width, text, text_begi text_size.x = line_width end - if out_offset then + if out_offset then -- offset allow for the possibility of sitting after a trailing \n out_offset.x = line_width out_offset.y = text_size.y + line_height end - if (line_width > 0 or text_size.y == 0.0) then + if (line_width > 0 or text_size.y == 0.0) then -- whereas size.y will ignore the trailing \n text_size.y = text_size.y + line_height end @@ -2817,6 +3206,7 @@ function MT.ImFont:RenderChar(draw_list, size, pos, col, c, cpu_fine_clip) end function MT.ImFontAtlas:AddFont(font_cfg_in) + -- Sanity Checks IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") IM_ASSERT((font_cfg_in.FontData ~= nil and font_cfg_in.FontDataSize > 0) or (font_cfg_in.FontLoader ~= nil)) IM_ASSERT(font_cfg_in.SizePixels > 0.0, "Is ImFontConfig struct correctly initialized?") @@ -2828,10 +3218,12 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) "Specifying glyph offset/advances requires a reference size to base it on.") end + -- Lazily create builder on the first call to AddFont if self.Builder == nil then ImFontAtlasBuildInit(self) end + -- Create new font local is_first_font = (self.Fonts.Size == 0) local font if not font_cfg_in.MergeMode then @@ -2843,11 +3235,12 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) font.CurrentRasterizerDensity = font_cfg_in.RasterizerDensity self.Fonts:push_back(font) else - IM_ASSERT(self.Fonts.Size > 0, "Cannot use MergeMode for the first font!") + IM_ASSERT(self.Fonts.Size > 0, "Cannot use MergeMode for the first font!") -- When using MergeMode make sure that a font has already been added before. font = (font_cfg_in.DstFont ~= nil) and font_cfg_in.DstFont or self.Fonts:back() - ImFontAtlasFontDiscardBakes(self, font, 0) + ImFontAtlasFontDiscardBakes(self, font, 0) -- Need to discard bakes if the font was already used, because baked->FontLoaderDatas[] will change size. (#9162) end + -- Add to list self.Sources:push_back(font_cfg_in) local font_cfg = self.Sources:back() if (font_cfg.DstFont == nil) then @@ -2856,6 +3249,8 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) font.Sources:push_back(font_cfg) ImFontAtlasBuildUpdatePointers(self) + -- Sanity check + -- We don't round cfg.SizePixels yet as relative size of merged fonts are used afterwards. if font_cfg.GlyphExcludeRanges ~= nil then local size = 0 for _, v in ipairs(font_cfg.GlyphExcludeRanges) do if v == 0 then break end size = size + 1 end @@ -2865,14 +3260,18 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) if font_cfg.FontLoader ~= nil then IM_ASSERT(font_cfg.FontLoader.FontBakedLoadGlyph ~= nil) - IM_ASSERT(font_cfg.FontLoader.LoaderInit == nil and font_cfg.FontLoader.LoaderShutdown == nil) + IM_ASSERT(font_cfg.FontLoader.LoaderInit == nil and font_cfg.FontLoader.LoaderShutdown == nil) -- FIXME-NEWATLAS: Unsupported yet. end + -- | Target w/ Implicit RefSize | Target w/ Explicit RefSize | + -- Adding w/ Implicit RefSize: | OK (same scale) | OK (same scale) | + -- Adding w/ Explicit RefSize: | KO | OK (custom scale) | if font_cfg_in.MergeMode and font_cfg_in.SizePixels > 0 then IM_ASSERT(bit32.band(font.Flags, ImFontFlags.ImplicitRefSize) == 0, "Cannot use MergeMode with an explicit reference size when the destination font used an implicit reference size!") end IM_ASSERT(font_cfg.FontLoaderData == nil) if not ImFontAtlasFontSourceInit(self, font_cfg) then + -- Rollback (this is a fragile/rarely exercised code-path. TestSuite's "misc_atlas_add_invalid_font" aim to test this) ImFontAtlasFontDestroySourceData(self, font_cfg) self.Sources:pop_back() font.Sources:pop_back() @@ -2891,12 +3290,16 @@ function MT.ImFontAtlas:AddFont(font_cfg_in) return font end +-- This duplicates some of the logic in UpdateFontsNewFrame() which is a bit chicken-and-eggy/tricky to extract due to variety of codepaths and possible initialization ordering. --- @param ctx ImGuiContext --- @return float local function GetExpectedContextFontSize(ctx) return ((ctx.Style.FontSizeBase > 0.0) and ctx.Style.FontSizeBase or 13.0) * ctx.Style.FontScaleMain * ctx.Style.FontScaleDpi end +-- Legacy function with heuristic to select Pixel or Vector font. +-- The selection is based on (style.FontSizeBase * style.FontScaleMain * style.FontScaleDpi) reaching a small threshold at the time of adding the default font. +-- Prefer calling AddFontDefaultVector() or AddFontDefaultBitmap() based on your own logic. --- @param font_cfg ImFontConfig function MT.ImFontAtlas:AddFontDefault(font_cfg) if self.OwnerContext == nil or GetExpectedContextFontSize(self.OwnerContext) >= 15.0 then @@ -2910,7 +3313,7 @@ function MT.ImFontAtlas:AddFontFromMemoryTTF(font_data, font_data_size, size_pix IM_ASSERT(not self.Locked, "Cannot modify a locked ImFontAtlas!") local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() IM_ASSERT(font_cfg.FontData == nil) - IM_ASSERT(font_data_size > 100, "Incorrect value for font_data_size!") + IM_ASSERT(font_data_size > 100, "Incorrect value for font_data_size!") -- Heuristic to prevent accidentally passing a wrong value to font_data_size. font_cfg.FontData = font_data font_cfg.FontDataSize = font_data_size font_cfg.SizePixels = (size_pixels > 0.0) and size_pixels or font_cfg.SizePixels @@ -2940,6 +3343,7 @@ function MT.ImFontAtlas:AddFontFromFileTTF(filename, size_pixels, font_cfg_templ local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() if not font_cfg.Name or font_cfg.Name == "" then + -- Store a short copy of filename into the font name for convenience for i = #filename, 1, -1 do local c = string.byte(filename, i, i) if (c == 47 or c == 92) then -- '/' or '\\' @@ -2961,31 +3365,35 @@ function GetDefaultFontDataProggyForever() end -- TODO: IMGUI_DISABLE_DEFAULT_FONT, IMGUI_DISABLE_DEFAULT_FONT_BITMAP +-- Load ProggyClean.ttf. Default size 13, disable oversampling. +-- If you want a similar font which may be better scaled, consider using AddFontDefaultVector(). --- @param font_cfg_template ImFontConfig function MT.ImFontAtlas:AddFontDefaultBitmap(font_cfg_template) local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() if not font_cfg_template then - font_cfg.PixelSnapH = true + font_cfg.PixelSnapH = true -- Prevents sub-integer scaling factors at lower-level layers. end if font_cfg.SizePixels <= 0.0 then - font_cfg.SizePixels = 13.0 + font_cfg.SizePixels = 13.0 -- This only serves (1) as a reference for GlyphOffset.y setting and (2) as a default for pre-1.92 backend. font_cfg.Flags = bit32.bor(font_cfg.Flags, ImFontFlags.ImplicitRefSize) end if not font_cfg.Name or font_cfg.Name == "" then font_cfg.Name = "ProggyClean.ttf" end font_cfg.EllipsisChar = 0x0085 - font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 1.0 * (font_cfg.SizePixels / 13.0) + font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 1.0 * (font_cfg.SizePixels / 13.0) -- Add +1 offset per 13 units local ttf_data, ttf_data_size = GetDefaultFontDataProggyClean() return self:AddFontFromMemoryTTF(ttf_data, ttf_data_size, font_cfg.SizePixels, font_cfg) end +-- Load a minimal version of ProggyForever, designed to match our good old ProggyClean, but nicely scalable. +-- (See build script in https://github.com/ocornut/proggyforever for details) --- @param font_cfg_template ImFontConfig function MT.ImFontAtlas:AddFontDefaultVector(font_cfg_template) local font_cfg = font_cfg_template and font_cfg_template or ImFontConfig() if not font_cfg_template then - font_cfg.PixelSnapH = true + font_cfg.PixelSnapH = true -- Precisely match ProggyClean, but prevents sub-integer scaling factors at lower-level layers. end if font_cfg.SizePixels <= 0.0 then font_cfg.SizePixels = 13.0 @@ -2994,8 +3402,8 @@ function MT.ImFontAtlas:AddFontDefaultVector(font_cfg_template) if not font_cfg.Name or font_cfg.Name == "" then font_cfg.Name = "ProggyForever.ttf" end - font_cfg.ExtraSizeScale = font_cfg.ExtraSizeScale * 1.015 - font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 0.5 * (font_cfg.SizePixels / 16.0) + font_cfg.ExtraSizeScale = font_cfg.ExtraSizeScale * 1.015 -- Match ProggyClean + font_cfg.GlyphOffset.y = font_cfg.GlyphOffset.y + 0.5 * (font_cfg.SizePixels / 16.0) -- Closer match ProggyClean + avoid descenders going too high (with current code). local ttf_data, ttf_data_size = GetDefaultFontDataProggyForever() return self:AddFontFromMemoryTTF(ttf_data, ttf_data_size, font_cfg.SizePixels, font_cfg) @@ -3006,7 +3414,7 @@ function MT.ImFontAtlas:GetCustomRect(id, out_r) if r == nil then return false end - IM_ASSERT(self.TexData.Width > 0 and self.TexData.Height > 0) + IM_ASSERT(self.TexData.Width > 0 and self.TexData.Height > 0) -- Font atlas needs to be built before we can calculate UV coordinates if out_r == nil then return true end @@ -3048,6 +3456,7 @@ function ImFontAtlasGetMouseCursorTexData(atlas, cursor_type, out_offset, out_si return true end +-- At it is common to do an AddCustomRect() followed by a GetCustomRect(), we provide an optional 'out_r' argument to retrieve the info straight away. function MT.ImFontAtlas:AddCustomRect(width, height, out_r) IM_ASSERT(width > 0 and width <= 0xFFFF) IM_ASSERT(height > 0 and height <= 0xFFFF) @@ -3083,7 +3492,7 @@ local function IM_NORMALIZE2F_OVER_ZERO(VX, VY) end local function IM_FIXNORMAL2F(VX, VY) - local IM_FIXNORMAL2F_MAX_INVLEN2 = 100 + local IM_FIXNORMAL2F_MAX_INVLEN2 = 100 -- 500.0f (see #4053, #3366) local d2 = VX * VX + VY * VY if d2 > 0.000001 then @@ -3097,10 +3506,14 @@ local function IM_FIXNORMAL2F(VX, VY) return VX, VY end +------------------------------------------------------------------------------- +-- [SECTION] ImDrawData +------------------------------------------------------------------------------- + function MT.ImDrawData:Clear() self.Valid = false self.FrameCount = 0; self.TotalIdxCount = 0; self.TotalVtxCount = 0 - self.CmdLists:resize(0) + self.CmdLists:resize(0) -- The ImDrawList are NOT owned by ImDrawData but e.g. by ImGuiContext, so we don't clear them. self.DisplayPos = ImVec2(0.0, 0.0) self.DisplaySize = ImVec2(0.0, 0.0) self.FramebufferScale = ImVec2(0.0, 0.0) @@ -3108,6 +3521,8 @@ function MT.ImDrawData:Clear() self.Textures = nil end +-- Important: 'out_list' is generally going to be draw_data.CmdLists, but may be another temporary list +-- as long at it is expected that the result will be later merged into draw_data.CmdLists[]. function ImGui.AddDrawListToDrawDataEx(draw_data, out_list, draw_list) if draw_list.CmdBuffer.Size == 0 then return @@ -3116,12 +3531,15 @@ function ImGui.AddDrawListToDrawDataEx(draw_data, out_list, draw_list) return end + -- Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. + -- May trigger for you if you are using PrimXXX functions incorrectly. IM_ASSERT(draw_list.VtxBuffer.Size == 0 or draw_list._VtxWritePtr == draw_list.VtxBuffer.Size + 1) IM_ASSERT(draw_list.IdxBuffer.Size == 0 or draw_list._IdxWritePtr == draw_list.IdxBuffer.Size + 1) if (bit32.band(draw_list.Flags, ImDrawListFlags.AllowVtxOffset) == 0) then IM_ASSERT(draw_list._VtxCurrentIdx == draw_list.VtxBuffer.Size + 1) end + -- Add to output list + records state in ImDrawData out_list:push_back(draw_list) draw_data.TotalVtxCount = draw_data.TotalVtxCount + draw_list.VtxBuffer.Size draw_data.TotalIdxCount = draw_data.TotalIdxCount + draw_list.IdxBuffer.Size @@ -3139,6 +3557,10 @@ local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD, _MAXERROR) return ImCl local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(_N, _MAXERROR) return (_MAXERROR / (1 - ImCos(IM_PI / ImMax(_N, IM_PI)))) end local function IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_ERROR(_N, _RAD) return ((1 - ImCos(IM_PI / ImMax(_N, IM_PI))) / _RAD) end +------------------------------------------------------------------------------- +-- [SECTION] ImDrawList +------------------------------------------------------------------------------- + function MT.ImDrawListSharedData:SetCircleTessellationMaxError(max_error) if self.CircleTessellationMaxError == max_error then return @@ -3166,6 +3588,8 @@ function MT.ImDrawList:_SetDrawListSharedData(data) end end +-- 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 PushTexture() after this. -- TODO: function MT.ImDrawList:_ResetForNewFrame() self._ContentClipX0 = nil -- set again by Begin() (Roblox backend scroll reuse) @@ -3215,7 +3639,7 @@ end function MT.ImDrawList:AddDrawCmd() local draw_cmd = ImDrawCmd() - ImVec4_Copy(draw_cmd.ClipRect, self._CmdHeader.ClipRect) -- Same as calling ImDrawCmd_HeaderCopy()? + ImVec4_Copy(draw_cmd.ClipRect, self._CmdHeader.ClipRect) -- Same as calling ImDrawCmd_HeaderCopy() draw_cmd.TexRef = self._CmdHeader.TexRef draw_cmd.VtxOffset = self._CmdHeader.VtxOffset draw_cmd.IdxOffset = self.IdxBuffer.Size @@ -3224,11 +3648,13 @@ function MT.ImDrawList:AddDrawCmd() self.CmdBuffer:push_back(draw_cmd) end +-- Pop trailing draw command (used before merging or presenting to user) +-- Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == nil function MT.ImDrawList:_PopUnusedDrawCmd() while self.CmdBuffer.Size > 0 do local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] if curr_cmd.ElemCount ~= 0 or curr_cmd.UserCallback ~= nil then - break + break -- return;// break; end self.CmdBuffer:pop_back() @@ -3253,6 +3679,7 @@ function MT.ImDrawList:AddCallback(callback, userdata, userdata_size) curr_cmd.UserCallback = callback -- TODO: _CallbacksDataBuf? if userdata_size == 0 then + -- Store user data directly in command (no indirection) curr_cmd.UserCallbackData = userdata else @@ -3261,7 +3688,7 @@ function MT.ImDrawList:AddCallback(callback, userdata, userdata_size) end - self:AddDrawCmd() + self:AddDrawCmd() -- Force a new command after us (see comment below) end --- Compare ClipRect, TexRef, VtxOffset @@ -3309,6 +3736,7 @@ local function ImDrawCmd_AreSequentialIdxOffset(CMD_0, CMD_1) return CMD_0.IdxOffset + CMD_0.ElemCount == CMD_1.IdxOffset end +-- Try to merge two last draw commands function MT.ImDrawList:_TryMergeDrawCmds() IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] @@ -3319,7 +3747,10 @@ function MT.ImDrawList:_TryMergeDrawCmds() end end +-- Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. +-- The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. function MT.ImDrawList:_OnChangedClipRect() + -- If current command is used with different settings we need to add a new command IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] if (curr_cmd.ElemCount ~= 0 and self._CmdHeader.ClipRect ~= curr_cmd.ClipRect) then @@ -3330,6 +3761,7 @@ function MT.ImDrawList:_OnChangedClipRect() IM_ASSERT(curr_cmd.UserCallback == nil) + -- Try to merge with previous command if it matches, else use current command local prev_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size - 1] if (curr_cmd.ElemCount == 0 and self.CmdBuffer.Size > 1 and ImDrawCmd_HeaderCompare(self._CmdHeader, prev_cmd) and ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) and prev_cmd.UserCallback == nil) then self.CmdBuffer:pop_back() @@ -3341,6 +3773,7 @@ function MT.ImDrawList:_OnChangedClipRect() end function MT.ImDrawList:_OnChangedTexture() + -- If current command is used with different settings we need to add a new command IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] if curr_cmd.ElemCount ~= 0 and curr_cmd.TexRef ~= self._CmdHeader.TexRef then @@ -3349,10 +3782,12 @@ function MT.ImDrawList:_OnChangedTexture() return end + -- Unlike other _OnChangedXXX functions this may be called by ImFontAtlasUpdateDrawListsTextures() in more locations so we need to handle this case. if curr_cmd.UserCallback ~= nil then return end + -- Try to merge with previous command if it matches, else use current command local prev_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size - 1] if curr_cmd.ElemCount == 0 and self.CmdBuffer.Size > 1 and ImDrawCmd_HeaderCompare(self._CmdHeader, prev_cmd) and ImDrawCmd_AreSequentialIdxOffset(prev_cmd, curr_cmd) and prev_cmd.UserCallback == nil then self.CmdBuffer:pop_back() @@ -3364,10 +3799,12 @@ function MT.ImDrawList:_OnChangedTexture() end function MT.ImDrawList:_OnChangedVtxOffset() + -- We don't need to compare curr_cmd.VtxOffset ~= _CmdHeader.VtxOffset because we know it'll be different at the time we call this. self._VtxCurrentIdx = 1 IM_ASSERT_PARANOID(self.CmdBuffer.Size > 0) local curr_cmd = self.CmdBuffer.Data[self.CmdBuffer.Size] + --IM_ASSERT(curr_cmd.VtxOffset ~= self._CmdHeader.VtxOffset) -- See #3349 if curr_cmd.ElemCount ~= 0 then self:AddDrawCmd() return @@ -3376,9 +3813,11 @@ function MT.ImDrawList:_OnChangedVtxOffset() curr_cmd.VtxOffset = self._CmdHeader.VtxOffset end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] ImDrawListSplitter ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap.. +------------------------------------------------------------------------------- -- Lua: channels swap ImVector objects with the draw list (C++ memcpy of the vector headers). -- Channel 0 holds nothing while it is the current channel (its buffers live in the draw list). @@ -3416,11 +3855,14 @@ function MT.ImDrawListSplitter:Split(draw_list, channels_count) IM_ASSERT(self._Current == 0 and self._Count <= 1, "Nested channel splitting is not supported. Please use separate instances of ImDrawListSplitter.") local old_channels_count = self._Channels.Size if old_channels_count < channels_count then - self._Channels:reserve(channels_count) + self._Channels:reserve(channels_count) -- Avoid over reserving since this is likely to stay stable self._Channels:resize(channels_count) end self._Count = channels_count + -- Channels[] hold storage that we'll swap with draw_list._CmdBuffer/_IdxBuffer + -- The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + -- When we switch to the next channel, we'll copy draw_list._CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list.CmdBuffer/_IdxBuffer -- Channel 0 is the draw list itself (memset to 0 in C++) local channels = self._Channels.Data channels[1] = { _CmdBuffer = nil, _IdxBuffer = nil } @@ -3555,6 +3997,8 @@ function MT.ImDrawList:ChannelsMerge() self._Splitter:Merge(self) end --- @param n int # 0-based function MT.ImDrawList:ChannelsSetCurrent(n) self._Splitter:SetCurrentChannel(self, n) end +-- - We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds. +-- - Filled shapes must always use clockwise winding order. The anti-aliasing fringe depends on it. Counter-clockwise shapes will have "inward" anti-aliasing. --- @param points ImVec2[] --- @param points_count int --- @param col ImU32 @@ -3582,6 +4026,7 @@ function MT.ImDrawList:AddConvexPolyFilled(points, points_count, col) self._IdxWritePtr = idx_write_ptr + 3 end + -- Compute normals self._Data.TempBuffer:reserve_discard(points_count) local temp_normals = self._Data.TempBuffer.Data @@ -3658,6 +4103,7 @@ function MT.ImDrawList:PopTexture() self:_OnChangedTexture() end +-- This is used by ImGui.PushFont()/PopFont(). It works because we never use _TextureIdStack[] elsewhere than in PushTexture()/PopTexture(). function MT.ImDrawList:_SetTexture(tex_ref) if (self._CmdHeader.TexRef == tex_ref) then return @@ -3667,11 +4113,18 @@ function MT.ImDrawList:_SetTexture(tex_ref) self:_OnChangedTexture() end +-- Reserve space for a number of vertices and indices. +-- You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or +-- submit the intermediate results. PrimUnreserve() can be used to release unused allocations. @native function MT.ImDrawList:PrimReserve(idx_count, vtx_count) + -- Large mesh support (when enabled) IM_ASSERT_PARANOID(idx_count >= 0 and vtx_count >= 0) if (self._VtxCurrentIdx + vtx_count >= bit32.lshift(1, 16)) and (bit32.band(self.Flags, ImDrawListFlags.AllowVtxOffset) ~= 0) then + -- FIXME: In theory we should be testing that vtx_count <64k here. + -- In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us + -- to not make that check until we rework the text functions to handle clipping and large horizontal lines better. self._CmdHeader.VtxOffset = self.VtxBuffer.Size + 1 self:_OnChangedVtxOffset() end @@ -3688,6 +4141,7 @@ function MT.ImDrawList:PrimReserve(idx_count, vtx_count) self._IdxWritePtr = idx_buffer_old_size + 1 end +-- Release the number of reserved vertices/indices from the end of the last reservation made with PrimReserve(). function MT.ImDrawList:PrimUnreserve(idx_count, vtx_count) IM_ASSERT_PARANOID(idx_count >= 0 and vtx_count >= 0) @@ -3701,6 +4155,7 @@ function MT.ImDrawList:PrimUnreserve(idx_count, vtx_count) self._IdxWritePtr = self.IdxBuffer.Size + 1 end +-- Fully unrolled with inline call to keep our debug builds decently fast. --- @param a ImVec2 --- @param c ImVec2 --- @param col ImU32 @@ -3778,6 +4233,10 @@ function MT.ImDrawList:AddPolyline(points, points_count, col, thickness, flags) local opaque_uv = self._Data.TexUvWhitePixel local count = closed and points_count or points_count - 1 -- Number of line segments local thick_line = thickness > self._FringeScale + -- If this assert triggers on legacy code: + -- - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. + -- - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. + -- Read more details near AddRect() + see "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?") if bit32.band(self.Flags, ImDrawListFlags.AntiAliasedLines) ~= 0 then @@ -4043,6 +4502,8 @@ function MT.ImDrawList:AddRectFilled(p_min, p_max, col, rounding, flags) end end +-- p_min = upper-left, p_max = lower-right +-- Note: this does not support anti-aliasing when provided non-integer vertices. --- @param p_min ImVec2 --- @param p_max ImVec2 --- @param col_upr_left ImU32 @@ -4064,6 +4525,7 @@ function MT.ImDrawList:AddRectFilledMultiColor(p_min, p_max, col_upr_left, col_u self:PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left) end +-- p_min = upper-left, p_max = lower-right --- @param p_min ImVec2 --- @param p_max ImVec2 --- @param col ImU32 @@ -4075,7 +4537,16 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) if thickness == nil then thickness = 1.0 end if flags == nil then flags = 0 end - IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?") + -- If this assert triggers on legacy code: + -- - 1.92.8 (2025/05): swapped two last parameters order: flags, thickness --> thickness, flags. This should normally be caught by compile-time type-checking. + -- - 1.92.8 (2025/05): changed value of ImDrawList_Closed which was previously guaranteed to be == 1. Hardcoded use of 1 or true should be replaced. + -- - 1.82.0 (2021/03): changed ImDrawCornerFlags to ImDrawFlags_RoundXXX values. + -- If you used hard-coded 1 to 15 or ~0 in flags to configure corner rounding use the new flags! + -- - Hard coded support for ~0 == ImDrawFlags_RoundAll. + -- - Hard coded support for values 0x01 to 0x0F (matching 15 out of 16 old flags combinations) --> see FixRectCornerFlags() in <1.90 code. + -- - Hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundNone or use 'float rounding = 0.0f'. + -- See "API BREAKING CHANGES" section for 1.82, 1.90 and 1.92.8. + IM_ASSERT_USER_ERROR_RET(bit32.band(flags, ImDrawFlags.InvalidMask_) == 0, "Incorrect parameter. Did you swap 'thickness' and 'flags'?") -- Or misuse of legacy hard-coded ImDrawCornerFlags values if bit32.band(col, IM_COL32_A_MASK) == 0 then return @@ -4094,7 +4565,7 @@ function MT.ImDrawList:AddRect(p_min, p_max, col, rounding, thickness, flags) if bit32.band(self.Flags, ImDrawListFlags.AntiAliasedLines) ~= 0 then self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.50, 0.50), rounding, flags) else - self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.49, 0.49), rounding, flags) + self:PathRect(p_min + ImVec2(0.50, 0.50), p_max - ImVec2(0.49, 0.49), rounding, flags) -- Better looking lower-right corner and rounded non-AA shapes. end self:PathStroke(col, thickness, ImDrawFlags.Closed) @@ -4257,10 +4728,13 @@ function MT.ImDrawList:AddText(font, font_size, pos, col, text, text_begin, text if bit32.band(col, IM_COL32_A_MASK) == 0 then return end + -- Accept null ranges if text_begin == text_end then return end + -- 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 == nil then font = self._Data.Font end @@ -4321,7 +4795,7 @@ function MT.ImDrawList:AddImageRounded(tex_ref, p_min, p_max, uv_min, uv_max, co return end - IM_ASSERT(bit32.band(flags, 0x0F) == 0, "Misuse of legacy hardcoded ImDrawCornerFlags values!") + IM_ASSERT(bit32.band(flags, 0x0F) == 0, "Misuse of legacy hardcoded ImDrawCornerFlags values!") -- If this assert triggers on legacy code: see comments in ImDrawList:PathRect(). if bit32.band(flags, ImDrawFlags.RoundCornersMask_) == 0 then flags = bit32.bor(flags, ImDrawFlags.RoundCornersAll) end @@ -4349,22 +4823,24 @@ end --- @param radius float function MT.ImDrawList:_CalcCircleAutoSegmentCount(radius) - local radius_idx = ImFloor(radius + 0.999) + 1 + -- Automatic segment count + local radius_idx = ImFloor(radius + 0.999) + 1 -- ceil to never reduce accuracy if radius_idx >= 1 and radius_idx <= 64 then -- IM_COUNTOF(_Data->CircleSegmentCounts) - return self._Data.CircleSegmentCounts[radius_idx] + return self._Data.CircleSegmentCounts[radius_idx] -- Use cached value else return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, self._Data.CircleTessellationMaxError) end end +-- 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) function MT.ImDrawList:PushClipRect(cr_min, cr_max, intersect_with_current_clip_rect) local cr = ImVec4(cr_min.x, cr_min.y, cr_max.x, cr_max.y) if intersect_with_current_clip_rect then local current = self._CmdHeader.ClipRect - if cr.x < current.x then cr.x = current.x end + if cr.x < current.x then cr.x = current.x end -- = ClipWith(). Note that passing inverted range wouldn't be fixed here. if cr.y < current.y then cr.y = current.y end if cr.z > current.z then cr.z = current.z end if cr.w > current.w then cr.w = current.w end @@ -4400,10 +4876,12 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp return end + -- Calculate arc auto segment step size if a_step <= 0 then a_step = math.floor(IM_DRAWLIST_ARCFAST_SAMPLE_MAX / self:_CalcCircleAutoSegmentCount(radius)) end + -- Make sure we never do steps larger than one quarter of the circle a_step = ImClamp(a_step, 1, math.floor(IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4)) local sample_range = ImAbs(a_max_sample - a_min_sample) @@ -4419,6 +4897,8 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp extra_max_sample = true samples = samples + 1 + -- When we have overstep to avoid awkwardly looking one long line and one tiny one at the end, + -- distribute first step range evenly between them by reducing first step size. if sample_range > 0 then a_step = a_step - math.floor((a_step - overstep) / 2) end @@ -4439,6 +4919,7 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp if a_max_sample >= a_min_sample then local a = a_min_sample while a <= a_max_sample do + -- a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more if sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX then sample_index = sample_index - IM_DRAWLIST_ARCFAST_SAMPLE_MAX end @@ -4454,6 +4935,7 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp else local a = a_min_sample while a >= a_max_sample do + -- a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more if sample_index < 0 then sample_index = sample_index + IM_DRAWLIST_ARCFAST_SAMPLE_MAX end @@ -4482,6 +4964,7 @@ function MT.ImDrawList:_PathArcToFastEx(center, radius, a_min_sample, a_max_samp IM_ASSERT_PARANOID(self._Path.Size == out_ptr - 1) end +-- 0: East, 3: South, 6: West, 9: North, 12: East @native function MT.ImDrawList:PathArcToFast(center, radius, a_min_of_12, a_max_of_12) if radius < 0.5 then @@ -4530,9 +5013,12 @@ function MT.ImDrawList:PathArcTo(center, radius, a_min, a_max, num_segments) return end + -- Automatic segment count if radius <= self._Data.ArcFastRadiusCutoff then local a_is_reverse = a_max < a_min + -- We are going to use precomputed values for mid samples. + -- Determine first and last sample in lookup table that belong to the arc. local a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0) local a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0) @@ -4559,7 +5045,8 @@ function MT.ImDrawList:PathArcTo(center, radius, a_min, a_max, num_segments) end end --- Not recommended to call this directly! +-- Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound. +-- DO NOT CALL DIRECTLY THIS WILL CHANGE WILDLY IN 2026. Use ImDrawList:AddText(). --- @param draw_list ImDrawList --- @param size float --- @param pos ImVec2 @@ -4575,6 +5062,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b if wrap_width == nil then wrap_width = .0 end if flags == nil then flags = 0 end + -- Align to be pixel perfect local x = pos.x local y = pos.y if y > clip_rect.w then @@ -4595,11 +5083,15 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b local origin_x = x local word_wrap_enabled = (wrap_width > 0.0) + -- Fast-forward to first visible line local s = text_begin if y + line_height < clip_rect.y then while y + line_height < clip_rect.y and s < text_end do local line_end = ImMemchr(text, '\n', s) if word_wrap_enabled then + -- 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 = ImFontCalcWordWrapPositionEx(self, size, text, s, (line_end ~= nil) and line_end or text_end, wrap_width, flags) s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) else @@ -4610,6 +5102,8 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b end end + -- For large text, scan for the last visible line in order to avoid over-reserving in the call to PrimReserve() + -- Note that very large horizontal line will still be affected by the issue (e.g. a one megabyte string buffer without a newline will likely crash atm) if text_end - s > 1e4 and not word_wrap_enabled then local s_end = s local y_end = y @@ -4626,6 +5120,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b return end + -- Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) local vtx_count_max = (text_end - s) * 4 local idx_count_max = (text_end - s) * 6 local idx_expected_size = draw_list.IdxBuffer.Size + idx_count_max @@ -4648,6 +5143,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b while s < text_end do repeat if word_wrap_enabled then + -- 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 not word_wrap_eol then word_wrap_eol = ImFontCalcWordWrapPositionEx(self, size, text, s, text_end, wrap_width - (x - origin_x), flags) end @@ -4656,15 +5152,16 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b x = origin_x y = y + line_height if y > clip_rect.w then - stop = true; break + stop = true; break -- break out of main loop end word_wrap_eol = nil - s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) + s = ImTextCalcWordWrapNextLineStart(text, s, text_end, flags) -- Wrapping skips upcoming blanks break end end + -- Decode and advance source local c if text_is_str then c = string.byte(text, s) else c = text[s] end if c < 0x80 then @@ -4680,7 +5177,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b x = origin_x y = y + line_height if y > clip_rect.w then - stop = true; break + stop = true; break -- break out of main loop end break @@ -4702,16 +5199,19 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b local char_width = glyph.AdvanceX * scale if glyph.Visible then + -- We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w local x1 = x + glyph.X0 * scale local x2 = x + glyph.X1 * scale local y1 = y + glyph.Y0 * scale local y2 = y + glyph.Y1 * scale if x1 <= clip_rect.z and x2 >= clip_rect.x then + -- Render a character local u1 = glyph.U0 local v1 = glyph.V0 local u2 = glyph.U1 local v2 = glyph.V1 + -- CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. if (cpu_fine_clip) then if (x1 < clip_rect.x) then u1 = u1 + (1.0 - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1) @@ -4736,8 +5236,10 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b end end + -- Support for untinted glyphs local glyph_col = glyph.Colored and color_untinted or col + -- We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here: do local o = (vtx_write - 1) * 36 writef64(vtx_data, o, x1); writef64(vtx_data, o + 8, y1); writef64(vtx_data, o + 16, u1); writef64(vtx_data, o + 24, v1); writeu32(vtx_data, o + 32, glyph_col) @@ -4759,7 +5261,7 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b if stop then break end end - -- Edge case: calling RenderText() with unloaded glyphs triggering texture change. It doesn't happen via ImGui.* calls because CalcTextSize() is always used + -- 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 then IM_ASSERT(draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount == 0) draw_list.CmdBuffer:pop_back() @@ -4769,7 +5271,8 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b return self:RenderText(draw_list, size, pos, col, clip_rect, text, text_begin, text_end, wrap_width, flags) -- was `goto begin` end - draw_list.VtxBuffer.Size = vtx_write - 1 + -- Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action. + draw_list.VtxBuffer.Size = vtx_write - 1 -- Same as calling shrink() draw_list.IdxBuffer.Size = idx_write - 1 draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount = draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size].ElemCount - (idx_expected_size - draw_list.IdxBuffer.Size) draw_list._VtxWritePtr = vtx_write @@ -4777,6 +5280,22 @@ function MT.ImFont:RenderText(draw_list, size, pos, col, clip_rect, text, text_b draw_list._VtxCurrentIdx = vtx_index end +------------------------------------------------------------------------------- +-- [SECTION] ImGui Internal Render Helpers +------------------------------------------------------------------------------- +-- Vaguely redesigned to stop accessing ImGui global state: +-- - RenderArrow() +-- - RenderBullet() +-- - RenderCheckMark() +-- - RenderArrowPointingAt() +-- - RenderRectFilledInRangeH() +-- - RenderRectFilledWithHole() +------------------------------------------------------------------------------- +-- Function in need of a redesign (legacy mess) +-- - RenderColorRectWithAlphaCheckerboard() +------------------------------------------------------------------------------- + +-- Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state --- @param draw_list ImDrawList --- @param pos ImVec2 --- @param color ImU32 @@ -4817,7 +5336,7 @@ end --- @param pos ImVec2 --- @param col ImU32 function ImGui.RenderBullet(draw_list, pos, col) - -- FIXME-OPT: This should be baked in font now that it's easier + -- FIXME-OPT: This should be baked in font now that it's easier. local font_size = draw_list._Data.FontSize draw_list:AddCircleFilled(pos, font_size * 0.20, col, (font_size < 22) and 8 or ((font_size < 40) and 12 or 0)) -- Hardcode optimal/nice tessellation threshold end @@ -4841,7 +5360,7 @@ function ImGui.RenderCheckMark(draw_list, pos, col, sz) draw_list:PathStroke(col, thickness) end --- Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side +-- Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side. --- @param draw_list ImDrawList --- @param pos ImVec2 --- @param half_sz ImVec2 @@ -4856,7 +5375,7 @@ function ImGui.RenderArrowPointingAt(draw_list, pos, half_sz, direction, col) draw_list:AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col) elseif direction == ImGuiDir.Down then draw_list:AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col) - elseif direction == ImGuiDir.None or direction == ImGuiDir.COUNT then + elseif direction == ImGuiDir.None or direction == ImGuiDir.COUNT then -- Fix warnings end end @@ -4864,9 +5383,12 @@ local function ImAcos01(x) if x <= 0.0 then return IM_PI * 0.5 end if x >= 1.0 then return 0.0 end return ImAcos(x) + --return (-0.69813170079773212 * x * x - 0.87266462599716477) * x + 1.5707963267948966 -- Cheap approximation, may be enough for what we do. end --- FIXME: Cleanup and move code to ImDrawList +-- FIXME: Cleanup and move code to ImDrawList. +-- - Before 2025-12-04: RenderRectFilledRangeH() with 'float x_start_norm, float x_end_norm` <- normalized +-- - After 2025-12-04: RenderRectFilledInRangeH() with 'float x1, float x2' <- absolute coords!! --- @param draw_list ImDrawList --- @param rect ImRect --- @param col ImU32 @@ -5002,7 +5524,7 @@ function ImGui.RenderColorRectWithAlphaCheckerboard(draw_list, p_min, p_max, col break end - cell_flags = ImDrawFlags.RoundCornersNone + cell_flags = ImDrawFlags.RoundCornersNone -- FIXME: Could use CalcRoundingFlagsForRectInRect() if y1 <= p_min.y then if x1 <= p_min.x then cell_flags = bit32.bor(cell_flags, ImDrawFlags.RoundCornersTopLeft) end if x2 >= p_max.x then cell_flags = bit32.bor(cell_flags, ImDrawFlags.RoundCornersTopRight) end @@ -5055,14 +5577,14 @@ function ImGui.RenderRectFilledWithHole(draw_list, outer, inner, col, rounding) if fill_R and fill_D then draw_list:AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, D.RoundCornersBottomRight) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- Extra primitives (Ngon, Ellipse, Bezier, concave fill) ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [port] These follow the 1.92 stroker this port uses (no ImDrawFlags_StrokeXXX placement flags). function MT.ImDrawList:PathEllipticalArcTo(center, radius, rot, a_min, a_max, num_segments) if num_segments == nil or num_segments <= 0 then - num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) + num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) -- A bit pessimistic, maybe there's a better computation to do here. end local cos_rot, sin_rot = ImCos(rot), ImSin(rot) for i = 0, num_segments do @@ -5084,6 +5606,7 @@ function ImBezierQuadraticCalc(p1, p2, p3, t) return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x, w1 * p1.y + w2 * p2.y + w3 * p3.y) end +-- Closely mimics ImBezierCubicClosestPointCasteljau() in imgui.cpp local function PathBezierCubicCurveToCasteljau(path, x1, y1, x2, y2, x3, y3, x4, y4, tess_tol, level) local dx, dy = x4 - x1, y4 - y1 local d2 = math.abs((x2 - x4) * dy - (y2 - y4) * dx) @@ -5119,7 +5642,7 @@ end function MT.ImDrawList:PathBezierCubicCurveTo(p2, p3, p4, num_segments) local p1 = self._Path:back() if num_segments == nil or num_segments == 0 then - PathBezierCubicCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, self._Data.CurveTessellationTol, 0) + PathBezierCubicCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, self._Data.CurveTessellationTol, 0) -- Auto-tessellated else local t_step = 1.0 / num_segments for i_step = 1, num_segments do self._Path:push_back(ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step)) end @@ -5129,33 +5652,39 @@ end function MT.ImDrawList:PathBezierQuadraticCurveTo(p2, p3, num_segments) local p1 = self._Path:back() if num_segments == nil or num_segments == 0 then - PathBezierQuadraticCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, self._Data.CurveTessellationTol, 0) + PathBezierQuadraticCurveToCasteljau(self._Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, self._Data.CurveTessellationTol, 0) -- Auto-tessellated else local t_step = 1.0 / num_segments for i_step = 1, num_segments do self._Path:push_back(ImBezierQuadraticCalc(p1, p2, p3, t_step * i_step)) end end end +-- Guaranteed to honor 'num_segments' function MT.ImDrawList:AddNgon(center, radius, col, num_segments, thickness) if thickness == nil then thickness = 1.0 end if bit32.band(col, IM_COL32_A_MASK) == 0 or num_segments <= 2 then return end + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = (IM_PI * 2.0) * (num_segments - 1.0) / num_segments self:PathArcTo(center, radius - 0.5, 0.0, a_max, num_segments - 1) self:PathStroke(col, thickness, ImDrawFlags.Closed) end +-- Guaranteed to honor 'num_segments' function MT.ImDrawList:AddNgonFilled(center, radius, col, num_segments) if bit32.band(col, IM_COL32_A_MASK) == 0 or num_segments <= 2 then return end + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = (IM_PI * 2.0) * (num_segments - 1.0) / num_segments self:PathArcTo(center, radius, 0.0, a_max, num_segments - 1) self:PathFillConvex(col) end +-- Ellipse function MT.ImDrawList:AddEllipse(center, radius, col, rot, num_segments, thickness) if rot == nil then rot = 0.0 end if thickness == nil then thickness = 1.0 end if bit32.band(col, IM_COL32_A_MASK) == 0 then return end - if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end + if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end -- A bit pessimistic, maybe there's a better computation to do here. + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = IM_PI * 2.0 * (num_segments - 1.0) / num_segments self:PathEllipticalArcTo(center, radius, rot, 0.0, a_max, num_segments - 1) self:PathStroke(col, thickness, ImDrawFlags.Closed) @@ -5164,12 +5693,14 @@ end function MT.ImDrawList:AddEllipseFilled(center, radius, col, rot, num_segments) if rot == nil then rot = 0.0 end if bit32.band(col, IM_COL32_A_MASK) == 0 then return end - if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end + if num_segments == nil or num_segments <= 0 then num_segments = self:_CalcCircleAutoSegmentCount(ImMax(radius.x, radius.y)) end -- A bit pessimistic, maybe there's a better computation to do here. + -- Because we are filling a closed shape we remove 1 from the count of segments/points local a_max = IM_PI * 2.0 * (num_segments - 1.0) / num_segments self:PathEllipticalArcTo(center, radius, rot, 0.0, a_max, num_segments - 1) self:PathFillConvex(col) end +-- Cubic Bezier takes 4 controls points function MT.ImDrawList:AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments) if bit32.band(col, IM_COL32_A_MASK) == 0 then return end self:PathLineTo(p1) @@ -5177,6 +5708,7 @@ function MT.ImDrawList:AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segmen self:PathStroke(col, thickness or 1.0) end +-- Quadratic Bezier takes 3 controls points function MT.ImDrawList:AddBezierQuadratic(p1, p2, p3, col, thickness, num_segments) if bit32.band(col, IM_COL32_A_MASK) == 0 then return end self:PathLineTo(p1) diff --git a/imgui_h.lua b/imgui_h.lua index 31ae926..58c4126 100644 --- a/imgui_h.lua +++ b/imgui_h.lua @@ -1,5 +1,32 @@ ---- Dear ImGui WIP --- (Definitions) +-- dear imgui, v1.93.0 WIP +-- (headers) + +-- Help: +-- - Call and read ImGui.ShowDemoWindow() in imgui_demo.lua. All applications in examples/ are doing that. +-- - Read top of imgui.lua for more details, links and comments. + +-- Resources: +-- - FAQ ........................ https://dearimgui.com/faq +-- - Homepage ................... https://github.com/ocornut/imgui +-- - Releases & Changelog ....... https://github.com/ocornut/imgui/releases +-- - Wiki ....................... https://github.com/ocornut/imgui/wiki (lots of good stuff there) +-- - Issues & support ........... https://github.com/ocornut/imgui/issues + +-- Index of this file: +-- [SECTION] Forward declarations and basic types +-- [SECTION] METATABLE MANAGEMENT +-- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> +-- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) +-- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +-- [SECTION] Texture identifiers (ImTextureID, ImTextureRef) +-- [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) +-- [SECTION] ImGuiIO +-- [SECTION] Viewports +-- [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) +-- [SECTION] Flags & Enumerations +-- [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) +-- [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +-- [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) --- @meta @@ -10,6 +37,11 @@ local rawget = rawget; local rawset = rawset local bitAnd = bit32.band; local bitOr = bit32.bor local bitLShift = bit32.lshift +------------------------------------------------------------------------------- +-- [SECTION] Forward declarations and basic types +------------------------------------------------------------------------------- + +-- Scalar data types --- @class char : integer --- @class unsigned_char : integer @@ -54,25 +86,42 @@ function ImS32(val) return bitAnd(val, 0xFFFFFFFF) end --- @alias size_t unsigned_int +-- 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) --- @alias ImWchar16 unsigned_short --- @alias ImWchar ImWchar16 --- @alias bool boolean +-- A unique ID used by widgets (typically the result of hashing a stack of string) --- @alias ImGuiID unsigned_int +-- 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. --- @alias ImTextureID integer +-- ImGuiKey | ImGuiMod_XXX: for IsKeyChordPressed(), Shortcut() etc. an ImGuiKey optionally OR-ed with one or more ImGuiMod_XXX values. --- @alias ImGuiKeyChord int +-- ImDrawIdx: vertex index. [Compile-time configurable type] --- @alias ImDrawIdx unsigned_int +-- Library Version +-- (Integer encoded as XYYZZ for use in conditionals, e.g. 'if IMGUI_VERSION_NUM >= 12345') IMGUI_VERSION = "1.93.0 WIP" IMGUI_VERSION_NUM = 19298 -IM_UNICODE_CODEPOINT_INVALID = 0xFFFD -IM_UNICODE_CODEPOINT_MAX = 0xFFFF +-- Helper: Unicode defines +IM_UNICODE_CODEPOINT_INVALID = 0xFFFD -- Invalid Unicode code point (standard value). +IM_UNICODE_CODEPOINT_MAX = 0xFFFF -- Maximum Unicode code point supported by this build. +-- IM_ALLOC(), IM_FREE(), IM_DELETE() IM_ALLOC = ImGui.MemAlloc IM_FREE = ImGui.MemFree @@ -80,9 +129,9 @@ IM_FREE = ImGui.MemFree --- @param field string|int IM_DELETE = function(owner, field) if owner[field] ~= nil then owner[field] = nil; ImGui.MemFree(owner, field); end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] METATABLE MANAGEMENT ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- File-scope metatable storage local MT = {} @@ -95,11 +144,12 @@ function IM_ASSERT(_EXPR, _MSG) assert((_EXPR), _MSG) end IM_ASSERT_PARANOID = IM_ASSERT +-- A primary data type --- Note that `S64` and `U64` are not supported --- @enum ImGuiDataType ImGuiDataType = { - S8 = 0, -- signed char / char + S8 = 0, -- signed char / char (with sensible compilers) U8 = 1, -- unsigned char S16 = 2, -- short U16 = 3, -- unsigned short @@ -111,37 +161,43 @@ ImGuiDataType = String = 9, -- string (provided for user convenience, not supported by scalar widgets) COUNT = 10 } +-- Extend ImGuiDataType_ ImGuiDataType.Pointer = 11 -- [internal] ImGuiDataType.ID = 12 -- [internal] ImTextureID_Invalid = -1 +-- 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 = 0, - Alpha8 = 1, + RGBA32 = 0, -- 4 components per pixel, each is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + Alpha8 = 1, -- 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 = 0, - Destroyed = 1, - WantCreate = 2, - WantUpdates = 3, - WantDestroy = 4, + Destroyed = 1, -- Backend destroyed the texture. + WantCreate = 2, -- Requesting backend to create the texture. Set status OK when done. + WantUpdates = 3, -- Requesting backend to update specific blocks of pixels (write to texture portions which have never been used before). Set status OK when done. + WantDestroy = 4, -- Requesting backend to destroy the texture. Set status to Destroyed when done. } +-- Flags for ImFontAtlas build --- @enum ImFontAtlasFlags ImFontAtlasFlags = { None = 0, - NoPowerOfTwoHeight = bitLShift(1, 0), - NoMouseCursors = bitLShift(1, 1), - NoBakedLines = bitLShift(1, 2) + NoPowerOfTwoHeight = bitLShift(1, 0), -- Don't round the height to next power of two + NoMouseCursors = bitLShift(1, 1), -- Don't build software mouse cursors into the atlas (save a little texture memory) + NoBakedLines = bitLShift(1, 2) -- Don't build anti-aliased line textures into the atlas (save a little texture memory). SINCE 1.93.0 THIS PREVENTS ANTI-ALIASED LINES FROM WORKING AND WILL DISABLE THEM. } +-- A cardinal direction --- @enum ImGuiDir ImGuiDir = { @@ -153,6 +209,8 @@ ImGuiDir = COUNT = 4 } +-- Identify a mouse button. +-- Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience. --- @enum ImGuiMouseButton ImGuiMouseButton = { @@ -162,24 +220,29 @@ ImGuiMouseButton = COUNT = 5 } +-- Enumeration for GetMouseCursor() +-- User code may request backend to display given cursor by calling SetMouseCursor(), which is why we have some cursors that are marked unused here --- @enum ImGuiMouseCursor ImGuiMouseCursor = { None = -1, Arrow = 0, - TextInput = 1, - ResizeAll = 2, - ResizeNS = 3, - ResizeEW = 4, - ResizeNESW = 5, - ResizeNWSE = 6, - Hand = 7, - Wait = 8, - Progress = 9, - NotAllowed = 10, + TextInput = 1, -- When hovering over InputText, etc. + ResizeAll = 2, -- (Unused by Dear ImGui functions) + ResizeNS = 3, -- When hovering over a horizontal border + ResizeEW = 4, -- When hovering over a vertical border or a column + ResizeNESW = 5, -- When hovering over the bottom-left corner of a window + ResizeNWSE = 6, -- When hovering over the bottom-right corner of a window + Hand = 7, -- (Unused by Dear ImGui functions. Use for e.g. hyperlinks) + Wait = 8, -- When waiting for something to process/load. + Progress = 9, -- When waiting for something to process/load, but application is still interactive. + NotAllowed = 10, -- When hovering something with disallowed interaction. Usually a crossed circle. COUNT = 11 } +-- 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. --- @class ImTextureRect --- @field x unsigned_short --- @field y unsigned_short @@ -193,6 +256,7 @@ ImGuiMouseCursor = --- @return ImTextureRect function ImTextureRect(x, y, w, h) return { x = x, y = y, w = w, h = h } end +-- ImVec2: 2D vector used to store positions, sizes etc. [Compile-time configurable type] -- [Luau] Stored as named fields {x=, y=} so the common `.x`/`.y` access is a plain table read (no metamethod call). -- Numeric keys 1, 2 still work through the metatable, but are slower: prefer .x/.y in hot code. --- @class ImVec2 @@ -262,6 +326,7 @@ function ImVec2_MulVX(a, scalar) return a.x * scalar, a.y * scalar end --- An inlined version of `ImVec2_Copy` currently for use in certain ImVector `push_back` local function ImVec2_TCopy(t, k, v) local dest = t[k]; dest.x = v.x; dest.y = v.y; end +-- ImVec4: 4D vector used to store clipping rectangles, colors etc. [Compile-time configurable type] -- [Luau] Same layout as ImVec2: named fields x, y, z, w; numeric keys 1..4 go through the metatable. --- @class ImVec4 --- @operator add(ImVec4): ImVec4 @@ -302,6 +367,11 @@ function IM_VEC4:__tostring() return string.format("ImVec4(%g, %g, %g, %g)", sel @native function ImVec4_Copy(dest, src) dest.x = src.x; dest.y = src.y; dest.z = src.z; dest.w = src.w end +------------------------------------------------------------------------------- +-- [SECTION] Helpers: Debug log, memory allocations macros, ImVector<> +------------------------------------------------------------------------------- + +-- ImVector<> --- A compact ImVector clone --- @class ImVector --- @field Data T[] # 1-based table @@ -408,6 +478,16 @@ function IM_VECTOR:index_from_ptr(p) IM_ASSERT(false, "index_from_ptr failed!") end +------------------------------------------------------------------------------- +-- [SECTION] Drawing API (ImDrawCmd, ImDrawIdx, ImDrawVert, ImDrawChannel, ImDrawListSplitter, ImDrawFlags, ImDrawList, ImDrawData) +------------------------------------------------------------------------------- + +-- Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. + +-- Typically, 1 command = 1 GPU draw call (unless command is a callback) +-- - 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. --- @class ImDrawCmd --- @field ClipRect ImVec4 --- @field TexRef ImTextureRef @@ -425,15 +505,15 @@ IM_DRAWCMD.__index = IM_DRAWCMD --- @nodiscard function ImDrawCmd() return setmetatable({ - ClipRect = ImVec4(), - TexRef = nil, - VtxOffset = 0, - IdxOffset = 0, - ElemCount = 0, - UserCallback = nil, - UserCallbackData = nil, - UserCallbackDataSize = 0, - UserCallbackDataOffset = 0 + ClipRect = ImVec4(), -- 4*4 -- Clipping rectangle (x1, y1, x2, y2). Subtract ImDrawData->DisplayPos to get clipping rectangle in "viewport" coordinates + TexRef = nil, -- 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. + VtxOffset = 0, -- 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. + IdxOffset = 0, -- 4 -- Start offset in index buffer. + ElemCount = 0, -- 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[]. + UserCallback = nil, -- 4-8 -- If != nil, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + UserCallbackData = nil, -- 4-8 -- Callback user data (when UserCallback != nil). If called AddCallback() with size == 0, this is a copy of the AddCallback() argument. If called AddCallback() with size > 0, this is pointing to a buffer where data is stored. + UserCallbackDataSize = 0, -- 4 -- Size of callback user data when using storage, otherwise 0. + UserCallbackDataOffset = 0 -- 4 -- [Internal] Offset of callback user data when using storage, otherwise -1. }, IM_DRAWCMD) end @@ -446,6 +526,7 @@ function IM_DRAWCMD:GetTexID() return tex_id end +-- Vertex layout --- @class ImDrawVert --- @field [1] ImVec2 # pos --- @field [2] ImVec2 # uv @@ -479,6 +560,7 @@ function IM_VTXBUF:clear() self.Size = 0; self.Capacity = 0; self.Buf = buffer.c function ImDrawVtx_Pos(b, i) local o = (i - 1) * VTX_STRIDE; return buffer.readf64(b, o), buffer.readf64(b, o + 8) end function ImDrawVtx_Col(b, i) return buffer.readu32(b, (i - 1) * VTX_STRIDE + 32) end +-- [Internal] For use by ImDrawList --- @class ImDrawCmdHeader --- @field ClipRect ImVec4 --- @field TexRef ImTextureRef @@ -488,6 +570,7 @@ function ImDrawVtx_Col(b, i) return buffer.readu32(b, (i - 1) * VTX_STRIDE + 32) --- @nodiscard function ImDrawCmdHeader() return { ClipRect = ImVec4(), TexRef = nil, VtxOffset = 0 } end +-- [Internal] For use by ImDrawListSplitter --- @class ImDrawChannel --- @field _CmdBuffer ImVector --- @field _IdxBuffer ImVector @@ -496,6 +579,8 @@ function ImDrawCmdHeader() return { ClipRect = ImVec4(), TexRef = nil, VtxOffset --- @nodiscard function ImDrawChannel() return { _CmdBuffer = ImVector(), _IdxBuffer = ImVector() } end +-- 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. --- @class ImDrawListSplitter --- @field _Current int --- @field _Count int @@ -507,6 +592,15 @@ MT.ImDrawListSplitter = {} -- methods in imgui_draw.lua MT.ImDrawListSplitter.__index = MT.ImDrawListSplitter function ImDrawListSplitter() return setmetatable({ _Current = 0, _Count = 0, _Channels = ImVector() }, MT.ImDrawListSplitter) end +-- Draw command list +-- This is the low-level list of polygons that ImGui.* functions are filling. At the end of the frame, +-- all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +-- Each dear imgui window contains its own ImDrawList. You can use ImGui.GetWindowDrawList() to +-- access the current window draw list and draw custom primitives. +-- You can interleave normal ImGui.* calls and adding primitives to the current draw list. +-- 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 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. --- @class ImDrawList --- @field CmdBuffer ImVector --- @field IdxBuffer ImVector @@ -559,24 +653,26 @@ end function ImDrawList(data) --- @type ImDrawList local this = setmetatable({ - CmdBuffer = ImVector(), - IdxBuffer = ImVector(), - VtxBuffer = ImDrawVtxBuffer(), - Flags = 0, + -- This is what you have to render + CmdBuffer = ImVector(), -- Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback. + IdxBuffer = ImVector(), -- Index buffer. Each command consume ImDrawCmd::ElemCount of those + VtxBuffer = ImDrawVtxBuffer(), -- Vertex buffer. + Flags = 0, -- Current flags for drawing primitives. Alter with PushDrawFlag()/PopDrawFlags() to adjust defaults to a given scope. - _VtxCurrentIdx = 1, - _Data = nil, - _VtxWritePtr = 1, - _IdxWritePtr = 1, - _Path = ImVector(ImVec2, ImVec2_TCopy), - _CmdHeader = ImDrawCmdHeader(), - _Splitter = ImDrawListSplitter(), - _ClipRectStack = ImVector(), - _TextureStack = ImVector(), - _CallbacksDataBuf = nil, + -- [Internal, used while building lists] + _VtxCurrentIdx = 1, -- [Internal] generally == VtxBuffer.Size unless we are past 64K vertices, in which case this gets reset to 0. + _Data = nil, -- Pointer to shared draw data (you can use ImGui.GetDrawListSharedData() to get the one from current ImGui context) + _VtxWritePtr = 1, -- [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + _IdxWritePtr = 1, -- [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + _Path = ImVector(ImVec2, ImVec2_TCopy), -- [Internal] current path building + _CmdHeader = ImDrawCmdHeader(), -- [Internal] template of active commands. Fields should match those of CmdBuffer.back(). + _Splitter = ImDrawListSplitter(), -- [Internal] for channels api (note: prefer using your own persistent instance of ImDrawListSplitter!) + _ClipRectStack = ImVector(), -- [Internal] + _TextureStack = ImVector(), -- [Internal] + _CallbacksDataBuf = nil, -- [Internal] - _FringeScale = 0, - _OwnerName = nil + _FringeScale = 0, -- [Internal] anti-alias fringe is scaled by this value, this helps to keep things sharp while zooming at vertex buffer content + _OwnerName = nil -- Pointer to owner window's name for debugging }, MT.ImDrawList) this:_SetDrawListSharedData(data) @@ -584,6 +680,9 @@ function ImDrawList(data) return this end +-- All draw data to render a Dear ImGui frame +-- (NB: the style and the naming convention here is a little inconsistent, we currently preserve them for backward compatibility purpose, +-- as this is one of the oldest structure exposed by the library! Basically, ImDrawList == CmdList) --- @class ImDrawData --- @field Valid bool --- @field FrameCount int @@ -603,12 +702,23 @@ function ImDrawData() --- @type ImDrawData local this = setmetatable({}, MT.ImDrawData) - this.CmdLists = ImVector() + this.CmdLists = ImVector() -- Array of ImDrawList* to render. The ImDrawLists are owned by ImGuiContext and only pointed to from here. this:Clear() return this end +------------------------------------------------------------------------------- +-- [SECTION] Texture API (ImTextureFormat, ImTextureStatus, ImTextureRect, ImTextureData) +------------------------------------------------------------------------------- + +-- 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 --- @class ImTextureData --- @field UniqueID int --- @field Status ImTextureStatus @@ -636,22 +746,23 @@ function ImTextureData() --- @type ImTextureData local this = setmetatable({}, MT.ImTextureData) - this.UniqueID = 0 - this.Status = ImTextureStatus.Destroyed - this.BackendUserData = nil - this.TexID = ImTextureID_Invalid - this.Format = 0 - this.Width = 0 - this.Height = 0 - this.BytesPerPixel = 0 - this.Pixels = nil - this.UsedRect = ImTextureRect() - this.UpdateRect = ImTextureRect() - this.Updates = ImVector() - this.UnusedFrames = 0 - this.RefCount = 0 - this.UseColors = false - this.WantDestroyNextFrame = false + -------------------------------------------- core / backend --------------------------------------- + this.UniqueID = 0 -- w - -- [DEBUG] Sequential index to facilitate identifying a texture when debugging/printing. Unique per atlas. + this.Status = ImTextureStatus.Destroyed -- rw rw -- ImTextureStatus.OK/_WantCreate/_WantUpdates/_WantDestroy. Always use SetStatus() to modify! + this.BackendUserData = nil -- - rw -- Convenience storage for backend. Some backends may have enough with TexID. + this.TexID = ImTextureID_Invalid -- 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. + this.Format = 0 -- w r -- ImTextureFormat.RGBA32 (default) or ImTextureFormat.Alpha8 + this.Width = 0 -- w r -- Texture width + this.Height = 0 -- w r -- Texture height + this.BytesPerPixel = 0 -- w r -- 4 or 1 + this.Pixels = nil -- w r -- Pointer to whole texture buffer holding 'Width*Height' pixels and 'Width*Height*BytesPerPixels' bytes. + this.UsedRect = ImTextureRect() -- w r -- Bounding box encompassing all past and queued Updates[]. + this.UpdateRect = ImTextureRect() -- w r -- Bounding box encompassing all queued Updates[]. + this.Updates = ImVector() -- w r -- Array of individual updates. + this.UnusedFrames = 0 -- 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. + this.RefCount = 0 -- w r -- Number of contexts using this texture. Used during backend shutdown. + this.UseColors = false -- w r -- Tell whether our texture data is known to use colors (rather than just white + alpha). + this.WantDestroyNextFrame = false -- rw - -- [Internal] Queued to set ImTextureStatus.WantDestroy next frame. May still be used in the current frame. return this end @@ -671,6 +782,14 @@ function MT.ImTextureData:SetTexID(tex_id) self.TexID = tex_id end --- @param status ImTextureStatus function MT.ImTextureData:SetStatus(status) self.Status = status if (status == ImTextureStatus.Destroyed and not self.WantDestroyNextFrame and self.Pixels ~= nil) then self.Status = ImTextureStatus.WantCreate end end +------------------------------------------------------------------------------- +-- [SECTION] Texture identifiers (ImTextureID, ImTextureRef) +------------------------------------------------------------------------------- + +-- 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. --- @class ImTextureRef --- @field _TexData? ImTextureData --- @field _TexID ImTextureID @@ -681,11 +800,18 @@ IM_TEXTURE_REF.__index = IM_TEXTURE_REF --- @nodiscard function ImTextureRef(tex_id) return setmetatable({ - _TexData = nil, - _TexID = tex_id or ImTextureID_Invalid + -- Members (either are set, never both!) + _TexData = nil, -- A texture, generally owned by a ImFontAtlas. Will convert to ImTextureID during render loop, after texture has been uploaded. + _TexID = tex_id or ImTextureID_Invalid -- _OR_ Low-level backend texture identifier, if already uploaded or created by user/app. Generally provided to e.g. ImGui.Image() calls. }, IM_TEXTURE_REF) end +------------------------------------------------------------------------------- +-- [SECTION] Font API (ImFontConfig, ImFontGlyph, ImFontGlyphRangesBuilder, ImFontAtlasFlags, ImFontAtlas, ImFontBaked, ImFont) +------------------------------------------------------------------------------- + +-- Font runtime data for a given size +-- Important: pointers to ImFontBaked are only valid for the current frame. --- @class ImFontBaked --- @field IndexAdvanceX ImVector # Glyphs->AdvanceX in a directly indexable way. Note that codepoint starts from 0, so IndexAdvanceX.Data[0 + 1] holds the advanceX of glyph at codepoint 0 --- @field FallbackAdvanceX float @@ -713,29 +839,37 @@ function ImFontBaked() --- @type ImFontBaked local this = setmetatable({}, MT.ImFontBaked) - this.IndexAdvanceX = ImVector() - this.FallbackAdvanceX = 0 - this.Size = 0 - this.RasterizerDensity = 0 + -- [Internal] Members: Hot ~20/24 bytes (for CalcTextSize) + this.IndexAdvanceX = ImVector() -- 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). + this.FallbackAdvanceX = 0 -- 4 -- out -- FindGlyph(FallbackChar)->AdvanceX + this.Size = 0 -- 4 -- in -- Height of characters/line, set during loading (doesn't change after loading) + this.RasterizerDensity = 0 -- 4 -- in -- Density this is baked at - this.IndexLookup = ImVector() - this.Glyphs = ImVector() - this.FallbackGlyphIndex = -1 + -- [Internal] Members: Hot ~28/36 bytes (for RenderText loop) + this.IndexLookup = ImVector() -- 12-16 -- out -- Sparse. Index glyphs by Unicode code-point. + this.Glyphs = ImVector() -- 12-16 -- out -- All glyphs. + this.FallbackGlyphIndex = -1 -- 4 -- out -- Index of FontFallbackChar - this.Ascent = 0 + -- [Internal] Members: Cold + this.Ascent = 0 -- 4+4 -- out -- Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] (unscaled) this.Descent = 0 this.MetricsTotalSurface = 0 this.WantDestroy = false this.LoadNoFallback = false this.LoadNoRenderOnLayout = false - this.LastUsedFrame = 0 - this.BakedId = 0 - this.OwnerFont = nil - this.FontLoaderDatas = nil + this.LastUsedFrame = 0 -- 4 -- -- Record of that time this was bounds + this.BakedId = 0 -- 4 -- -- Unique ID for this baked storage + this.OwnerFont = nil -- 4-8 -- in -- Parent font + this.FontLoaderDatas = nil -- 4-8 -- -- Font loader opaque storage (per baked font * sources): single contiguous buffer allocated by imgui, passed to loader. return this end +-- Font runtime data and rendering +-- - ImFontAtlas automatically loads a default embedded font for you if you didn't load one manually. +-- - Since 1.92.0 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). --- @class ImFont --- @field LastBaked ImFontBaked --- @field OwnerAtlas ImFontAtlas @@ -762,23 +896,27 @@ function ImFont() --- @type ImFont local this = setmetatable({}, MT.ImFont) - this.LastBaked = nil - this.OwnerAtlas = nil - this.Flags = 0 - this.CurrentRasterizerDensity = 0 - this.FontId = 0 - this.LegacySize = 0 - this.Sources = ImVector() - this.EllipsisChar = 0 - this.FallbackChar = 0 + -- [Internal] Members: Hot ~12-20 bytes + this.LastBaked = nil -- 4-8 -- Cache last bound baked. NEVER USE DIRECTLY. Use GetFontBaked(). + this.OwnerAtlas = nil -- 4-8 -- What we have been loaded into. + this.Flags = 0 -- 4 -- Font flags. + this.CurrentRasterizerDensity = 0 -- 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. + this.FontId = 0 -- Unique identifier for the font + this.LegacySize = 0 -- 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). + this.Sources = ImVector() -- 16 -- in -- List of sources. Pointers within OwnerAtlas->Sources[] + this.EllipsisChar = 0 -- 2-4 -- out -- Character used for ellipsis rendering ('...'). If you ever want to temporarily swap this for an alternative/dummy char, make sure to clear EllipsisAutoBake. + this.FallbackChar = 0 -- 2-4 -- out -- Character used if a glyph isn't found (U+FFFD, '?') this.Used8kPagesMap = {} - this.EllipsisAutoBake = false - this.RemapPairs = {} + this.EllipsisAutoBake = false -- 1 -- -- Mark when the "..." glyph (== EllipsisChar) needs to be generated by combining multiple '.'. + this.RemapPairs = {} -- 16 -- -- Remapping pairs when using AddRemapCodepointXXX(). this.Scale = 0 return this end +-- A font input/source (we may rename this to ImFontSource in the future) --- @class ImFontConfig --- @field Name string --- @field FontData table @@ -814,37 +952,49 @@ function ImFontConfig() --- @type ImFontConfig local this = setmetatable({}, IM_FONT_CONFIG) - this.Name = nil - this.FontData = nil - this.FontDataSize = 0 - this.FontDataOwnedByAtlas = true + -- Data Source + this.Name = nil -- -- Name (strictly to ease debugging, hence limited size buffer) + this.FontData = nil -- TTF/OTF data + this.FontDataSize = 0 -- TTF/OTF data size + this.FontDataOwnedByAtlas = true -- true -- TTF/OTF data ownership taken by the owner ImFontAtlas (will delete memory itself). SINCE 1.92, THE DATA NEEDS TO PERSIST FOR WHOLE DURATION OF ATLAS. - this.MergeMode = false - this.PixelSnapH = false - this.OversampleH = 0 - this.OversampleV = 0 - this.EllipsisChar = 0 - this.SizePixels = 0 - this.GlyphRanges = nil - this.GlyphExcludeRanges = nil - this.GlyphOffset = ImVec2() - this.GlyphMinAdvanceX = 0 - this.GlyphMaxAdvanceX = FLT_MAX - this.GlyphExtraAdvanceX = 0 - this.FontNo = 0 - this.FontLoaderFlags = 0 - this.RasterizerMultiply = 1.0 - this.RasterizerDensity = 1.0 - this.ExtraSizeScale = 1.0 + -- Options + this.MergeMode = false -- 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. + this.PixelSnapH = false -- false -- Align every glyph AdvanceX to pixel boundaries. Prevents fractional font size from working correctly! Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, OversampleH/V will default to 1. + this.OversampleH = 0 -- 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. + this.OversampleV = 0 -- 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. + this.EllipsisChar = 0 -- 0 -- Explicitly specify Unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used. + this.SizePixels = 0 -- Output size in pixels for rasterizer (more or less maps to the resulting font height). + this.GlyphRanges = nil -- nil -- *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). + this.GlyphExcludeRanges = nil -- nil -- 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. + this.GlyphOffset = ImVec2() -- 0, 0 -- Offset (in pixels) all glyphs from this font input. Absolute value for default size, other sizes will scale this value. + this.GlyphMinAdvanceX = 0 -- 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. + this.GlyphMaxAdvanceX = FLT_MAX -- FLT_MAX -- Maximum AdvanceX for glyphs + this.GlyphExtraAdvanceX = 0 -- 0 -- Extra spacing (in pixels) between glyphs. Please contact us if you are using this. -- FIXME-NEWATLAS: Intentionally unscaled + this.FontNo = 0 -- 0 -- Index of font within TTF/OTF file + this.FontLoaderFlags = 0 -- 0 -- Settings for custom font builder. THIS IS BUILDER IMPLEMENTATION DEPENDENT. Leave as zero if unsure. + this.RasterizerMultiply = 1.0 -- 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. + this.RasterizerDensity = 1.0 -- 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. + this.ExtraSizeScale = 1.0 -- 1.0f -- Extra rasterizer scale over SizePixels. - this.Flags = 0 - this.DstFont = nil - this.FontLoader = nil - this.FontLoaderData = nil + -- [Internal] + this.Flags = 0 -- Font flags (don't use just yet, will be exposed in upcoming 1.92.X updates) + this.DstFont = nil -- Target font (as we merging fonts, multiple ImFontConfig may target the same font) + this.FontLoader = nil -- Custom font backend for this source (default source is the one stored in ImFontAtlas) + this.FontLoaderData = nil -- Font loader opaque storage (per font config) return this end +-- Load and rasterize multiple TTF/OTF fonts into a same texture. The font atlas will build a single texture holding: +-- - 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). +-- - 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. --- @class ImFontAtlas --- @field Flags ImFontAtlasFlags --- @field TexDesiredFormat ImTextureFormat @@ -883,41 +1033,46 @@ function ImFontAtlas() --- @type ImFontAtlas local this = setmetatable({}, MT.ImFontAtlas) - this.Flags = 0 - this.TexDesiredFormat = ImTextureFormat.RGBA32 - this.TexGlyphPadding = 1 - this.TexMinWidth = 512 - this.TexMinHeight = 128 - this.TexMaxWidth = 8192 - this.TexMaxHeight = 8192 + -- Input + this.Flags = 0 -- Build flags (see ImFontAtlasFlags_) + this.TexDesiredFormat = ImTextureFormat.RGBA32 -- Desired texture format (default to ImTextureFormat.RGBA32 but may be changed to ImTextureFormat.Alpha8). + this.TexGlyphPadding = 1 -- FIXME: Should be called "TexPackPadding". Padding between glyphs within texture in pixels. Defaults to 1. If your rendering method never relies on bilinear filtering you may set this to 0. + this.TexMinWidth = 512 -- Minimum desired texture width. Must be a power of two. Default to 512. + this.TexMinHeight = 128 -- Minimum desired texture height. Must be a power of two. Default to 128. + this.TexMaxWidth = 8192 -- Maximum desired texture width. Must be a power of two. Default to 8192. + this.TexMaxHeight = 8192 -- Maximum desired texture height. Must be a power of two. Default to 8192. this.TexRef = ImTextureRef() - this.TexData = nil + this.TexData = nil -- Latest texture. - this.TexList = ImVector() - this.Locked = false - this.RendererHasTextures = false - this.TexPixelsUseColors = nil - this.TexUvScale = nil - this.TexUvWhitePixel = nil - this.Fonts = ImVector() - this.Sources = ImVector() + -- [Internal] + this.TexList = ImVector() -- Texture list (most often TexList.Size == 1). TexData is always == TexList.back(). DO NOT USE DIRECTLY, USE GetDrawData().Textures[]/GetPlatformIO().Textures[] instead! + this.Locked = false -- Marked as locked during ImGui.NewFrame()..EndFrame() scope if TexUpdates are not supported. Any attempt to modify the atlas will assert. + this.RendererHasTextures = false -- Copy of (BackendFlags & ImGuiBackendFlags.RendererHasTextures) from supporting context. + this.TexPixelsUseColors = nil -- 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. + this.TexUvScale = nil -- = (1.0f/TexData->TexWidth, 1.0f/TexData->TexHeight). May change as new texture gets created. + this.TexUvWhitePixel = nil -- Texture coordinates to a white pixel. May change as new texture gets created. + this.Fonts = ImVector() -- 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. + this.Sources = ImVector() -- Source/configuration data this.TexUvLines = {} - this.TexNextUniqueID = 1 - this.FontNextUniqueID = 1 - this.DrawListSharedDatas = ImVector() - this.Builder = nil - this.FontLoader = nil - this.FontLoaderName = nil - this.FontLoaderData = nil - this.FontLoaderFlags = nil - this.RefCount = 0 - this.OwnerContext = nil + this.TexNextUniqueID = 1 -- Next value to be stored in TexData->UniqueID + this.FontNextUniqueID = 1 -- Next value to be stored in ImFont->FontID + this.DrawListSharedDatas = ImVector() -- List of users for this atlas. Typically one per Dear ImGui context. + this.Builder = nil -- Opaque interface to our data that doesn't need to be public and may be discarded when rebuilding. + this.FontLoader = nil -- 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. + this.FontLoaderName = nil -- Font loader name (for display e.g. in About box) == FontLoader->Name + this.FontLoaderData = nil -- Font backend opaque storage + this.FontLoaderFlags = nil -- Shared flags (for all fonts) for font loader. THIS IS BUILD IMPLEMENTATION DEPENDENT (e.g. Per-font override is also available in ImFontConfig). + this.RefCount = 0 -- Number of contexts using this atlas + this.OwnerContext = nil -- Context which own the atlas will be in charge of updating and destroying it. return this end +-- 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) --- @class ImFontAtlasRect --- @field x unsigned_short --- @field y unsigned_short @@ -926,6 +1081,8 @@ end --- @field uv0 ImVec2 --- @field uv1 ImVec2 +-- 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. --- @alias ImFontAtlasRectId int ImFontAtlasRectId_Invalid = -1 @@ -934,13 +1091,14 @@ ImFontAtlasRectId_Invalid = -1 --- @nodiscard function ImFontAtlasRect() return { - x = nil, y = nil, - w = nil, h = nil, - uv0 = ImVec2(), + x = nil, y = nil, -- Position (in current texture) + w = nil, h = nil, -- Size + uv0 = ImVec2(), -- UV coordinates (in current texture) uv1 = ImVec2() } end +-- Hold rendering data for one glyph. --- @class ImFontGlyph --- @field Colored boolean --- @field Visible boolean @@ -965,15 +1123,30 @@ function ImFontGlyph() Visible = false, SourceIdx = 0, Codepoint = 0, - AdvanceX = 0, + AdvanceX = 0, -- Horizontal distance to advance cursor/layout position. - X0 = 0, Y0 = 0, X1 = 0, Y1 = 0, - U0 = 0, V0 = 0, U1 = 0, V1 = 0, + X0 = 0, Y0 = 0, X1 = 0, Y1 = 0, -- Glyph corners. Offsets from current cursor/layout position. + U0 = 0, V0 = 0, U1 = 0, V1 = 0, -- Texture coordinates for the current value of ImFontAtlas->TexRef. Cached equivalent of calling GetCustomRect() with PackId. - PackId = -1 + PackId = -1 -- [Internal] ImFontAtlasRectId value (FIXME: Cold data, could be moved elsewhere?) } end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiIO +------------------------------------------------------------------------------- + +-- Communicate most settings and inputs/outputs to Dear ImGui using this structure. +-- Access via ImGui.GetIO(). Read 'Programmer guide' section in .cpp file for general usage. +-- It is generally expected that: +-- - initialization: backends and user code writes to ImGuiIO. +-- - main loop: backends writes to ImGuiIO, user code and imgui code reads from ImGuiIO. +------------------------------------------------------------------------------- +-- Also see ImGui.GetPlatformIO() and ImGuiPlatformIO struct for OS/platform related functions: clipboard, IME etc. +------------------------------------------------------------------------------- + +-- [Internal] Storage used by IsKeyDown(), IsKeyPressed() etc functions. +-- If prior to 1.87 you used io.KeysDownDuration[] (which was marked as internal), you should use GetKeyData(key)->DownDuration and *NOT* io.KeysData[key]->DownDuration. --- @class ImGuiKeyData --- @field Down bool --- @field DownDuration float @@ -984,6 +1157,8 @@ end --- @nodiscard function ImGuiKeyData() return { Down = false, DownDuration = 0.0, DownDurationPrev = 0.0, AnalogValue = 0.0 } end +-- Configuration flags stored in io.ConfigFlags. Set by user/application. +-- Note that nowadays most of our configuration options are in other ImGuiIO fields, e.g. io.ConfigWindowsMoveFromTitleBarOnly. --- @enum ImGuiConfigFlags ImGuiConfigFlags = { None = 0, @@ -1005,126 +1180,157 @@ MT.ImGuiIO.__index = MT.ImGuiIO --- @return ImGuiIO function ImGuiIO() local this = { - Ctx = nil, + Ctx = nil, -- Parent UI context (needs to be set explicitly by parent). - KeyCtrl = false, - KeyShift = false, - KeyAlt = false, - KeySuper = false, + KeyCtrl = false, -- Keyboard modifier down: Ctrl (non-macOS), Cmd (macOS) + KeyShift = false, -- Keyboard modifier down: Shift + KeyAlt = false, -- Keyboard modifier down: Alt + KeySuper = false, -- Keyboard modifier down: Windows/Super (non-macOS), Ctrl (macOS) - KeyMods = nil, + -- Other state maintained from data above + IO function calls + KeyMods = nil, -- 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() - BackendFlags = ImGuiBackendFlags.None, - ConfigFlags = ImGuiConfigFlags.None, - DisplaySize = ImVec2(-1.0, -1.0), + BackendFlags = ImGuiBackendFlags.None, -- = 0 -- See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. + ConfigFlags = ImGuiConfigFlags.None, -- = 0 -- See ImGuiConfigFlags_ enum. Set by user/application. Keyboard/Gamepad navigation options, etc. + DisplaySize = ImVec2(-1.0, -1.0), -- -- Main display size, in pixels (== GetMainViewport()->Size). May change every frame. - DeltaTime = 1.0 / 60.0, + DeltaTime = 1.0 / 60.0, -- = 1.0f/60.0f -- Time elapsed since last frame, in seconds. May change every frame. - DisplayFramebufferScale = ImVec2(1.0, 1.0), + DisplayFramebufferScale = ImVec2(1.0, 1.0), -- = (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. - MousePos = ImVec2(), - MousePosPrev = ImVec2(), + -- Main Input State + -- (this block used to be written by backend, since 1.87 it is best to NOT write to those directly, call the AddXXX functions above instead) + -- (reading from those variables is fair game, as they are extremely unlikely to be moving anywhere) + MousePos = ImVec2(), -- Mouse position, in pixels. Set to ImVec2(-FLT_MAX, -FLT_MAX) if mouse is unavailable (on another screen, etc.) + MousePosPrev = ImVec2(), -- Previous mouse position (note that MouseDelta is not necessary == MousePos-MousePosPrev, in case either position is invalid) - WantSetMousePos = false, + WantSetMousePos = false, -- MousePos has been altered, backend should reposition mouse on next frame. Rarely used! Set only when io.ConfigNavMoveSetMousePos is enabled. - MouseDelta = ImVec2(), + MouseDelta = ImVec2(), -- Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta. - MouseDown = {[0] = false, [1] = false, [2] = false}, + MouseDown = {[0] = false, [1] = false, [2] = false}, -- Mouse buttons: 0=left, 1=right, 2=middle + extras (ImGuiMouseButton.COUNT == 5). Dear ImGui mostly uses left and right buttons. Other buttons allow us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. - MouseWheel = 0, - MouseWheelH = 0, + MouseWheel = 0, -- Mouse wheel Vertical: 1 unit scrolls about 5 lines text. >0 scrolls Up, <0 scrolls Down. Hold Shift to turn vertical scroll into horizontal scroll. + MouseWheelH = 0, -- 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. - MouseCtrlLeftAsRightClick = false, + MouseCtrlLeftAsRightClick = false, -- (OSX) Set to true when the current click was a Ctrl+Click that spawned a simulated right click - MouseWheelRequestAxisSwap = false, + MouseWheelRequestAxisSwap = false, -- 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. - ConfigColorEditFlags = ImGuiColorEditFlags.DefaultOptions_, + ConfigColorEditFlags = ImGuiColorEditFlags.DefaultOptions_, -- = -- Current settings for ColorEdit/ColorPicker widgets. Must have one bit of ImGuiColorEditFlags.DisplayMask_, one bit of ImGuiColorEditFlags.DataTypeMask_, one bit of ImGuiColorEditFlags.PickerMask_, one bit of ImGuiColorEditFlags.InputMask_. Defaults to ImGuiColorEditFlags.DefaultOptions_. May be further edited by users, unless you also set ImGuiColorEditFlags.NoOptions. - ConfigMacOSXBehaviors = false, - ConfigNavCursorVisibleAuto = true, - ConfigNavCursorVisibleAlways = false, - ConfigInputTrickleEventQueue = true, - ConfigWindowsResizeFromEdges = true, + -- Widget options + ConfigMacOSXBehaviors = false, -- Swap Cmd<>Ctrl keys + OS X style text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl. + ConfigNavCursorVisibleAuto = true, -- = true -- Using directional navigation key makes the cursor visible. Mouse click hides the cursor. + ConfigNavCursorVisibleAlways = false, -- = false -- Navigation cursor is always visible. + ConfigInputTrickleEventQueue = true, -- = true -- Enable input queue trickling: some types of events submitted during the same frame (e.g. button down + up) will be spread over multiple frames, improving interactions with low framerates. + ConfigWindowsResizeFromEdges = true, -- = 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) - ConfigDebugIniSettings = false, - ConfigWindowsCopyContentsWithCtrlC = false, - ConfigWindowsMoveFromTitleBarOnly = false, - ConfigErrorRecovery = true, - ConfigErrorRecoveryEnableAssert = true, - ConfigErrorRecoveryEnableDebugLog = true, - ConfigErrorRecoveryEnableTooltip = true, - ConfigDebugHighlightIdConflicts = false, - ConfigDebugHighlightIdConflictsShowItemPicker = true, + ConfigDebugIniSettings = false, -- = false -- Save .ini data with extra comments (particularly helpful for Docking, but makes saving slower) + ConfigWindowsCopyContentsWithCtrlC = false, -- = 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. + ConfigWindowsMoveFromTitleBarOnly = false, -- = false -- Enable allowing to move windows only when clicking on their title bar. Does not apply to windows without a title bar. + -- Options to configure Error Handling and how we handle recoverable errors [EXPERIMENTAL] + -- - Error recovery is provided as a way to facilitate: + -- - Recovery after a programming error (native code or scripting language - the latter tends to facilitate iterating on code while running). + -- - Recovery after running an exception handler or any error processing which may skip code after an error has been detected. + -- - Error recovery is not perfect nor guaranteed! It is a feature to ease development. + -- You not are not supposed to rely on it in the course of a normal application run. + -- - Functions that support error recovery are using IM_ASSERT_USER_ERROR() instead of IM_ASSERT(). + -- - By design, we do NOT allow error recovery to be 100% silent. One of the three options needs to be checked! + -- - Always ensure that on programmers seats you have at minimum Asserts or Tooltips enabled when making direct imgui API calls! + -- Otherwise it would severely hinder your ability to catch and correct mistakes! + -- Read https://github.com/ocornut/imgui/wiki/Error-Handling for details. + -- - Programmer seats: keep asserts (default), or disable asserts and keep error tooltips (new and nice!) + -- - Non-programmer seats: maybe disable asserts, but make sure errors are resurfaced (tooltips, visible log entries, use callback etc.) + -- - Recovery after error/exception: record stack sizes with ErrorRecoveryStoreState(), disable assert, set log callback (to e.g. trigger high-level breakpoint), recover with ErrorRecoveryTryToRecoverState(), restore settings. + ConfigErrorRecovery = true, -- = true -- Enable error recovery support. Some errors won't be detected and lead to direct crashes if recovery is disabled. + ConfigErrorRecoveryEnableAssert = true, -- = true -- Enable asserts on recoverable error. By default call IM_ASSERT() when returning from a failing IM_ASSERT_USER_ERROR() + ConfigErrorRecoveryEnableDebugLog = true, -- = true -- Enable debug log output on recoverable errors. + ConfigErrorRecoveryEnableTooltip = true, -- = true -- Enable tooltip on recoverable errors. The tooltip include a way to enable asserts if they were disabled. + -- 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 + ConfigDebugHighlightIdConflicts = false, -- Highlight and show an error message popup when multiple items have conflicting identifiers. + ConfigDebugHighlightIdConflictsShowItemPicker = true, -- =true -- Show "Item Picker" button in aforementioned popup. IniFilename = "imgui.ini", -- Roblox: no disk access, only used as a flag (nil disables .ini handling) - IniSavingRate = 5.0, - LogFilename = "imgui_log.txt", - WantSaveIniSettings = false, + IniSavingRate = 5.0, -- = 5.0f -- Minimum time between saving positions/sizes to .ini file, in seconds. + LogFilename = "imgui_log.txt", -- = "imgui_log.txt"-- Path to .log file (default parameter to ImGui.LogToFile when no file is specified). + WantSaveIniSettings = false, -- When manual .ini load/save is active (io.IniFilename == nil), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. Important: clear io.WantSaveIniSettings yourself after saving! - ConfigDockingNoSplit = false, - ConfigDockingNoDockingOver = false, - ConfigDockingWithShift = false, - ConfigDockingAlwaysTabBar = false, - ConfigDockingTransparentPayload = false, - ConfigViewportsNoAutoMerge = false, - ConfigViewportsNoTaskBarIcon = false, - ConfigViewportsNoDecoration = true, - ConfigViewportsNoDefaultParent = true, - ConfigViewportsPlatformFocusSetsImGuiFocus = true, + -- Docking options (when ImGuiConfigFlags.DockingEnable is set) + ConfigDockingNoSplit = false, -- = false -- Simplified docking mode: disable window splitting, so docking is limited to merging multiple windows together into tab-bars. + ConfigDockingNoDockingOver = false, -- = false -- Simplified docking mode: disable window merging into a same tab-bar, so docking is limited to splitting windows. + ConfigDockingWithShift = false, -- = false -- Enable docking with holding Shift key (reduce visual noise, allows dropping in wider space) + ConfigDockingAlwaysTabBar = false, -- = false -- [BETA] [FIXME: This currently creates regression with auto-sizing and general overhead] Make every single floating window display within a docking node. + ConfigDockingTransparentPayload = false, -- = false -- [BETA] Make window or viewport transparent when docking and only display docking boxes on the target viewport. Useful if rendering of multiple viewport cannot be synced. Best used with ConfigViewportsNoAutoMerge. + -- Viewport options (when ImGuiConfigFlags.ViewportsEnable is set) + -- (sorry for the amount of "NoXXXX" flags, which may be harder to reason about! may rework someday) + ConfigViewportsNoAutoMerge = false, -- = false; -- Set to make all floating imgui windows always create their own viewport. Otherwise, they are merged into the main host viewports when overlapping it. May also set ImGuiViewportFlags.NoAutoMerge on individual viewport. + ConfigViewportsNoTaskBarIcon = false, -- = 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. + ConfigViewportsNoDecoration = true, -- = 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). + ConfigViewportsNoDefaultParent = true, -- = true -- Disable setting OS window parent to main viewport by default. The platform backend is expected to honor `viewport->ParentViewportID` to setup a parent/child relationship between the OS windows (supported if ImGuiBackendFlags.HasParentViewport is set). When parented: child windows always appear in front of their parent. Set to false if you want viewports to automatically be parent of main viewport, otherwise all viewports will be top-level OS windows. Parent/child relationship may be set on a per-window basis using ImGuiWindowClass. + ConfigViewportsPlatformFocusSetsImGuiFocus = true, -- = 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). - ConfigMemoryCompactTimer = 60.0, + ConfigMemoryCompactTimer = 60.0, -- = 60.0f -- Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable. - MouseDrawCursor = false, + -- Miscellaneous options + -- (you can visualize and interact with all options in 'Demo->Configuration') + MouseDrawCursor = false, -- = false -- Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). Cannot be easily renamed to 'io.ConfigXXX' because this is frequently used by backend implementations. - MouseClicked = {[0] = false, [1] = false, [2] = false}, - MouseReleased = {[0] = false, [1] = false, [2] = false}, - MouseClickedCount = {[0] = 0, [1] = 0, [2] = 0}, - MouseClickedLastCount = {[0] = 0, [1] = 0, [2] = 0}, - MouseDownDuration = {[0] = -1, [1] = -1, [2] = -1}, - MouseDownDurationPrev = {[0] = -1, [1] = -1, [2] = -1}, + MouseClicked = {[0] = false, [1] = false, [2] = false}, -- Mouse button went from !Down to Down (same as MouseClickedCount[x] != 0) + MouseReleased = {[0] = false, [1] = false, [2] = false}, -- Mouse button went from Down to !Down + MouseClickedCount = {[0] = 0, [1] = 0, [2] = 0}, -- == 0 (not clicked), == 1 (same as MouseClicked[]), == 2 (double-clicked), == 3 (triple-clicked) etc. when going from !Down to Down + MouseClickedLastCount = {[0] = 0, [1] = 0, [2] = 0}, -- Count successive number of clicks. Stays valid after mouse release. Reset after another click is done. + MouseDownDuration = {[0] = -1, [1] = -1, [2] = -1}, -- Duration the mouse button has been down (0.0f == just clicked) + MouseDownDurationPrev = {[0] = -1, [1] = -1, [2] = -1}, -- Previous time the mouse button has been down - MouseDragMaxDistanceAbs = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, - MouseDragMaxDistanceSqr = {[0] = 0, [1] = 0, [2] = 0}, + MouseDragMaxDistanceAbs = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, -- Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point + MouseDragMaxDistanceSqr = {[0] = 0, [1] = 0, [2] = 0}, -- Squared maximum distance of how much mouse has traveled from the clicking point (used for moving thresholds) - MouseDownOwned = {[0] = nil, [1] = nil, [2] = nil}, - MouseDownOwnedUnlessPopupClose = {[0] = nil, [1] = nil, [2] = nil}, - MouseClickedTime = {[0] = 0, [1] = 0, [2] = 0}, - MouseReleasedTime = {[0] = 0, [1] = 0, [2] = 0}, - MouseClickedPos = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, + MouseDownOwned = {[0] = nil, [1] = nil, [2] = nil}, -- 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. + MouseDownOwnedUnlessPopupClose = {[0] = nil, [1] = nil, [2] = nil}, -- Track if button was clicked inside a dear imgui window. + MouseClickedTime = {[0] = 0, [1] = 0, [2] = 0}, -- Time of last click (used to figure out double-click) + MouseReleasedTime = {[0] = 0, [1] = 0, [2] = 0}, -- Time of last released (rarely used! but useful to handle delayed single-click when trying to disambiguate them from double-click). + MouseClickedPos = {[0] = ImVec2(), [1] = ImVec2(), [2] = ImVec2()}, -- Position at time of clicking - MouseDoubleClicked = {[0] = false, [1] = false, [2] = false}, + MouseDoubleClicked = {[0] = false, [1] = false, [2] = false}, -- Has mouse button been double-clicked? (same as MouseClickedCount[x] == 2) - MouseDoubleClickTime = 0.30, - MouseSingleClickDelay = 0.50, - MouseDoubleClickMaxDist = 6.0, - MouseDragThreshold = 6.0, - KeyRepeatDelay = 0.275, - KeyRepeatRate = 0.050, + -- Inputs Behaviors + -- (other variables, ones which are expected to be tweaked within UI code, are exposed in ImGuiStyle) + MouseDoubleClickTime = 0.30, -- = 0.30f -- Time for consecutive clicks to account as a double-click, in seconds. + MouseSingleClickDelay = 0.50, -- Time for a delayed click when using GetItemClickedCountWithSingleClickDelay() or IsMouseReleasedWithDelay(), in seconds. Must be > io.MouseDoubleClickTime. + MouseDoubleClickMaxDist = 6.0, -- = 6.0f -- Distance threshold to stay in to validate a double-click or multiple clicks, in pixels. + MouseDragThreshold = 6.0, -- = 6.0f -- Distance threshold before considering we are dragging. + KeyRepeatDelay = 0.275, -- = 0.275f -- When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + KeyRepeatRate = 0.050, -- = 0.050f -- When holding a key/button, rate at which it repeats, in seconds. KeysData = {}, -- size = ImGuiKey.NamedKey_COUNT - WantCaptureMouse = nil, - WantCaptureKeyboard = nil, - WantTextInput = nil, + WantCaptureMouse = nil, -- Set when Dear ImGui will use mouse inputs, in this case do not dispatch them to your main game/application (either way, always pass on mouse inputs to imgui). (e.g. unclicked mouse is hovering over an imgui window, widget is active, mouse was clicked over an imgui window, etc.). + WantCaptureKeyboard = nil, -- Set when Dear ImGui will use keyboard inputs, in this case do not dispatch them to your main game/application (either way, always pass keyboard inputs to imgui). (e.g. InputText active, or an imgui window is focused and navigation is enabled, etc.). + WantTextInput = nil, -- Mobile/console: when set, you may display an on-screen keyboard. This is set by Dear ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active). - Framerate = 0, + Framerate = 0, -- Estimate of application framerate (rolling average over 60 frames, based on io.DeltaTime), in frame per second. Solely for convenience. Slow applications may not want to use a moving average or may want to reset underlying buffers occasionally. MetricsRenderVertices = 0, MetricsRenderIndices = 0, MetricsRenderWindows = 0, MetricsActiveWindows = 0, - NavActive = false, - NavVisible = false, + NavActive = false, -- Keyboard/Gamepad navigation is currently allowed (will handle ImGuiKey.NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags.NoNavInputs flag. + NavVisible = false, -- Keyboard/Gamepad navigation highlight is visible and allowed (will handle ImGuiKey.NavXXX events). - MetricsRenderWindows = 0, + MetricsRenderWindows = 0, -- Number of visible windows - Fonts = nil, - FontDefault = nil, + -- Font system + Fonts = nil, -- -- Font atlas: load, rasterize and pack one or more fonts into a single texture. + FontDefault = nil, -- = nil -- Font to use on NewFrame(). Use nil to uses Fonts->Fonts[0]. - BackendPlatformUserData = nil, - BackendRendererUserData = nil, + BackendPlatformUserData = nil, -- = nil -- User data for platform backend + BackendRendererUserData = nil, -- = nil -- User data for renderer backend - InputQueueCharacters = ImVector(), + InputQueueCharacters = ImVector(), -- Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper. - AppAcceptingEvents = true, - InputQueueSurrogate = 0 + AppAcceptingEvents = true, -- Only modify via SetAppAcceptingEvents() + InputQueueSurrogate = 0 -- For AddInputCharacterUTF16() } for i = 0, ImGuiKey.NamedKey_COUNT - 1 do @@ -1134,6 +1340,7 @@ function ImGuiIO() return setmetatable(this, MT.ImGuiIO) end +-- (Optional) Support for IME (Input Method Editor) via the platform_io.Platform_SetImeDataFn() function. Handler is called during EndFrame(). --- @class ImGuiPlatformImeData --- @field WantVisible bool --- @field WantTextInput bool @@ -1145,11 +1352,11 @@ end --- @nodiscard function ImGuiPlatformImeData() return { - WantVisible = false, - WantTextInput = false, - InputPos = ImVec2(), - InputLineHeight = 0.0, - ViewportId = 0 + WantVisible = false, -- A widget wants the IME to be visible. + WantTextInput = false, -- A widget wants text input, not necessarily IME to be visible. This is automatically set to the upcoming value of io.WantTextInput. + InputPos = ImVec2(), -- Position of input cursor (for IME). + InputLineHeight = 0.0, -- Line height (for IME). + ViewportId = 0 -- ID of platform window/viewport. } end @@ -1177,26 +1384,39 @@ function ImGuiPlatformImeData_Compare(data1, data2) return true end +------------------------------------------------------------------------------- +-- [SECTION] Viewports +------------------------------------------------------------------------------- + +-- Flags stored in ImGuiViewport::Flags, giving indications to the platform backends. --- @enum ImGuiViewportFlags ImGuiViewportFlags = { None = 0, - IsPlatformWindow = bitLShift(1, 0), - IsPlatformMonitor = bitLShift(1, 1), - OwnedByApp = bitLShift(1, 2), - NoDecoration = bitLShift(1, 3), - NoTaskBarIcon = bitLShift(1, 4), - NoFocusOnAppearing = bitLShift(1, 5), - NoFocusOnClick = bitLShift(1, 6), - NoInputs = bitLShift(1, 7), - NoRendererClear = bitLShift(1, 8), - NoAutoMerge = bitLShift(1, 9), - TopMost = bitLShift(1, 10), - CanHostOtherWindows = bitLShift(1, 11), + IsPlatformWindow = bitLShift(1, 0), -- Represent a Platform Window + IsPlatformMonitor = bitLShift(1, 1), -- Represent a Platform Monitor (unused yet) + OwnedByApp = bitLShift(1, 2), -- Platform Window: Is created/managed by the user application? (rather than our backend) + NoDecoration = bitLShift(1, 3), -- Platform Window: Disable platform decorations: title bar, borders, etc. (generally set all windows, but if ImGuiConfigFlags.ViewportsDecoration is set we only set this on popups/tooltips) + NoTaskBarIcon = bitLShift(1, 4), -- Platform Window: Disable platform task bar icon (generally set on popups/tooltips, or all windows if ImGuiConfigFlags.ViewportsNoTaskBarIcon is set) + NoFocusOnAppearing = bitLShift(1, 5), -- Platform Window: Don't take focus when created. + NoFocusOnClick = bitLShift(1, 6), -- Platform Window: Don't take focus when clicked on. + NoInputs = bitLShift(1, 7), -- Platform Window: Make mouse pass through so we can drag this window while peaking behind it. + NoRendererClear = bitLShift(1, 8), -- Platform Window: Renderer doesn't need to clear the framebuffer ahead (because we will fill it entirely). + NoAutoMerge = bitLShift(1, 9), -- Platform Window: Avoid merging this window into another host window. This can only be set via ImGuiWindowClass viewport flags override (because we need to now ahead if we are going to create a viewport in the first place!). + TopMost = bitLShift(1, 10), -- Platform Window: Display on top (for tooltips only). + CanHostOtherWindows = bitLShift(1, 11), -- Viewport can host multiple imgui windows (secondary viewports are associated to a single window). -- FIXME: In practice there's still probably code making the assumption that this is always and only on the MainViewport. Will fix once we add support for "no main viewport". - IsMinimized = bitLShift(1, 12), - IsFocused = bitLShift(1, 13) + -- Output status flags (from Platform) + IsMinimized = bitLShift(1, 12), -- Platform Window: Window is minimized, can skip render. When minimized we tend to avoid using the viewport pos/size for clipping window or testing if they are contained in the viewport. + IsFocused = bitLShift(1, 13) -- Platform Window: Window is focused (last call to Platform_GetWindowFocus() returned true) } +-- - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows. +-- - With multi-viewport enabled, we extend this concept to have multiple active viewports. +-- - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode. +-- - About Main Area vs Work Area: +-- - Main Area = entire viewport. +-- - Work Area = entire viewport minus sections used by main menu bars (for platform windows), or by task bar (for platform monitor). +-- - Windows are generally trying to stay within the Work Area of their host viewport. --- @class ImGuiViewport --- @field ID ImGuiID --- @field Flags ImGuiViewportFlags @@ -1232,21 +1452,26 @@ end --- @nodiscard function ImGuiViewport() return setmetatable({ - ID = 0, - Flags = 0, - Pos = ImVec2(), - Size = ImVec2(), - FramebufferScale = ImVec2(), - WorkPos = ImVec2(), - WorkSize = ImVec2(), - DpiScale = 0, + ID = 0, -- Unique identifier for the viewport + Flags = 0, -- See ImGuiViewportFlags_ + Pos = ImVec2(), -- Main Area: Position of the viewport (Dear ImGui coordinates are the same as OS desktop/native coordinates) + Size = ImVec2(), -- Main Area: Size of the viewport. + FramebufferScale = ImVec2(), -- 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. + WorkPos = ImVec2(), -- Work Area: Position of the viewport minus task bars, menus bars, status bars (>= Pos) + WorkSize = ImVec2(), -- Work Area: Size of the viewport minus task bars, menu bars, status bars (<= Size) + DpiScale = 0, -- 1.0f = 96 DPI = No extra scale. - PlatformHandle = nil, - PlatformHandleRaw = nil, - PlatformWindowCreated = false + PlatformHandle = nil, -- void* to hold higher-level, platform window handle (e.g. HWND for Win32 backend, Uint32 WindowID for SDL, GLFWWindow* for GLFW), for FindViewportByPlatformHandle(). + PlatformHandleRaw = nil, -- void* to hold lower-level, platform-native window handle (always HWND on Win32 platform, unused for other platforms). + PlatformWindowCreated = false -- Platform window has been created (Platform_CreateWindow() has been called). This is false during the first frame where a viewport is being created. }, MT.ImGuiViewport) end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiPlatformIO + other Platform Dependent Interfaces (ImGuiPlatformMonitor, ImGuiPlatformImeData) +------------------------------------------------------------------------------- + +-- Access via ImGui.GetPlatformIO() --- @class ImGuiPlatformIO --- @field Platform_GetClipboardTextFn fun(ctx?: ImGuiContext): string --- @field Platform_CreateWindow fun(vp: ImGuiViewport) @@ -1261,29 +1486,54 @@ MT.ImGuiPlatformIO.__index = MT.ImGuiPlatformIO --- @nodiscard function ImGuiPlatformIO() local this = { - Platform_GetClipboardTextFn = nil, + ------------------------------------------------------------------------------- + -- Input - Interface with OS and Platform backend (most common stuff) + ------------------------------------------------------------------------------- + + -- Optional: Access OS clipboard + -- (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + Platform_GetClipboardTextFn = nil, -- Should return nil on failure (e.g. clipboard data is not text). Platform_SetClipboardTextFn = nil, + -- Optional: Open link/folder/file in OS Shell + -- (default to use ShellExecuteW() on Windows, system() on Linux/Mac. expected to return false on failure, but some platforms may always return true) Platform_OpenInShellFn = nil, Platform_OpenInShellUserData = nil, + ------------------------------------------------------------------------------- + -- Input - Interface with Renderer Backend + ------------------------------------------------------------------------------- + + -- Optional: Maximum texture size supported by renderer (used to adjust how we size textures). 0 if not known. Renderer_TextureMaxWidth = 0, Renderer_TextureMaxHeight = 0, + -- Written by some backends during ImGui_ImplXXXX_RenderDrawData() call to point backend_specific ImGui_ImplXXXX_RenderState* structure. Renderer_RenderState = nil, + -- (Optional) Monitor list + -- - Updated by: app/backend. Update every frame to dynamically support changing monitor or DPI configuration. + -- - Used by: dear imgui to query DPI info, clamp popups/tooltips within same monitor and not have them straddle monitors. Monitors = ImVector(), - Textures = ImVector(), - Viewports = ImVector(), + -- 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. + Textures = ImVector(), -- 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") + Viewports = ImVector(), -- Main viewports, followed by all secondary viewports. + -- Optional: Platform locale + -- [Experimental] Configure decimal point e.g. '.' or ',' useful for some languages (e.g. German), generally pulled from *localeconv()->decimal_point Platform_LocaleDecimalPoint = 46, -- '.' - Platform_OnChangedViewport = nil, + Platform_OnChangedViewport = nil, -- (Optional) [BETA] FIXME-DPI: DPI handling: Called during Begin() every time the viewport we are outputting into changes, so backend has a chance to swap fonts to adjust style. } return setmetatable(this, MT.ImGuiPlatformIO) end +-- (Optional) This is required when enabling multi-viewport. Represent the bounds of each connected monitor/display and their DPI. +-- We use this information for multiple DPI support + clamping the position of popups and tooltips so they don't straddle multiple monitors. --- @class ImGuiPlatformMonitor --- @field MainPos ImVec2 --- @field MainSize ImVec2 @@ -1296,45 +1546,52 @@ end --- @nodiscard function ImGuiPlatformMonitor() return { - MainPos = ImVec2(0, 0), + MainPos = ImVec2(0, 0), -- Coordinates of the area displayed on this monitor (Min = upper left, Max = bottom right) MainSize = ImVec2(0, 0), - WorkPos = ImVec2(0, 0), + WorkPos = ImVec2(0, 0), -- Coordinates without task bars / side bars / menu bars. Used to avoid positioning popups/tooltips inside this region. If you don't have this info, please copy the value for MainPos/MainSize. WorkSize = ImVec2(0, 0), - DpiScale = 1.0, + DpiScale = 1.0, -- 1.0f = 96 DPI - PlatformHandle = nil + PlatformHandle = nil -- Backend dependant data (e.g. HMONITOR, GLFWmonitor*, SDL Display Index, NSScreen*) } end +------------------------------------------------------------------------------- +-- [SECTION] Flags & Enumerations +------------------------------------------------------------------------------- + +-- Flags for ImGui.Begin() +-- (Those are per-window flags. There are shared flags in ImGuiIO: io.ConfigWindowsResizeFromEdges and io.ConfigWindowsMoveFromTitleBarOnly) --- @enum ImGuiWindowFlags ImGuiWindowFlags = { None = 0, - NoTitleBar = bitLShift(1, 0), - NoResize = bitLShift(1, 1), - NoMove = bitLShift(1, 2), - NoScrollbar = bitLShift(1, 3), - NoScrollWithMouse = bitLShift(1, 4), - NoCollapse = bitLShift(1, 5), - AlwaysAutoResize = bitLShift(1, 6), - NoBackground = bitLShift(1, 7), - NoSavedSettings = bitLShift(1, 8), - NoMouseInputs = bitLShift(1, 9), - MenuBar = bitLShift(1, 10), - HorizontalScrollbar = bitLShift(1, 11), - NoFocusOnAppearing = bitLShift(1, 12), - NoBringToFrontOnFocus = bitLShift(1, 13), - AlwaysVerticalScrollbar = bitLShift(1, 14), - AlwaysHorizontalScrollbar = bitLShift(1, 15), - NoNavInputs = bitLShift(1, 16), - NoNavFocus = bitLShift(1, 17), - UnsavedDocument = bitLShift(1, 18), - NoDocking = bitLShift(1, 19), - DockNodeHost = bitLShift(1, 23), - ChildWindow = bitLShift(1, 24), - Tooltip = bitLShift(1, 25), - Popup = bitLShift(1, 26), - Modal = bitLShift(1, 27), - ChildMenu = bitLShift(1, 28) + NoTitleBar = bitLShift(1, 0), -- Disable title-bar + NoResize = bitLShift(1, 1), -- Disable user resizing with the lower-right grip + NoMove = bitLShift(1, 2), -- Disable user moving the window + NoScrollbar = bitLShift(1, 3), -- Disable scrollbars (window can still scroll with mouse or programmatically) + NoScrollWithMouse = bitLShift(1, 4), -- Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set. + NoCollapse = bitLShift(1, 5), -- Disable user collapsing window by double-clicking on it. Also referred to as Window Menu Button (e.g. within a docking node). + AlwaysAutoResize = bitLShift(1, 6), -- Resize every window to its content every frame + NoBackground = bitLShift(1, 7), -- Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f). + NoSavedSettings = bitLShift(1, 8), -- Never load/save settings in .ini file + NoMouseInputs = bitLShift(1, 9), -- Disable catching mouse, hovering test with pass through. + MenuBar = bitLShift(1, 10), -- Has a menu-bar + HorizontalScrollbar = bitLShift(1, 11), -- Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + NoFocusOnAppearing = bitLShift(1, 12), -- Disable taking focus when transitioning from hidden to visible state + NoBringToFrontOnFocus = bitLShift(1, 13), -- Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus) + AlwaysVerticalScrollbar = bitLShift(1, 14), -- Always show vertical scrollbar (even if ContentSize.y < Size.y) + AlwaysHorizontalScrollbar = bitLShift(1, 15), -- Always show horizontal scrollbar (even if ContentSize.x < Size.x) + NoNavInputs = bitLShift(1, 16), -- No keyboard/gamepad navigation within the window + NoNavFocus = bitLShift(1, 17), -- No focusing toward this window with keyboard/gamepad navigation (e.g. skipped by Ctrl+Tab) + UnsavedDocument = bitLShift(1, 18), -- Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. + NoDocking = bitLShift(1, 19), -- Disable docking of this window + -- [Internal] + DockNodeHost = bitLShift(1, 23), -- Don't use! For internal use by Begin()/NewFrame() + ChildWindow = bitLShift(1, 24), -- Don't use! For internal use by BeginChild() + Tooltip = bitLShift(1, 25), -- Don't use! For internal use by BeginTooltip() + Popup = bitLShift(1, 26), -- Don't use! For internal use by BeginPopup() + Modal = bitLShift(1, 27), -- Don't use! For internal use by BeginPopupModal() + ChildMenu = bitLShift(1, 28) -- Don't use! For internal use by BeginMenu() } -- [Internal] @@ -1342,51 +1599,74 @@ ImGuiWindowFlags.NoNav = bitOr(ImGuiWindowFlags.NoNavInputs, ImGuiWindowF ImGuiWindowFlags.NoDecoration = bitOr(ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoCollapse) ImGuiWindowFlags.NoInputs = bitOr(ImGuiWindowFlags.NoMouseInputs, ImGuiWindowFlags.NoNavInputs, ImGuiWindowFlags.NoNavFocus) +-- Flags for ImGui.PushItemFlag() +-- (Those are shared by all submitted items) --- @enum ImGuiItemFlags ImGuiItemFlags = { - None = 0, - NoTabStop = bitLShift(1, 0), - NoNav = bitLShift(1, 1), - NoNavDefaultFocus = bitLShift(1, 2), - ButtonRepeat = bitLShift(1, 3), - AutoClosePopups = bitLShift(1, 4), - AllowDuplicateId = bitLShift(1, 5), - Disabled = bitLShift(1, 6), - LiveEditOnInputText = bitLShift(1, 7), - LiveEditOnInputScalar = bitLShift(1, 8) + None = 0, -- Default: + NoTabStop = bitLShift(1, 0), -- false -- Disable keyboard tabbing. This is a "lighter" version of ImGuiItemFlags.NoNav. + NoNav = bitLShift(1, 1), -- false -- Disable any form of focusing: keyboard/gamepad directional navigation and SetKeyboardFocusHere() calls. + NoNavDefaultFocus = bitLShift(1, 2), -- false -- Disable item being a candidate for default focus (e.g. used by title bar items). + ButtonRepeat = bitLShift(1, 3), -- false -- Any button-like behavior will have repeat mode enabled (based on io.KeyRepeatDelay and io.KeyRepeatRate values). Note that you can also call IsItemActive() after any button to tell if it is being held. + AutoClosePopups = bitLShift(1, 4), -- true -- MenuItem()/Selectable() automatically close their parent popup window. + AllowDuplicateId = bitLShift(1, 5), -- false -- Allow submitting an item with the same identifier as an item already submitted this frame without triggering a warning tooltip if io.ConfigDebugHighlightIdConflicts is set. + Disabled = bitLShift(1, 6), -- false -- [Internal] Disable interactions. DOES NOT affect visuals. This is used by BeginDisabled()/EndDisabled() and only provided here so you can read back via GetItemFlags(). + ------------------------------------------------------------------------------- + -- LiveEdit refers to applying edits to backing variables _while_ typing a value using the keyboard. + -- Widget: | Input: | w/ LiveEdit: | Output: + -- InputText() | "123" | on(default) | "1" then "12" then "123" + -- InputText() | "123" | off | "123" after validating or tabbing out or losing focus. + -- DragFloat(), SliderInt(), etc. | "123" | on* | 1 then 12 then 123 + -- DragFloat(), SliderInt(), etc. | "123" | off(default)* | 123 after validation or tabbing out or losing focus. + -- (*) Since 1.92.9 (July 2026), ImGuiItemFlags.LiveEditOnInputScalar is OFF by default. In prior version it was ON for everything. + ------------------------------------------------------------------------------- + LiveEditOnInputText = bitLShift(1, 7), -- true -- InputText: apply keyboard edits to backing value while typing. Otherwise, edits are applied when validating, tabbing out or losing focus. + LiveEditOnInputScalar = bitLShift(1, 8) -- false -- DragXXX, SliderXXX, InputScalar: apply keyboard edits to backing value while typing. Otherwise, edits are applied when validating, tabbing out or losing focus. } ImGuiItemFlags.LiveEditOnInput = bitOr(ImGuiItemFlags.LiveEditOnInputText, ImGuiItemFlags.LiveEditOnInputScalar) +-- Status flags for an already submitted item +-- - output: stored in g.LastItemData.StatusFlags --- @enum ImGuiItemStatusFlags ImGuiItemStatusFlags = { None = 0, - HoveredRect = bitLShift(1, 0), - HasDisplayRect = bitLShift(1, 1), - Edited = bitLShift(1, 2), - ToggledSelection = bitLShift(1, 3), - ToggledOpen = bitLShift(1, 4), - HasDeactivated = bitLShift(1, 5), - Deactivated = bitLShift(1, 6), - HoveredWindow = bitLShift(1, 7), - Visible = bitLShift(1, 8), - HasClipRect = bitLShift(1, 9), - HasShortcut = bitLShift(1, 10), - EditedInternal = bitLShift(1, 11) + HoveredRect = bitLShift(1, 0), -- Mouse position is within item rectangle (does NOT mean that the window is in correct z-order and can be hovered!, this is only one part of the most-common IsItemHovered test) + HasDisplayRect = bitLShift(1, 1), -- g.LastItemData.DisplayRect is valid + Edited = bitLShift(1, 2), -- Value exposed by item was edited in the current frame (should match the bool return value of most widgets) + ToggledSelection = bitLShift(1, 3), -- Set when Selectable(), TreeNode() reports toggling a selection. We can't report "Selected", only state changes, in order to easily handle clipping with less issues. + ToggledOpen = bitLShift(1, 4), -- Set when TreeNode() reports toggling their open state. + HasDeactivated = bitLShift(1, 5), -- Set if the widget/group is able to provide data for the ImGuiItemStatusFlags.Deactivated flag. + Deactivated = bitLShift(1, 6), -- Only valid if ImGuiItemStatusFlags.HasDeactivated is set. + HoveredWindow = bitLShift(1, 7), -- Override the HoveredWindow test to allow cross-window hover testing. + Visible = bitLShift(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()). + HasClipRect = bitLShift(1, 9), -- g.LastItemData.ClipRect is valid. + HasShortcut = bitLShift(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. + EditedInternal = bitLShift(1, 11) -- Similar to ImGuiItemStatusFlags.Edited but bypassing ImGuiItemFlags.NoMarkEdited. } +-- Flags for ImGui.BeginChild() +-- (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. +-- - This allows BeginChild() to return false when not within boundaries (e.g. when scrolling), which is more optimal. BUT it won't update its auto-size while clipped. +-- While not perfect, it is a better default behavior as the always-on performance gain is more valuable than the occasional "resizing after becoming visible again" glitch. +-- - You may also use ImGuiChildFlags.AlwaysAutoResize to force an update even when child window is not in view. +-- HOWEVER PLEASE UNDERSTAND THAT DOING SO WILL PREVENT BeginChild() FROM EVER RETURNING FALSE, disabling benefits of coarse clipping. --- @enum ImGuiChildFlags ImGuiChildFlags = { None = 0, - Borders = bitLShift(1, 0), - AlwaysUseWindowPadding = bitLShift(1, 1), - ResizeX = bitLShift(1, 2), - ResizeY = bitLShift(1, 3), - AutoResizeX = bitLShift(1, 4), - AutoResizeY = bitLShift(1, 5), - AlwaysAutoResize = bitLShift(1, 6), - FrameStyle = bitLShift(1, 7), - NavFlattened = bitLShift(1, 8) + Borders = bitLShift(1, 0), -- Show an outer border and enable WindowPadding. (IMPORTANT: this is always == 1 == true for legacy reason) + AlwaysUseWindowPadding = bitLShift(1, 1), -- Pad with style.WindowPadding even if no border are drawn (no padding by default for non-bordered child windows because it makes more sense) + ResizeX = bitLShift(1, 2), -- Allow resize from right border (layout direction). Enable .ini saving (unless ImGuiWindowFlags.NoSavedSettings passed to window flags) + ResizeY = bitLShift(1, 3), -- Allow resize from bottom border (layout direction). " + AutoResizeX = bitLShift(1, 4), -- Enable auto-resizing width. Read "IMPORTANT: Size measurement" details above. + AutoResizeY = bitLShift(1, 5), -- Enable auto-resizing height. Read "IMPORTANT: Size measurement" details above. + AlwaysAutoResize = bitLShift(1, 6), -- Combined with AutoResizeX/AutoResizeY. Always measure size even when child is hidden, always return true, always disable clipping optimization! NOT RECOMMENDED. + FrameStyle = bitLShift(1, 7), -- Style the child window like a framed item: use FrameBg, FrameRounding, FrameBorderSize, FramePadding instead of ChildBg, ChildRounding, ChildBorderSize, WindowPadding. + NavFlattened = bitLShift(1, 8) -- [BETA] Share focus scope, allow keyboard/gamepad navigation to cross over parent border to this child or between sibling child windows. } ImGuiChildFlags.ResizeBoth = bitOr(ImGuiChildFlags.ResizeX, ImGuiChildFlags.ResizeY) @@ -1403,25 +1683,30 @@ ImGuiNextItemDataFlags = { HasColorMarker = bitLShift(1, 5) } +-- Flags for ImDrawList functions --- @enum ImDrawFlags ImDrawFlags = { None = 0, - RoundCornersTopLeft = bitLShift(1, 4), - RoundCornersTopRight = bitLShift(1, 5), - RoundCornersBottomLeft = bitLShift(1, 6), - RoundCornersBottomRight = bitLShift(1, 7), - RoundCornersNone = bitLShift(1, 8), - Closed = bitLShift(1, 9) + -- - Rounding default to ImDrawFlags.RoundCornersAll when 'rounding > 0'. + -- - So you only need to use the ImDrawFlags.RoundCornersXXX flags if you want a special configuration (e.g. a rectangle with one rounded corner). + -- Rounding for AddRectXXX(), PathRect() ------ -- Prim/Scope? + RoundCornersTopLeft = bitLShift(1, 4), -- OK -- -- Round top-left corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersTopRight = bitLShift(1, 5), -- OK -- -- Round top-right corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersBottomLeft = bitLShift(1, 6), -- OK -- -- Round bottom-left corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersBottomRight = bitLShift(1, 7), -- OK -- -- Round bottom-right corner only (when 'rounding > 0.0f', we default to all corners). + RoundCornersNone = bitLShift(1, 8), -- OK -- -- Disable rounding even when 'rounding > 0.0f'. This value is NOT zero, it is NOT an implicit flag! + -- Stroke Options ----------------------------- -- Prim/Scope? + Closed = bitLShift(1, 9) -- OK -- -- PathStroke(), AddPolyline(): specify that shape should be closed. } ImDrawFlags.RoundCornersTop = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight) ImDrawFlags.RoundCornersBottom = bitOr(ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight) ImDrawFlags.RoundCornersLeft = bitOr(ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersTopLeft) ImDrawFlags.RoundCornersRight = bitOr(ImDrawFlags.RoundCornersBottomRight, ImDrawFlags.RoundCornersTopRight) -ImDrawFlags.RoundCornersAll = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight, ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight) +ImDrawFlags.RoundCornersAll = bitOr(ImDrawFlags.RoundCornersTopLeft, ImDrawFlags.RoundCornersTopRight, ImDrawFlags.RoundCornersBottomLeft, ImDrawFlags.RoundCornersBottomRight) -- (Default!!) ImDrawFlags.RoundCornersDefault_ = ImDrawFlags.RoundCornersAll -ImDrawFlags.RoundCornersMask_ = bitOr(ImDrawFlags.RoundCornersAll, ImDrawFlags.RoundCornersNone) -ImDrawFlags.InvalidMask_ = 0x8000000F +ImDrawFlags.RoundCornersMask_ = bitOr(ImDrawFlags.RoundCornersAll, ImDrawFlags.RoundCornersNone) -- [Internal] +ImDrawFlags.InvalidMask_ = 0x8000000F -- [Internal] == 0x8000000F. Reserved to detect misuses. --- @enum ImDrawListFlags ImDrawListFlags = { @@ -1433,155 +1718,195 @@ ImDrawListFlags = { TextNoPixelSnap = bitLShift(1, 4) } +-- 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, - NoLoadError = bitLShift(1, 1), - NoLoadGlyphs = bitLShift(1, 2), - LockBakedSizes = bitLShift(1, 3), - ImplicitRefSize = bitLShift(1, 4) + NoLoadError = bitLShift(1, 1), -- Disable throwing an error/assert when calling AddFontXXX() with missing file/data. Calling code is expected to check AddFontXXX() return value. + NoLoadGlyphs = bitLShift(1, 2), -- [Internal] Disable loading new glyphs. + LockBakedSizes = bitLShift(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. + ImplicitRefSize = bitLShift(1, 4) -- [Internal] Reference size was not set explicitly. } +-- Enumeration for AddMouseSourceEvent() actual source of Mouse Input data. +-- Historically we use "Mouse" terminology everywhere to indicate pointer data, e.g. MousePos, IsMousePressed(), io.AddMousePosEvent() +-- But that "Mouse" data can come from different source which occasionally may be useful for application to know about. +-- You can submit a change of pointer type using io.AddMouseSourceEvent(). --- @enum ImGuiMouseSource ImGuiMouseSource = { - Mouse = 0, - TouchScreen = 1, - Pen = 2, + Mouse = 0, -- Input is coming from an actual mouse. + TouchScreen = 1, -- Input is coming from a touch screen (no hovering prior to initial press, less precise initial press aiming, dual-axis wheeling possible). + Pen = 2, -- Input is coming from a pressure/magnetic pen (often used in conjunction with high-sampling rates). COUNT = 3 } +-- Enumeration for ImGui.SetNextWindow***(), SetWindow***(), SetNextItem***() functions +-- Represent a condition. +-- Important: Treat as a regular enum! Do NOT combine multiple values using binary operators! All the functions above treat 0 as a shortcut to ImGuiCond.Always. --- @enum ImGuiCond ImGuiCond = { - None = 0, - Always = bitLShift(1, 0), - Once = bitLShift(1, 1), - FirstUseEver = bitLShift(1, 2), - Appearing = bitLShift(1, 3) + None = 0, -- No condition (always set the variable), same as _Always + Always = bitLShift(1, 0), -- No condition (always set the variable), same as _None + Once = bitLShift(1, 1), -- Set the variable once per runtime session (only the first call will succeed) + FirstUseEver = bitLShift(1, 2), -- Set the variable if the object/window has no persistently saved data (no entry in .ini file) + Appearing = bitLShift(1, 3) -- Set the variable if the object/window is appearing after being hidden/inactive (or the first time) } +-- Flags for Shortcut(), SetNextItemShortcut(), +-- (and for upcoming extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() that are still in imgui_internal.h) +-- Don't mistake with ImGuiInputTextFlags! (which is for ImGui.InputText() function) --- @enum ImGuiInputFlags ImGuiInputFlags = { None = 0, - Repeat = bitLShift(1, 0), - RouteActive = bitLShift(1, 10), - RouteFocused = bitLShift(1, 11), - RouteGlobal = bitLShift(1, 12), - RouteAlways = bitLShift(1, 13), - RouteOverFocused = bitLShift(1, 14), - RouteOverActive = bitLShift(1, 15), - RouteUnlessBgFocused = bitLShift(1, 16), - RouteFromRootWindow = bitLShift(1, 17), - Tooltip = bitLShift(1, 18) + Repeat = bitLShift(1, 0), -- Enable repeat. Return true on successive repeats. Default for legacy IsKeyPressed(). NOT Default for legacy IsMouseClicked(). MUST BE == 1. + -- Flags for Shortcut(), SetNextItemShortcut() + -- - Routing policies: RouteGlobal+OverActive >> RouteActive or RouteFocused (if owner is active item) >> RouteGlobal+OverFocused >> RouteFocused (if in focused window stack) >> RouteGlobal. + -- - Default policy is RouteFocused. Can select only 1 policy among all available. + RouteActive = bitLShift(1, 10), -- Route to active item only. + RouteFocused = bitLShift(1, 11), -- Route to windows in the focus stack (DEFAULT). Deep-most focused window takes inputs. Active item takes inputs over deep-most focused window. + RouteGlobal = bitLShift(1, 12), -- Global route (unless a focused window or active item registered the route). + RouteAlways = bitLShift(1, 13), -- Do not register route, poll keys directly. + -- - Routing options + RouteOverFocused = bitLShift(1, 14), -- Option: global route: higher priority than focused route (unless active item in focused route). + RouteOverActive = bitLShift(1, 15), -- Option: global route: higher priority than active item. Unlikely you need to use that: will interfere with every active items, e.g. Ctrl+A registered by InputText will be overridden by this. May not be fully honored as user/internal code is likely to always assume they can access keys when active. + RouteUnlessBgFocused = bitLShift(1, 16), -- Option: global route: will not be applied if underlying background/void is focused (== no Dear ImGui windows are focused). Useful for overlay applications. + RouteFromRootWindow = bitLShift(1, 17), -- Option: route evaluated from the point of view of root window rather than current window. + -- Flags for SetNextItemShortcut() + Tooltip = bitLShift(1, 18) -- Automatically display a tooltip when hovering item [BETA] Unsure of right api (opt-in/opt-out) } +-- Flags for InvisibleButton() [extended in imgui_internal.h] --- @enum ImGuiButtonFlags ImGuiButtonFlags = { None = 0, - MouseButtonLeft = bitLShift(1, 0), - MouseButtonRight = bitLShift(1, 1), - MouseButtonMiddle = bitLShift(1, 2), - EnableNav = bitLShift(1, 3), - PressedOnClick = bitLShift(1, 4), - PressedOnClickRelease = bitLShift(1, 5), - PressedOnClickReleaseAnywhere = bitLShift(1, 6), - PressedOnRelease = bitLShift(1, 7), - PressedOnDoubleClick = bitLShift(1, 8), - PressedOnDragDropHold = bitLShift(1, 9), - FlattenChildren = bitLShift(1, 11), - AllowOverlap = bitLShift(1, 12), - AlignTextBaseLine = bitLShift(1, 15), - NoKeyModsAllowed = bitLShift(1, 16), - NoHoldingActiveId = bitLShift(1, 17), - NoNavFocus = bitLShift(1, 18), - NoHoveredOnFocus = bitLShift(1, 19), - NoSetKeyOwner = bitLShift(1, 20), - NoTestKeyOwner = bitLShift(1, 21), - NoFocus = bitLShift(1, 22) + MouseButtonLeft = bitLShift(1, 0), -- React on left mouse button (default) + MouseButtonRight = bitLShift(1, 1), -- React on right mouse button + MouseButtonMiddle = bitLShift(1, 2), -- React on center mouse button + EnableNav = bitLShift(1, 3), -- InvisibleButton(): do not disable navigation/tabbing. Otherwise disabled by default. + PressedOnClick = bitLShift(1, 4), -- return true on click (mouse down event) + PressedOnClickRelease = bitLShift(1, 5), -- [Default] return true on click + release on same item <-- this is what the majority of Button are using + PressedOnClickReleaseAnywhere = bitLShift(1, 6), -- return true on click + release even if the release event is not done while hovering the item + PressedOnRelease = bitLShift(1, 7), -- return true on release (default requires click+release). Prior to 2026/03/20 this implied ImGuiButtonFlags.NoHoldingActiveId but they are separate now. + PressedOnDoubleClick = bitLShift(1, 8), -- return true on double-click (default requires click+release) + PressedOnDragDropHold = bitLShift(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 -> use ImGuiItemFlags.ButtonRepeat instead. + FlattenChildren = bitLShift(1, 11), -- allow interactions even if a child window is overlapping + AllowOverlap = bitLShift(1, 12), -- Hit testing will allow subsequent widgets to overlap this one. Require previous frame HoveredId to match before being usable. Shortcut to calling SetNextItemAllowOverlap(). + --ImGuiButtonFlags.DontClosePopups = 1 << 13, -- disable automatically closing parent popup on press + --ImGuiButtonFlags.Disabled = 1 << 14, -- disable interactions -> use BeginDisabled() or ImGuiItemFlags.Disabled + AlignTextBaseLine = bitLShift(1, 15), -- vertically align button to match text baseline - ButtonEx() only -- FIXME: Should be removed and handled by SmallButton(), not possible currently because of DC.CursorPosPrevLine + NoKeyModsAllowed = bitLShift(1, 16), -- disable mouse interaction if a key modifier is held + NoHoldingActiveId = bitLShift(1, 17), -- don't set ActiveId while holding the mouse (ImGuiButtonFlags.PressedOnClick only) + NoNavFocus = bitLShift(1, 18), -- don't override navigation focus when activated (FIXME: this is essentially used every time an item uses ImGuiItemFlags.NoNav, but because legacy specs don't requires LastItemData to be set ButtonBehavior(), we can't poll g.LastItemData.ItemFlags) + NoHoveredOnFocus = bitLShift(1, 19), -- don't report as hovered when nav focus is on this item + NoSetKeyOwner = bitLShift(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!) + NoTestKeyOwner = bitLShift(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!) + NoFocus = bitLShift(1, 22) -- [EXPERIMENTAL: Not very well specced]. Don't focus parent window when clicking. } -ImGuiButtonFlags.MouseButtonMask_ = bitOr(ImGuiButtonFlags.MouseButtonLeft, ImGuiButtonFlags.MouseButtonRight, ImGuiButtonFlags.MouseButtonMiddle) +ImGuiButtonFlags.MouseButtonMask_ = bitOr(ImGuiButtonFlags.MouseButtonLeft, ImGuiButtonFlags.MouseButtonRight, ImGuiButtonFlags.MouseButtonMiddle) -- [Internal] ImGuiButtonFlags.PressedOnMask_ = bitOr(ImGuiButtonFlags.PressedOnClick, ImGuiButtonFlags.PressedOnClickRelease, ImGuiButtonFlags.PressedOnClickReleaseAnywhere, ImGuiButtonFlags.PressedOnRelease, ImGuiButtonFlags.PressedOnDoubleClick, ImGuiButtonFlags.PressedOnDragDropHold) ImGuiButtonFlags.PressedOnDefault_ = ImGuiButtonFlags.PressedOnClickRelease ImGuiButtonFlags.NoKeyModifiers = ImGuiButtonFlags.NoKeyModsAllowed +-- Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure. +-- - The enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. +-- During initialization or between frames, feel free to just poke into ImGuiStyle directly. +-- - When changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type. --- @enum ImGuiStyleVar ImGuiStyleVar = { - Alpha = 0, - DisabledAlpha = 1, - WindowPadding = 2, - WindowRounding = 3, - WindowBorderSize = 4, - WindowMinSize = 5, - WindowTitleAlign = 6, - ChildRounding = 7, - ChildBorderSize = 8, - PopupRounding = 9, - PopupBorderSize = 10, - FramePadding = 11, - FrameRounding = 12, - FrameBorderSize = 13, - ItemSpacing = 14, - ItemInnerSpacing = 15, - IndentSpacing = 16, - CellPadding = 17, - ScrollbarSize = 18, - ScrollbarRounding = 19, - ScrollbarPadding = 20, - GrabMinSize = 21, - GrabRounding = 22, - ImageRounding = 23, - ImageBorderSize = 24, - TabRounding = 25, - TabBorderSize = 26, - TabMinWidthBase = 27, - TabMinWidthShrink = 28, - TabBarBorderSize = 29, - TabBarOverlineSize = 30, - TableAngledHeadersAngle = 31, - TableAngledHeadersTextAlign = 32, - TreeLinesSize = 33, - TreeLinesRounding = 34, - MenuItemRounding = 35, - SelectableRounding = 36, - DragDropTargetRounding = 37, - ButtonTextAlign = 38, - SelectableTextAlign = 39, - SeparatorTextBorderSize = 40, - SeparatorTextAlign = 41, - SeparatorTextPadding = 42, + -- Enum name -------------------------- -- Member in ImGuiStyle structure (see ImGuiStyle for descriptions) + Alpha = 0, -- float Alpha + DisabledAlpha = 1, -- float DisabledAlpha + WindowPadding = 2, -- ImVec2 WindowPadding + WindowRounding = 3, -- float WindowRounding + WindowBorderSize = 4, -- float WindowBorderSize + WindowMinSize = 5, -- ImVec2 WindowMinSize + WindowTitleAlign = 6, -- ImVec2 WindowTitleAlign + ChildRounding = 7, -- float ChildRounding + ChildBorderSize = 8, -- float ChildBorderSize + PopupRounding = 9, -- float PopupRounding + PopupBorderSize = 10, -- float PopupBorderSize + FramePadding = 11, -- ImVec2 FramePadding + FrameRounding = 12, -- float FrameRounding + FrameBorderSize = 13, -- float FrameBorderSize + ItemSpacing = 14, -- ImVec2 ItemSpacing + ItemInnerSpacing = 15, -- ImVec2 ItemInnerSpacing + IndentSpacing = 16, -- float IndentSpacing + CellPadding = 17, -- ImVec2 CellPadding + ScrollbarSize = 18, -- float ScrollbarSize + ScrollbarRounding = 19, -- float ScrollbarRounding + ScrollbarPadding = 20, -- float ScrollbarPadding + GrabMinSize = 21, -- float GrabMinSize + GrabRounding = 22, -- float GrabRounding + ImageRounding = 23, -- float ImageRounding + ImageBorderSize = 24, -- float ImageBorderSize + TabRounding = 25, -- float TabRounding + TabBorderSize = 26, -- float TabBorderSize + TabMinWidthBase = 27, -- float TabMinWidthBase + TabMinWidthShrink = 28, -- float TabMinWidthShrink + TabBarBorderSize = 29, -- float TabBarBorderSize + TabBarOverlineSize = 30, -- float TabBarOverlineSize + TableAngledHeadersAngle = 31, -- float TableAngledHeadersAngle + TableAngledHeadersTextAlign = 32, -- ImVec2 TableAngledHeadersTextAlign + TreeLinesSize = 33, -- float TreeLinesSize + TreeLinesRounding = 34, -- float TreeLinesRounding + MenuItemRounding = 35, -- float MenuItemRounding + SelectableRounding = 36, -- float SelectableRounding + DragDropTargetRounding = 37, -- float DragDropTargetRounding + ButtonTextAlign = 38, -- ImVec2 ButtonTextAlign + SelectableTextAlign = 39, -- ImVec2 SelectableTextAlign + SeparatorTextBorderSize = 40, -- float SeparatorTextBorderSize + SeparatorTextAlign = 41, -- ImVec2 SeparatorTextAlign + SeparatorTextPadding = 42, -- ImVec2 SeparatorTextPadding COUNT = 43 } +-- Flags for ImGui.IsItemHovered(), ImGui.IsWindowHovered() +-- Note: if you are trying to check whether your mouse should be dispatched to Dear ImGui or to your app, you should use 'io.WantCaptureMouse' instead! Please read the FAQ! +-- Note: windows with the ImGuiWindowFlags.NoInputs flag are ignored by IsWindowHovered() calls. --- @enum ImGuiHoveredFlags ImGuiHoveredFlags = { - None = 0, - ChildWindows = bitLShift(1, 0), - RootWindow = bitLShift(1, 1), - AnyWindow = bitLShift(1, 2), - NoPopupHierarchy = bitLShift(1, 3), - DockHierarchy = bitLShift(1, 4), - AllowWhenBlockedByPopup = bitLShift(1, 5), - AllowWhenBlockedByActiveItem = bitLShift(1, 7), - AllowWhenOverlappedByItem = bitLShift(1, 8), - AllowWhenOverlappedByWindow = bitLShift(1, 9), - AllowWhenDisabled = bitLShift(1, 10), - NoNavOverride = bitLShift(1, 11), - ForTooltip = bitLShift(1, 12), - Stationary = bitLShift(1, 13), - DelayNone = bitLShift(1, 14), - DelayShort = bitLShift(1, 15), - DelayNormal = bitLShift(1, 16), - NoSharedDelay = bitLShift(1, 17) + None = 0, -- Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them. + ChildWindows = bitLShift(1, 0), -- IsWindowHovered() only: Return true if any children of the window is hovered + RootWindow = bitLShift(1, 1), -- IsWindowHovered() only: Test from root window (top most parent of the current hierarchy) + AnyWindow = bitLShift(1, 2), -- IsWindowHovered() only: Return true if any window is hovered + NoPopupHierarchy = bitLShift(1, 3), -- IsWindowHovered() only: Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + DockHierarchy = bitLShift(1, 4), -- IsWindowHovered() only: Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) + AllowWhenBlockedByPopup = bitLShift(1, 5), -- Return true even if a popup window is normally blocking access to this item/window + --ImGuiHoveredFlags.AllowWhenBlockedByModal = 1 << 6, -- Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet. + AllowWhenBlockedByActiveItem = bitLShift(1, 7), -- Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns. + AllowWhenOverlappedByItem = bitLShift(1, 8), -- IsItemHovered() only: Return true even if the item uses AllowOverlap mode and is overlapped by another hoverable item. + AllowWhenOverlappedByWindow = bitLShift(1, 9), -- IsItemHovered() only: Return true even if the position is obstructed or overlapped by another window. + AllowWhenDisabled = bitLShift(1, 10), -- IsItemHovered() only: Return true even if the item is disabled + NoNavOverride = bitLShift(1, 11), -- IsItemHovered() only: Disable using keyboard/gamepad navigation state when active, always query mouse + -- Tooltips mode + -- - typically used in IsItemHovered() + SetTooltip() sequence. + -- - this is a shortcut to pull flags from 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav' where you can reconfigure desired behavior. + -- e.g. 'HoverFlagsForTooltipMouse' defaults to 'ImGuiHoveredFlags.Stationary | ImGuiHoveredFlags.DelayShort | ImGuiHoveredFlags.AllowWhenDisabled'. + -- - for frequently actioned or hovered items providing a tooltip, you want may to use ImGuiHoveredFlags.ForTooltip (stationary + delay) so the tooltip doesn't show too often. + -- - for items which main purpose is to be hovered, or items with low affordance, or in less consistent apps, prefer no delay or shorter delay. + ForTooltip = bitLShift(1, 12), -- Shortcut for standard flags when using IsItemHovered() + SetTooltip() sequence. + -- (Advanced) Mouse Hovering delays. + -- - generally you can use ImGuiHoveredFlags.ForTooltip to use application-standardized flags. + -- - use those if you need specific overrides. + Stationary = bitLShift(1, 13), -- Require mouse to be stationary for style.HoverStationaryDelay (~0.15 sec) _at least one time_. After this, can move on same item/window. Using the stationary test tends to reduces the need for a long delay. + DelayNone = bitLShift(1, 14), -- IsItemHovered() only: Return true immediately (default). As this is the default you generally ignore this. + DelayShort = bitLShift(1, 15), -- IsItemHovered() only: Return true after style.HoverDelayShort elapsed (~0.15 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). + DelayNormal = bitLShift(1, 16), -- IsItemHovered() only: Return true after style.HoverDelayNormal elapsed (~0.40 sec) (shared between items) + requires mouse to be stationary for style.HoverStationaryDelay (once per item). + NoSharedDelay = bitLShift(1, 17) -- IsItemHovered() only: Disable shared delay system where moving from one item to the next keeps the previous timer for a short time (standard for tooltips with long delays) } +-- Flags for ImGui.IsWindowFocused() --- @enum ImGuiFocusedFlags ImGuiFocusedFlags = { None = 0, ChildWindows = bitLShift(1, 0), -- Return true if any children of the window is focused RootWindow = bitLShift(1, 1), -- Test from root window (top most parent of the current hierarchy) - AnyWindow = bitLShift(1, 2), -- Return true if any window is focused - NoPopupHierarchy = bitLShift(1, 3), -- Do not consider popup hierarchy - DockHierarchy = bitLShift(1, 4), -- Consider docking hierarchy + AnyWindow = bitLShift(1, 2), -- Return true if any window is focused. Important: If you are trying to tell how to dispatch your low-level inputs, do NOT use this. Use 'io.WantCaptureMouse' instead! Please read the FAQ! + NoPopupHierarchy = bitLShift(1, 3), -- Do not consider popup hierarchy (do not treat popup emitter as parent of popup) (when used with _ChildWindows or _RootWindow) + DockHierarchy = bitLShift(1, 4), -- Consider docking hierarchy (treat dockspace host as parent of docked window) (when used with _ChildWindows or _RootWindow) } ImGuiFocusedFlags.RootAndChildWindows = bitOr(ImGuiFocusedFlags.RootWindow, ImGuiFocusedFlags.ChildWindows) @@ -1592,13 +1917,20 @@ ImGuiHoveredFlags.DelayMask_ = bitOr(ImGuiHoveredFlags.DelayNone, ImGuiHoveredFl ImGuiHoveredFlags.AllowedMaskForIsWindowHovered = bitOr(ImGuiHoveredFlags.ChildWindows, ImGuiHoveredFlags.RootWindow, ImGuiHoveredFlags.AnyWindow, ImGuiHoveredFlags.NoPopupHierarchy, ImGuiHoveredFlags.DockHierarchy, ImGuiHoveredFlags.AllowWhenBlockedByPopup, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.Stationary) ImGuiHoveredFlags.AllowedMaskForIsItemHovered = bitOr(ImGuiHoveredFlags.AllowWhenBlockedByPopup, ImGuiHoveredFlags.AllowWhenBlockedByActiveItem, ImGuiHoveredFlags.AllowWhenOverlapped, ImGuiHoveredFlags.AllowWhenDisabled, ImGuiHoveredFlags.NoNavOverride, ImGuiHoveredFlags.ForTooltip, ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayMask_) +-- 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 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 latter 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 ImGuiKey = { + -- Keyboard None = 0, - NamedKey_BEGIN = 512, + NamedKey_BEGIN = 512, -- First valid key value (other than 0) - Tab = 512, + Tab = 512, -- == ImGuiKey.NamedKey_BEGIN LeftArrow = 513, RightArrow = 514, UpArrow = 515, @@ -1635,10 +1967,14 @@ ImGuiKey = { Keypad0 = 612, Keypad1 = 613, Keypad2 = 614, Keypad3 = 615, Keypad4 = 616, Keypad5 = 617, Keypad6 = 618, Keypad7 = 619, Keypad8 = 620, Keypad9 = 621, KeypadDecimal = 622, KeypadDivide = 623, KeypadMultiply = 624, KeypadSubtract = 625, KeypadAdd = 626, KeypadEnter = 627, KeypadEqual = 628, - AppBack = 629, + AppBack = 629, -- Available on some keyboard/mouses. Often referred as "Browser Back" AppForward = 630, - Oem102 = 631, + Oem102 = 631, -- Non-US backslash. + -- Gamepad + -- (analog values are 0.0f to 1.0f) + -- (download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets) + -- XBOX | SWITCH | PLAYSTA. | -> ACTION GamepadStart = 632, GamepadBack = 633, GamepadFaceLeft = 634, GamepadFaceRight = 635, GamepadFaceUp = 636, GamepadFaceDown = 637, GamepadDpadLeft = 638, GamepadDpadRight = 639, GamepadDpadUp = 640, GamepadDpadDown = 641, @@ -1652,121 +1988,138 @@ ImGuiKey = { ReservedForModCtrl = 663, ReservedForModShift = 664, ReservedForModAlt = 665, ReservedForModSuper = 666, + -- [Internal] If you need to iterate all keys (for e.g. an input mapper) you may use ImGuiKey.NamedKey_BEGIN..ImGuiKey.NamedKey_END. NamedKey_END = 667 } ImGuiKey.NamedKey_COUNT = ImGuiKey.NamedKey_END - ImGuiKey.NamedKey_BEGIN +-- Keyboard Modifiers (explicitly submitted by backend via AddKeyEvent() calls) +-- - 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. +-- In practice: it's complicated; mods are often provided from different sources. Keyboard layout, IME, sticky keys and +-- backends tend to interfere and break that equivalence. The safer decision is to relay that ambiguity down to the end-user... +-- - On macOS, we swap Cmd(Super) and Ctrl keys at the time of the io.AddKeyEvent() call. ImGuiMod_None = 0 -ImGuiMod_Ctrl = bitLShift(1, 12) -ImGuiMod_Shift = bitLShift(1, 13) -ImGuiMod_Alt = bitLShift(1, 14) -ImGuiMod_Super = bitLShift(1, 15) -ImGuiMod_Mask_ = 0xF000 +ImGuiMod_Ctrl = bitLShift(1, 12) -- Ctrl (non-macOS), Cmd (macOS) +ImGuiMod_Shift = bitLShift(1, 13) -- Shift +ImGuiMod_Alt = bitLShift(1, 14) -- Option/Menu +ImGuiMod_Super = bitLShift(1, 15) -- Windows/Super (non-macOS), Ctrl (macOS) +ImGuiMod_Mask_ = 0xF000 -- 4-bits +-- Enumeration for PushStyleColor() / PopStyleColor() --- @enum ImGuiCol ImGuiCol = { Text = 0, TextDisabled = 1, - WindowBg = 2, - ChildBg = 3, - PopupBg = 4, + WindowBg = 2, -- Background of normal windows + ChildBg = 3, -- Background of child windows + PopupBg = 4, -- Background of popups, menus, tooltips windows Border = 5, BorderShadow = 6, - FrameBg = 7, + FrameBg = 7, -- Background of checkbox, radio button, plot, slider, text input FrameBgHovered = 8, FrameBgActive = 9, - TitleBg = 10, - TitleBgActive = 11, - TitleBgCollapsed = 12, + TitleBg = 10, -- Title bar + TitleBgActive = 11, -- Title bar when focused + TitleBgCollapsed = 12, -- Title bar when collapsed MenuBarBg = 13, ScrollbarBg = 14, ScrollbarGrab = 15, ScrollbarGrabHovered = 16, ScrollbarGrabActive = 17, - CheckMark = 18, - CheckboxSelectedBg = 19, + CheckMark = 18, -- Checkbox tick and RadioButton circle + CheckboxSelectedBg = 19, -- Checkbox background when Selected, otherwise use FrameBg SliderGrab = 20, SliderGrabActive = 21, Button = 22, ButtonHovered = 23, ButtonActive = 24, - Header = 25, + Header = 25, -- Header* colors are used for CollapsingHeader, TreeNode, Selectable, MenuItem HeaderHovered = 26, HeaderActive = 27, Separator = 28, SeparatorHovered = 29, SeparatorActive = 30, - ResizeGrip = 31, + ResizeGrip = 31, -- Resize grip in lower-right and lower-left corners of windows. ResizeGripHovered = 32, ResizeGripActive = 33, - InputTextCursor = 34, - TabHovered = 35, - Tab = 36, - TabSelected = 37, - TabSelectedOverline = 38, - TabDimmed = 39, - TabDimmedSelected = 40, - TabDimmedSelectedOverline = 41, - DockingPreview = 42, - DockingEmptyBg = 43, + InputTextCursor = 34, -- InputText cursor/caret + TabHovered = 35, -- Tab background, when hovered + Tab = 36, -- Tab background, when tab-bar is focused & tab is unselected + TabSelected = 37, -- Tab background, when tab-bar is focused & tab is selected + TabSelectedOverline = 38, -- Tab horizontal overline, when tab-bar is focused & tab is selected + TabDimmed = 39, -- Tab background, when tab-bar is unfocused & tab is unselected + TabDimmedSelected = 40, -- Tab background, when tab-bar is unfocused & tab is selected + TabDimmedSelectedOverline = 41, -- ..horizontal overline, when tab-bar is unfocused & tab is selected + DockingPreview = 42, -- Preview overlay color when about to docking something + DockingEmptyBg = 43, -- Background color for empty node (e.g. CentralNode with no window docked into it) PlotLines = 44, PlotLinesHovered = 45, PlotHistogram = 46, PlotHistogramHovered = 47, - TableHeaderBg = 48, - TableBorderStrong = 49, - TableBorderLight = 50, - TableRowBg = 51, - TableRowBgAlt = 52, - TextLink = 53, - TextSelectedBg = 54, - TreeLines = 55, - DragDropTarget = 56, - DragDropTargetBg = 57, - UnsavedMarker = 58, - NavCursor = 59, - NavWindowingHighlight = 60, - NavWindowingDimBg = 61, - ModalWindowDimBg = 62, + TableHeaderBg = 48, -- Table header background + TableBorderStrong = 49, -- Table outer and header borders (prefer using Alpha=1.0 here) + TableBorderLight = 50, -- Table inner borders (prefer using Alpha=1.0 here) + TableRowBg = 51, -- Table row background (even rows) + TableRowBgAlt = 52, -- Table row background (odd rows) + TextLink = 53, -- Hyperlink color + TextSelectedBg = 54, -- Selected text inside an InputText + TreeLines = 55, -- Tree node hierarchy outlines when using ImGuiTreeNodeFlags.DrawLines + DragDropTarget = 56, -- Rectangle border highlighting a drop target + DragDropTargetBg = 57, -- Rectangle background highlighting a drop target + UnsavedMarker = 58, -- Unsaved Document marker (in window title and tabs) + NavCursor = 59, -- Color of keyboard/gamepad navigation cursor/rectangle, when visible + NavWindowingHighlight = 60, -- Highlight window when using Ctrl+Tab + NavWindowingDimBg = 61, -- Darken/colorize entire screen behind the Ctrl+Tab window list, when active + ModalWindowDimBg = 62, -- Darken/colorize entire screen behind a modal window, when one is active COUNT = 63 } +-- Backend capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom backend. --- @enum ImGuiBackendFlags ImGuiBackendFlags = { None = 0, - HasGamepad = bitLShift(1, 0), - HasMouseCursors = bitLShift(1, 1), - HasSetMousePos = bitLShift(1, 2), - RendererHasVtxOffset = bitLShift(1, 3), - RendererHasTextures = bitLShift(1, 4), + HasGamepad = bitLShift(1, 0), -- Backend Platform supports gamepad and currently has one connected. + HasMouseCursors = bitLShift(1, 1), -- Backend Platform supports honoring GetMouseCursor() value to change the OS cursor shape. + HasSetMousePos = bitLShift(1, 2), -- Backend Platform supports io.WantSetMousePos requests to reposition the OS mouse position (only used if io.ConfigNavMoveSetMousePos is set). + RendererHasVtxOffset = bitLShift(1, 3), -- Backend Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bit indices. + RendererHasTextures = bitLShift(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] Multi-Viewports - RendererHasViewports = bitLShift(1, 10), - PlatformHasViewports = bitLShift(1, 11), - HasMouseHoveredViewport = bitLShift(1, 12), - HasParentViewport = bitLShift(1, 13) + RendererHasViewports = bitLShift(1, 10), -- Backend Renderer supports multiple viewports. + PlatformHasViewports = bitLShift(1, 11), -- Backend Platform supports multiple viewports. + HasMouseHoveredViewport = bitLShift(1, 12), -- Backend Platform supports calling io.AddMouseViewportEvent() with the viewport under the mouse. IF POSSIBLE, ignore viewports with the ImGuiViewportFlags.NoInputs flag (Win32 backend, GLFW 3.30+ backend can do this, SDL backend cannot). If this cannot be done, Dear ImGui needs to use a flawed heuristic to find the viewport under. + HasParentViewport = bitLShift(1, 13) -- Backend Platform supports honoring viewport->ParentViewport/ParentViewportId value, by applying the corresponding parent/child relationship at the Platform level. Child windows always appear in front of their parent window. } +-- Flags for ImGui.BeginDragDropSource(), ImGui.AcceptDragDropPayload() --- @enum ImGuiDragDropFlags ImGuiDragDropFlags = { None = 0, - SourceNoPreviewTooltip = bitLShift(1, 0), - SourceNoDisableHover = bitLShift(1, 1), - SourceNoHoldToOpenOthers = bitLShift(1, 2), - SourceAllowNullID = bitLShift(1, 3), - SourceExtern = bitLShift(1, 4), - PayloadAutoExpire = bitLShift(1, 5), - PayloadNoCrossContext = bitLShift(1, 6), - PayloadNoCrossProcess = bitLShift(1, 7), - AcceptBeforeDelivery = bitLShift(1, 10), - AcceptNoDrawDefaultRect = bitLShift(1, 11), - AcceptNoPreviewTooltip = bitLShift(1, 12), - AcceptDrawAsHovered = bitLShift(1, 13) + -- BeginDragDropSource() flags + SourceNoPreviewTooltip = bitLShift(1, 0), -- Disable preview tooltip. By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disables this behavior. + SourceNoDisableHover = bitLShift(1, 1), -- By default, when dragging we clear data so that IsItemHovered() will return false, to avoid subsequent user code submitting tooltips. This flag disables this behavior so you can still call IsItemHovered() on the source item. + SourceNoHoldToOpenOthers = bitLShift(1, 2), -- Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item. + SourceAllowNullID = bitLShift(1, 3), -- Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit. + SourceExtern = bitLShift(1, 4), -- External source (from outside of dear imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously. + PayloadAutoExpire = bitLShift(1, 5), -- Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged) + PayloadNoCrossContext = bitLShift(1, 6), -- Hint to specify that the payload may not be copied outside current dear imgui context. + PayloadNoCrossProcess = bitLShift(1, 7), -- Hint to specify that the payload may not be copied outside current process. + -- AcceptDragDropPayload() flags + AcceptBeforeDelivery = bitLShift(1, 10), -- AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered. + AcceptNoDrawDefaultRect = bitLShift(1, 11), -- Do not draw the default highlight rectangle when hovering over target. + AcceptNoPreviewTooltip = bitLShift(1, 12), -- Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site. + AcceptDrawAsHovered = bitLShift(1, 13) -- Accepting item will render as if hovered. Useful for e.g. a Button() used as a drop target. } -ImGuiDragDropFlags.AcceptPeekOnly = bitOr(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoDrawDefaultRect) +ImGuiDragDropFlags.AcceptPeekOnly = bitOr(ImGuiDragDropFlags.AcceptBeforeDelivery, ImGuiDragDropFlags.AcceptNoDrawDefaultRect) -- For peeking ahead and inspecting the payload before delivery. +-- Helpers macros to generate 32-bit encoded colors IM_COL32_R_SHIFT = 0 IM_COL32_G_SHIFT = 8 IM_COL32_B_SHIFT = 16 @@ -1782,121 +2135,145 @@ IM_COL32_WHITE = IM_COL32(255, 255, 255, 255) IM_COL32_BLACK = IM_COL32(0, 0, 0, 255) IM_COL32_BLACK_TRANS = IM_COL32(0, 0, 0, 0) +-- Flags for OpenPopup*(), BeginPopupContext*(), IsPopupOpen() functions. +-- - IMPORTANT: If you ever used the left mouse button with BeginPopupContextXXX() helpers before 1.92.6: Read "API BREAKING CHANGES" 2026/01/07 (1.92.6) entry in imgui.cpp or GitHub topic #9157. +-- - Multiple buttons currently cannot be combined/or-ed in those functions (we could allow it later). --- @enum ImGuiPopupFlags ImGuiPopupFlags = { None = 0, - MouseButtonLeft = bitLShift(1, 2), - MouseButtonRight = bitLShift(2, 2), - MouseButtonMiddle = bitLShift(3, 2), - NoReopen = bitLShift(1, 5), - NoOpenOverExistingPopup = bitLShift(1, 7), - NoOpenOverItems = bitLShift(1, 8), - AnyPopupId = bitLShift(1, 10), - AnyPopupLevel = bitLShift(1, 11) + MouseButtonLeft = bitLShift(1, 2), -- For BeginPopupContext*(): open on Left Mouse release. Only one button allowed! + MouseButtonRight = bitLShift(2, 2), -- For BeginPopupContext*(): open on Right Mouse release. Only one button allowed! (default) + MouseButtonMiddle = bitLShift(3, 2), -- For BeginPopupContext*(): open on Middle Mouse release. Only one button allowed! + NoReopen = bitLShift(1, 5), -- For OpenPopup*(), BeginPopupContext*(): don't reopen same popup if already open (won't reposition, won't reinitialize navigation) + --ImGuiPopupFlags.NoReopenAlwaysNavInit = 1 << 6, -- For OpenPopup*(), BeginPopupContext*(): focus and initialize navigation even when not reopening. + NoOpenOverExistingPopup = bitLShift(1, 7), -- For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack + NoOpenOverItems = bitLShift(1, 8), -- For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space + AnyPopupId = bitLShift(1, 10), -- For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup. + AnyPopupLevel = bitLShift(1, 11) -- For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level) } ImGuiPopupFlags.AnyPopup = bitOr(ImGuiPopupFlags.AnyPopupId, ImGuiPopupFlags.AnyPopupLevel) -ImGuiPopupFlags.MouseButtonShift_ = 2 -ImGuiPopupFlags.MouseButtonMask_ = 0x0C -ImGuiPopupFlags.InvalidMask_ = 0x03 +ImGuiPopupFlags.MouseButtonShift_ = 2 -- [Internal] +ImGuiPopupFlags.MouseButtonMask_ = 0x0C -- [Internal] +ImGuiPopupFlags.InvalidMask_ = 0x03 -- [Internal] Reserve legacy bits 0-1 to detect incorrectly passing 1 or 2 to the function. +-- Flags for ImGui.BeginCombo() --- @enum ImGuiComboFlags ImGuiComboFlags = { None = 0, - PopupAlignLeft = bitLShift(1, 0), - HeightSmall = bitLShift(1, 1), - HeightRegular = bitLShift(1, 2), - HeightLarge = bitLShift(1, 3), - HeightLargest = bitLShift(1, 4), - NoArrowButton = bitLShift(1, 5), - NoPreview = bitLShift(1, 6), - WidthFitPreview = bitLShift(1, 7) + PopupAlignLeft = bitLShift(1, 0), -- Align the popup toward the left by default + HeightSmall = bitLShift(1, 1), -- Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo() + HeightRegular = bitLShift(1, 2), -- Max ~8 items visible (default) + HeightLarge = bitLShift(1, 3), -- Max ~20 items visible + HeightLargest = bitLShift(1, 4), -- As many fitting items as possible + NoArrowButton = bitLShift(1, 5), -- Display on the preview box without the square arrow button + NoPreview = bitLShift(1, 6), -- Display only a square arrow button + WidthFitPreview = bitLShift(1, 7) -- Width dynamically calculated from preview contents } ImGuiComboFlags.HeightMask_ = bitOr(ImGuiComboFlags.HeightSmall, ImGuiComboFlags.HeightRegular, ImGuiComboFlags.HeightLarge, ImGuiComboFlags.HeightLargest) ImGuiComboFlags.CustomPreview = bitLShift(1, 20) +-- Flags for ImGui.Selectable() --- @enum ImGuiSelectableFlags ImGuiSelectableFlags = { None = 0, - NoAutoClosePopups = bitLShift(1, 0), - SpanAllColumns = bitLShift(1, 1), - AllowDoubleClick = bitLShift(1, 2), - Disabled = bitLShift(1, 3), - AllowOverlap = bitLShift(1, 4), - Highlight = bitLShift(1, 5), - SelectOnNav = bitLShift(1, 6), + NoAutoClosePopups = bitLShift(1, 0), -- Clicking this doesn't close parent popup window (overrides ImGuiItemFlags.AutoClosePopups) + SpanAllColumns = bitLShift(1, 1), -- Frame will span all columns of its container table (text will still fit in current column) + AllowDoubleClick = bitLShift(1, 2), -- Generate press events on double clicks too + Disabled = bitLShift(1, 3), -- Cannot be selected, display grayed out text + AllowOverlap = bitLShift(1, 4), -- Hit testing will allow subsequent widgets to overlap this one. Require previous frame HoveredId to match before being usable. Shortcut to calling SetNextItemAllowOverlap(). + Highlight = bitLShift(1, 5), -- Make the item be displayed as if it is hovered + SelectOnNav = bitLShift(1, 6), -- Auto-select when moved into, unless Ctrl is held. Automatic when in a BeginMultiSelect() block. + -- NB: need to be in sync with last value of ImGuiSelectableFlags_ NoHoldingActiveID = bitLShift(1, 20), - SelectOnClick = bitLShift(1, 22), - SelectOnRelease = bitLShift(1, 23), - SpanAvailWidth = bitLShift(1, 24), - SetNavIdOnHover = bitLShift(1, 25), - NoPadWithHalfSpacing = bitLShift(1, 26), - NoSetKeyOwner = bitLShift(1, 27), + SelectOnClick = bitLShift(1, 22), -- Override button behavior to react on Click (default is Click+Release) + SelectOnRelease = bitLShift(1, 23), -- Override button behavior to react on Release (default is Click+Release) + SpanAvailWidth = bitLShift(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) + SetNavIdOnHover = bitLShift(1, 25), -- Set Nav/Focus ID on mouse hover (used by MenuItem) + NoPadWithHalfSpacing = bitLShift(1, 26), -- Disable padding each side with ItemSpacing * 0.5f + NoSetKeyOwner = bitLShift(1, 27), -- Don't set key/input owner on the initial click (note: mouse buttons are keys! often, the key in question will be ImGuiKey.MouseLeft!) } +-- Flags for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton() --- @enum ImGuiColorEditFlags ImGuiColorEditFlags = { None = 0, - NoAlpha = bitLShift(1, 1), - NoPicker = bitLShift(1, 2), - NoOptions = bitLShift(1, 3), - NoSmallPreview = bitLShift(1, 4), - NoInputs = bitLShift(1, 5), - NoTooltip = bitLShift(1, 6), - NoLabel = bitLShift(1, 7), - NoSidePreview = bitLShift(1, 8), - NoDragDrop = bitLShift(1, 9), - NoBorder = bitLShift(1, 10), - NoColorMarkers = bitLShift(1, 11), + NoAlpha = bitLShift(1, 1), -- ColorEdit, ColorPicker, ColorButton: ignore Alpha component (will only read 3 components from the input pointer). + NoPicker = bitLShift(1, 2), -- ColorEdit: disable picker when clicking on color square. + NoOptions = bitLShift(1, 3), -- ColorEdit: disable toggling options menu when right-clicking on inputs/small preview. + NoSmallPreview = bitLShift(1, 4), -- ColorEdit, ColorPicker: disable color square preview next to the inputs. (e.g. to show only the inputs) + NoInputs = bitLShift(1, 5), -- ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview color square). + NoTooltip = bitLShift(1, 6), -- ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview. + NoLabel = bitLShift(1, 7), -- ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker). + NoSidePreview = bitLShift(1, 8), -- ColorPicker: disable bigger color preview on right side of the picker, use small color square preview instead. + NoDragDrop = bitLShift(1, 9), -- ColorEdit: disable drag and drop target/source. ColorButton: disable drag and drop source. + NoBorder = bitLShift(1, 10), -- ColorButton: disable border (which is enforced by default) + NoColorMarkers = bitLShift(1, 11), -- ColorEdit: disable rendering R/G/B/A color marker. May also be disabled globally by setting style.ColorMarkerSize = 0. -- Alpha preview - AlphaOpaque = bitLShift(1, 12), - AlphaNoBg = bitLShift(1, 13), - AlphaPreviewHalf = bitLShift(1, 14), + AlphaOpaque = bitLShift(1, 12), -- 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. + AlphaNoBg = bitLShift(1, 13), -- ColorEdit, ColorPicker, ColorButton: disable rendering a checkerboard background behind transparent color. + AlphaPreviewHalf = bitLShift(1, 14), -- ColorEdit, ColorPicker, ColorButton: display half opaque / half transparent preview. -- User Options (right-click on widget to change some of them) - AlphaBar = bitLShift(1, 18), - HDR = bitLShift(1, 19), - DisplayRGB = bitLShift(1, 20), - DisplayHSV = bitLShift(1, 21), - DisplayHex = bitLShift(1, 22), - Uint8 = bitLShift(1, 23), - Float = bitLShift(1, 24), - PickerHueBar = bitLShift(1, 25), - PickerHueWheel = bitLShift(1, 26), - PickerNoRotate = bitLShift(1, 27), - InputRGB = bitLShift(1, 28), - InputHSV = bitLShift(1, 29) + AlphaBar = bitLShift(1, 18), -- ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker. + HDR = bitLShift(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). + DisplayRGB = bitLShift(1, 20), -- [Display] -- ColorEdit: override _display_ type among RGB/HSV/Hex. ColorPicker: select any combination using one or more of RGB/HSV/Hex. + DisplayHSV = bitLShift(1, 21), -- [Display] -- " + DisplayHex = bitLShift(1, 22), -- [Display] -- " + Uint8 = bitLShift(1, 23), -- [DataType] -- ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255. + Float = bitLShift(1, 24), -- [DataType] -- ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers. + PickerHueBar = bitLShift(1, 25), -- [Picker] -- ColorPicker: bar for Hue, rectangle for Sat/Value. + PickerHueWheel = bitLShift(1, 26), -- [Picker] -- ColorPicker: wheel for Hue, triangle for Sat/Value. + PickerNoRotate = bitLShift(1, 27), -- [Picker] -- ColorPicker: disable rotating Sat/Value triangle. Best set in io.ConfigColorEditFlags once. + InputRGB = bitLShift(1, 28), -- [Input] -- ColorEdit, ColorPicker: input and output data in RGB format. + InputHSV = bitLShift(1, 29) -- [Input] -- ColorEdit, ColorPicker: input and output data in HSV format. } +-- Defaults Options copied to io.ConfigColorEditFlags during initialization. +-- The intent is that you probably don't want to override them in most of your calls. +-- Let the user choose via the option menu and/or modify io.ConfigColorEditFlags directly during startup if you want. ImGuiColorEditFlags.DefaultOptions_ = bitOr(ImGuiColorEditFlags.Uint8, ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.InputRGB, ImGuiColorEditFlags.PickerHueBar) +-- [Internal] Masks ImGuiColorEditFlags.AlphaMask_ = bitOr( ImGuiColorEditFlags.NoAlpha, ImGuiColorEditFlags.AlphaOpaque, ImGuiColorEditFlags.AlphaNoBg, ImGuiColorEditFlags.AlphaPreviewHalf ) ImGuiColorEditFlags.DisplayMask_ = bitOr( ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.DisplayHSV, ImGuiColorEditFlags.DisplayHex ) ImGuiColorEditFlags.DataTypeMask_ = bitOr( ImGuiColorEditFlags.Uint8, ImGuiColorEditFlags.Float ) ImGuiColorEditFlags.PickerMask_ = bitOr( ImGuiColorEditFlags.PickerHueWheel, ImGuiColorEditFlags.PickerHueBar ) ImGuiColorEditFlags.InputMask_ = bitOr( ImGuiColorEditFlags.InputRGB, ImGuiColorEditFlags.InputHSV ) +-- Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc. +-- We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them. +-- (Those are per-item flags. There is shared behavior flag too: ImGuiIO: io.ConfigDragClickToInputText) --- @enum ImGuiSliderFlags ImGuiSliderFlags = { None = 0, - Logarithmic = bitLShift(1, 5), - NoRoundToFormat = bitLShift(1, 6), - NoInput = bitLShift(1, 7), - WrapAround = bitLShift(1, 8), - ClampOnInput = bitLShift(1, 9), - ClampZeroRange = bitLShift(1, 10), - NoSpeedTweaks = bitLShift(1, 11), - ColorMarkers = bitLShift(1, 12), - InvalidMask_ = 0x7000000F, + Logarithmic = bitLShift(1, 5), -- Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags.NoRoundToFormat with this if using a format-string with small amount of digits. + NoRoundToFormat = bitLShift(1, 6), -- Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits). + NoInput = bitLShift(1, 7), -- Disable Ctrl+Click or Enter key allowing to input text directly into the widget. + WrapAround = bitLShift(1, 8), -- Enable wrapping around from max to min and from min to max. Only supported by DragXXX() functions for now. + ClampOnInput = bitLShift(1, 9), -- Clamp value to min/max bounds when input manually with Ctrl+Click. By default Ctrl+Click allows going out of bounds. + ClampZeroRange = bitLShift(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. + NoSpeedTweaks = bitLShift(1, 11), -- Disable keyboard modifiers altering tweak speed. Useful if you want to alter tweak speed yourself based on your own logic. + ColorMarkers = bitLShift(1, 12), -- DragScalarN(), SliderScalarN(): Draw R/G/B/A color markers on each component. + --ImGuiSliderFlags.LiveEditOnInput = 1 << 13, -- Shortcut to enable LiveEdit for this field. + --ImGuiSliderFlags.NoLiveEditOnInput= 1 << 14, -- Shortcut to disable LiveEdit for this field. + InvalidMask_ = 0x7000000F, -- [Internal] We treat using those bits as being potentially a 'float power' argument from legacy API (obsoleted 2020-08) that has got miscast to this enum, and will trigger an assert if needed. } ImGuiSliderFlags.AlwaysClamp = bitOr(ImGuiSliderFlags.ClampOnInput, ImGuiSliderFlags.ClampZeroRange) -ImGuiSliderFlags.Vertical = bitLShift(1, 20) -ImGuiSliderFlags.ReadOnly = bitLShift(1, 21) +ImGuiSliderFlags.Vertical = bitLShift(1, 20) -- Should this slider be orientated vertically? +ImGuiSliderFlags.ReadOnly = bitLShift(1, 21) -- Consider using g.NextItemData.ItemFlags |= ImGuiItemFlags.ReadOnly instead. +-- [ALPHA] Rarely used / very advanced uses only. Use with SetNextWindowClass() and DockSpace() functions. +-- Important: the content of this class is still highly WIP and likely to change and be refactored +-- before we stabilize Docking features. Please be mindful if using this. +-- Provide hints: +-- - To the platform backend via altered viewport flags (enable/disable OS decoration, OS task bar icons, etc.) +-- - To the platform backend for OS level parent/child relationships of viewport (otherwise: default is configured via io.ConfigViewportsNoDefaultParent) +-- - To the docking system for various options and filtering. --- @class ImGuiWindowClass --- @field ClassId ImGuiID --- @field ParentViewportId ImGuiID @@ -1908,66 +2285,82 @@ ImGuiSliderFlags.ReadOnly = bitLShift(1, 21) --- @nodiscard function ImGuiWindowClass() return { - ClassId = 0, - ParentViewportId = 0xFFFFFFFF, - FocusRouteParentWindowId = 0, - ViewportFlagsOverrideSet = 0, - ViewportFlagsOverrideClear = 0, + ClassId = 0, -- User data. 0 = Default class (unclassed). Windows of different classes cannot be docked with each others. + ParentViewportId = 0xFFFFFFFF, -- Hint for the platform backend. -1: use default. 0: request platform backend to not parent the platform. != 0: request platform backend to create a parent<>child relationship between the platform windows. Not conforming backends are free to e.g. parent every viewport to the main viewport or not. + FocusRouteParentWindowId = 0, -- ID of parent window for shortcut focus route evaluation, e.g. Shortcut() call from Parent Window will succeed when this window is focused. + ViewportFlagsOverrideSet = 0, -- Viewport flags to set when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. + ViewportFlagsOverrideClear = 0, -- Viewport flags to clear when a window of this class owns a viewport. This allows you to enforce OS decoration or task bar icon, override the defaults on a per-window basis. - TabItemFlagsOverrideSet = 0, - DockNodeFlagsOverrideSet = 0, - DockingAlwaysTabBar = false, - DockingAllowUnclassed = true + TabItemFlagsOverrideSet = 0, -- [EXPERIMENTAL] TabItem flags to set when a window of this class gets submitted into a dock node tab bar. May use with ImGuiTabItemFlags.Leading or ImGuiTabItemFlags.Trailing. + DockNodeFlagsOverrideSet = 0, -- [EXPERIMENTAL] Dock node flags to set when a window of this class is hosted by a dock node (it doesn't have to be selected!) + DockingAlwaysTabBar = false, -- Set to true to enforce single floating windows of this class always having their own docking node (equivalent of setting the global io.ConfigDockingAlwaysTabBar) + DockingAllowUnclassed = true -- Set to true to allow windows of this class to be docked/merged with an unclassed window. -- FIXME-DOCK: Move to DockNodeFlags override? } end +-- Flags for ImGui.InputText() +-- (Those are per-item flags. There are shared flags in ImGuiIO: io.ConfigInputTextCursorBlink and io.ConfigInputTextEnterKeepActive) --- @enum ImGuiInputTextFlags ImGuiInputTextFlags = { + -- Basic filters (also see ImGuiInputTextFlags.CallbackCharFilter) None = 0, -- Basic filters (also see ImGuiInputTextFlags.CallbackCharFilter) - CharsDecimal = bitLShift(1, 0), - CharsHexadecimal = bitLShift(1, 1), - CharsScientific = bitLShift(1, 2), - CharsUppercase = bitLShift(1, 3), - CharsNoBlank = bitLShift(1, 4), + CharsDecimal = bitLShift(1, 0), -- Allow 0123456789.+-*/ + CharsHexadecimal = bitLShift(1, 1), -- Allow 0123456789ABCDEFabcdef + CharsScientific = bitLShift(1, 2), -- Allow 0123456789.+-*/eE (Scientific notation input) + CharsUppercase = bitLShift(1, 3), -- Turn a..z into A..Z + CharsNoBlank = bitLShift(1, 4), -- Filter out spaces, tabs -- Inputs - AllowTabInput = bitLShift(1, 5), - EnterReturnsTrue = bitLShift(1, 6), - EscapeClearsAll = bitLShift(1, 7), - CtrlEnterForNewLine = bitLShift(1, 8), + AllowTabInput = bitLShift(1, 5), -- Pressing TAB input a '\t' character into the text field + EnterReturnsTrue = bitLShift(1, 6), -- Return 'true' when Enter is pressed (as opposed to every time the value was modified). Consider disabling LiveEdit! or using IsItemDeactivatedAfterEdit() instead! + EscapeClearsAll = bitLShift(1, 7), -- Escape key clears content if not empty, and deactivate otherwise (contrast to default behavior of Escape to revert) + CtrlEnterForNewLine = bitLShift(1, 8), -- In multi-line mode: validate with Enter, add new line with Ctrl+Enter (default is opposite: validate with Ctrl+Enter, add line with Enter). Note that Shift+Enter always enter a new line either way. -- Other options - ReadOnly = bitLShift(1, 9), - Password = bitLShift(1, 10), - AlwaysOverwrite = bitLShift(1, 11), - AutoSelectAll = bitLShift(1, 12), - ParseEmptyRefVal = bitLShift(1, 13), - DisplayEmptyRefVal = bitLShift(1, 14), - NoHorizontalScroll = bitLShift(1, 15), - NoUndoRedo = bitLShift(1, 16), + ReadOnly = bitLShift(1, 9), -- Read-only mode + Password = bitLShift(1, 10), -- Password mode, display all characters as '*', disable copy + AlwaysOverwrite = bitLShift(1, 11), -- Overwrite mode + AutoSelectAll = bitLShift(1, 12), -- Select entire text when first taking mouse focus + ParseEmptyRefVal = bitLShift(1, 13), -- InputFloat(), InputInt(), InputScalar() etc. only: parse empty string as zero value. + DisplayEmptyRefVal = bitLShift(1, 14), -- InputFloat(), InputInt(), InputScalar() etc. only: when value is zero, do not display it. Generally used with ImGuiInputTextFlags.ParseEmptyRefVal. + NoHorizontalScroll = bitLShift(1, 15), -- Disable following the cursor horizontally + NoUndoRedo = bitLShift(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 - ElideLeft = bitLShift(1, 17), + ElideLeft = bitLShift(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 - CallbackCompletion = bitLShift(1, 18), - CallbackHistory = bitLShift(1, 19), - CallbackAlways = bitLShift(1, 20), - CallbackCharFilter = bitLShift(1, 21), - CallbackResize = bitLShift(1, 22), - CallbackEdit = bitLShift(1, 23), + CallbackCompletion = bitLShift(1, 18), -- Callback on pressing TAB (for completion handling) + CallbackHistory = bitLShift(1, 19), -- Callback on pressing Up/Down arrows (for history handling) + CallbackAlways = bitLShift(1, 20), -- Callback on each iteration. User code may query cursor position, modify text buffer. + CallbackCharFilter = bitLShift(1, 21), -- Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. + CallbackResize = bitLShift(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) + CallbackEdit = bitLShift(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] - WordWrap = bitLShift(1, 24), + WordWrap = bitLShift(1, 24), -- InputTextMultiline(): word-wrap lines that are too long. -- [Internal] - Multiline = bitLShift(1, 26), - TempInput = bitLShift(1, 27), - LocalizeDecimalPoint = bitLShift(1, 28), + Multiline = bitLShift(1, 26), -- For internal use by InputTextMultiline() + TempInput = bitLShift(1, 27), -- For internal use by TempInputText(), will skip calling ItemAdd(). Require bounding-box to strictly match. + LocalizeDecimalPoint = bitLShift(1, 28), -- For internal use by InputScalar() and TempInputScalar() } +------------------------------------------------------------------------------- +-- [SECTION] Misc data structures (ImGuiInputTextCallbackData, ImGuiSizeCallbackData, ImGuiPayload) +------------------------------------------------------------------------------- + +-- 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 + 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 +-- - ImGuiInputTextFlags.CallbackCharFilter: Callback on character inputs to replace or discard them. Modify 'EventChar' to replace or discard, or return 1 in callback to discard. +-- - ImGuiInputTextFlags.CallbackResize: Callback on buffer capacity changes request (beyond 'buf_size' parameter value), allowing the string to grow. --- @class ImGuiInputTextCallbackData --- @return ImGuiInputTextCallbackData @@ -2028,40 +2421,51 @@ function MT.ImGuiInputTextCallbackData:SelectAll() self.SelectionStart = 0; self function MT.ImGuiInputTextCallbackData:ClearSelection() self.SelectionStart = self.BufTextLen; self.SelectionEnd = self.BufTextLen end function MT.ImGuiInputTextCallbackData:HasSelection() return self.SelectionStart ~= self.SelectionEnd end +-- Callback and functions types --- @alias ImGuiInputTextCallback fun(data: ImGuiInputTextCallbackData) --- @alias ImGuiMemAllocFunc fun(T: function, start_idx: int, end_idx: int, userdata: any): table --- @alias ImGuiMemFreeFunc fun(owner: table, field: string, userdata: any) +-- ImDrawCallback: Draw callbacks for advanced uses [configurable type: override in imconfig.h] +-- NB: You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering, +-- you can poke into the draw list for that! Draw callback may be useful for example to: +-- A) Change your GPU render state, +-- B) render a complex 3D scene inside a UI element without an intermediate texture/render target, etc. +-- The expected behavior from your rendering function is 'if (cmd.UserCallback != nil) { cmd.UserCallback(parent_list, cmd); } else { RenderTriangles() }' --- @alias ImDrawCallback fun(parent_list: ImDrawList, cmd: ImDrawCmd) +-- Flags for ImGui.TreeNodeEx(), ImGui.CollapsingHeader*() --- @enum ImGuiTreeNodeFlags ImGuiTreeNodeFlags = { None = 0, - Selected = bitLShift(1, 0), - Framed = bitLShift(1, 1), - AllowOverlap = bitLShift(1, 2), - NoTreePushOnOpen = bitLShift(1, 3), - NoAutoOpenOnLog = bitLShift(1, 4), - DefaultOpen = bitLShift(1, 5), - OpenOnDoubleClick = bitLShift(1, 6), - OpenOnArrow = bitLShift(1, 7), - Leaf = bitLShift(1, 8), - Bullet = bitLShift(1, 9), - FramePadding = bitLShift(1, 10), - SpanAvailWidth = bitLShift(1, 11), - SpanFullWidth = bitLShift(1, 12), - SpanLabelWidth = bitLShift(1, 13), - SpanAllColumns = bitLShift(1, 14), - LabelSpanAllColumns = bitLShift(1, 15), - NavLeftJumpsToParent = bitLShift(1, 17), - DrawLinesNone = bitLShift(1, 18), - DrawLinesFull = bitLShift(1, 19), - DrawLinesToNodes = bitLShift(1, 20), + Selected = bitLShift(1, 0), -- Draw as selected + Framed = bitLShift(1, 1), -- Draw frame with background (e.g. for CollapsingHeader) + AllowOverlap = bitLShift(1, 2), -- Hit testing will allow subsequent widgets to overlap this one. Require previous frame HoveredId to match before being usable. Shortcut to calling SetNextItemAllowOverlap(). + NoTreePushOnOpen = bitLShift(1, 3), -- Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + NoAutoOpenOnLog = bitLShift(1, 4), -- Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + DefaultOpen = bitLShift(1, 5), -- Default node to be open + OpenOnDoubleClick = bitLShift(1, 6), -- Open on double-click instead of simple click (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. + OpenOnArrow = bitLShift(1, 7), -- Open when clicking on the arrow part (default for multi-select unless any _OpenOnXXX behavior is set explicitly). Both behaviors may be combined. + Leaf = bitLShift(1, 8), -- No collapsing, no arrow (use as a convenience for leaf nodes). Note: will always open a tree/id scope and return true. If you never use that scope, add ImGuiTreeNodeFlags.NoTreePushOnOpen. + Bullet = bitLShift(1, 9), -- Display a bullet instead of arrow. IMPORTANT: node can still be marked open/close if you don't set the _Leaf flag! + FramePadding = bitLShift(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. + SpanAvailWidth = bitLShift(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. + SpanFullWidth = bitLShift(1, 12), -- Extend hit box to the left-most and right-most edges (cover the indent area). + SpanLabelWidth = bitLShift(1, 13), -- Narrow hit box + narrow hovering highlight, will only cover the label text. + SpanAllColumns = bitLShift(1, 14), -- Frame will span all columns of its container table (label will still fit in current column) + LabelSpanAllColumns = bitLShift(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 + NavLeftJumpsToParent = bitLShift(1, 17), -- Nav: left arrow moves back to parent. This is processed in TreePop() when there's an unfulfilled Left nav request remaining. + -- [EXPERIMENTAL] Draw lines connecting TreeNode hierarchy. Discuss in GitHub issue #2920. + -- Default value is pulled from style.TreeLinesFlags. May be overridden in TreeNode calls. + DrawLinesNone = bitLShift(1, 18), -- No lines drawn + DrawLinesFull = bitLShift(1, 19), -- Horizontal lines to child nodes. Vertical line drawn down to TreePop() position: cover full contents. Faster (for large trees). + DrawLinesToNodes = bitLShift(1, 20), -- Horizontal lines to child nodes. Vertical line drawn down to bottom-most child node. Slower (for large trees). - NoNavFocus = bitLShift(1, 27), - ClipLabelForTrailingButton = bitLShift(1, 28), - UpsideDownArrow = bitLShift(1, 29), + NoNavFocus = bitLShift(1, 27), -- Don't claim nav focus when interacting with this item (#8551) + ClipLabelForTrailingButton = bitLShift(1, 28), -- FIXME-WIP: Hard-coded for CollapsingHeader() + UpsideDownArrow = bitLShift(1, 29), -- FIXME-WIP: Turn Down arrow into an Up arrow, for reversed trees (#6517) } ImGuiTreeNodeFlags.CollapsingHeader = bitOr(ImGuiTreeNodeFlags.Framed, ImGuiTreeNodeFlags.NoTreePushOnOpen, ImGuiTreeNodeFlags.NoAutoOpenOnLog) @@ -2069,94 +2473,152 @@ ImGuiTreeNodeFlags.CollapsingHeader = bitOr(ImGuiTreeNodeFlags.Framed, ImGuiTree ImGuiTreeNodeFlags.OpenOnMask_ = bitOr(ImGuiTreeNodeFlags.OpenOnDoubleClick, ImGuiTreeNodeFlags.OpenOnArrow) ImGuiTreeNodeFlags.DrawLinesMask_ = bitOr(ImGuiTreeNodeFlags.DrawLinesNone, ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DrawLinesToNodes) +------------------------------------------------------------------------------- +-- [SECTION] Tables API flags and structures (ImGuiTableFlags, ImGuiTableColumnFlags, ImGuiTableRowFlags, ImGuiTableBgTarget, ImGuiTableSortSpecs, ImGuiTableColumnSortSpecs) +------------------------------------------------------------------------------- + +-- Flags for ImGui.BeginTable() +-- - Important! Sizing policies have complex and subtle side effects, much more so than you would expect. +-- Read comments/demos carefully + experiment with live demos to get acquainted with them. +-- - The DEFAULT sizing policies are: +-- - Default to ImGuiTableFlags.SizingFixedFit if ScrollX is on, or if host window has ImGuiWindowFlags.AlwaysAutoResize. +-- - Default to ImGuiTableFlags.SizingStretchSame if ScrollX is off. +-- - When ScrollX is off: +-- - Table defaults to ImGuiTableFlags.SizingStretchSame -> all Columns defaults to ImGuiTableColumnFlags.WidthStretch with same weight. +-- - Columns sizing policy allowed: Stretch (default), Fixed/Auto. +-- - Fixed Columns (if any) will generally obtain their requested width (unless the table cannot fit them all). +-- - Stretch Columns will share the remaining width according to their respective weight. +-- - Mixed Fixed/Stretch columns is possible but has various side-effects on resizing behaviors. +-- The typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +-- (this is because the visible order of columns have subtle but necessary effects on how they react to manual resizing). +-- - When ScrollX is on: +-- - Table defaults to ImGuiTableFlags.SizingFixedFit -> all Columns defaults to ImGuiTableColumnFlags.WidthFixed +-- - Columns sizing policy allowed: Fixed/Auto mostly. +-- - Fixed Columns can be enlarged as needed. Table will show a horizontal scrollbar if needed. +-- - When using auto-resizing (non-resizable) fixed columns, querying the content width to use item right-alignment e.g. SetNextItemWidth(-FLT_MIN) doesn't make sense, would create a feedback loop. +-- - Using Stretch columns OFTEN DOES NOT MAKE SENSE if ScrollX is on, UNLESS you have specified a value for 'inner_width' in BeginTable(). +-- If you specify a value for 'inner_width' then effectively the scrolling space is known and Stretch or mixed Fixed/Stretch columns become meaningful again. +-- - Read on documentation at the top of imgui_tables.cpp for details. --- @enum ImGuiTableFlags ImGuiTableFlags = { + -- Features None = 0, - Resizable = bitLShift(1, 0), - Reorderable = bitLShift(1, 1), - Hideable = bitLShift(1, 2), - Sortable = bitLShift(1, 3), - NoSavedSettings = bitLShift(1, 4), - ContextMenuInBody = bitLShift(1, 5), - RowBg = bitLShift(1, 6), - BordersInnerH = bitLShift(1, 7), - BordersOuterH = bitLShift(1, 8), - BordersInnerV = bitLShift(1, 9), - BordersOuterV = bitLShift(1, 10), - NoBordersInBody = bitLShift(1, 11), - NoBordersInBodyUntilResize = bitLShift(1, 12), - SizingFixedFit = bitLShift(1, 13), - SizingFixedSame = bitLShift(2, 13), - SizingStretchProp = bitLShift(3, 13), - SizingStretchSame = bitLShift(4, 13), - NoHostExtendX = bitLShift(1, 16), - NoHostExtendY = bitLShift(1, 17), - NoKeepColumnsVisible = bitLShift(1, 18), - PreciseWidths = bitLShift(1, 19), - NoClip = bitLShift(1, 20), - PadOuterX = bitLShift(1, 21), - NoPadOuterX = bitLShift(1, 22), - NoPadInnerX = bitLShift(1, 23), - ScrollX = bitLShift(1, 24), - ScrollY = bitLShift(1, 25), - SortMulti = bitLShift(1, 26), - SortTristate = bitLShift(1, 27), - HighlightHoveredColumn = bitLShift(1, 28), + Resizable = bitLShift(1, 0), -- Enable resizing columns. + Reorderable = bitLShift(1, 1), -- Enable reordering columns in header row. (Need calling TableSetupColumn() + TableHeadersRow() to display headers, or using ImGuiTableFlags.ContextMenuInBody to access context-menu without headers). + Hideable = bitLShift(1, 2), -- Enable hiding/disabling columns in context menu. + Sortable = bitLShift(1, 3), -- Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags.SortMulti and ImGuiTableFlags.SortTristate. + NoSavedSettings = bitLShift(1, 4), -- Disable persisting columns order, width, visibility and sort settings in the .ini file. + ContextMenuInBody = bitLShift(1, 5), -- Right-click on columns body/contents will also display table context menu. By default it is available in TableHeadersRow(). + -- Decorations + RowBg = bitLShift(1, 6), -- Set each RowBg color with ImGuiCol.TableRowBg or ImGuiCol.TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags.RowBg0 on each row manually) + BordersInnerH = bitLShift(1, 7), -- Draw horizontal borders between rows. + BordersOuterH = bitLShift(1, 8), -- Draw horizontal borders at the top and bottom. + BordersInnerV = bitLShift(1, 9), -- Draw vertical borders between columns. + BordersOuterV = bitLShift(1, 10), -- Draw vertical borders on the left and right sides. + NoBordersInBody = bitLShift(1, 11), -- [ALPHA] Disable vertical borders in columns Body (borders will always appear in Headers). -> May move to style + NoBordersInBodyUntilResize = bitLShift(1, 12), -- [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appear in Headers). -> May move to style + -- Sizing Policy (read above for defaults) + SizingFixedFit = bitLShift(1, 13), -- Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width. + SizingFixedSame = bitLShift(2, 13), -- Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags.NoKeepColumnsVisible. + SizingStretchProp = bitLShift(3, 13), -- Columns default to _WidthStretch with default weights proportional to each columns contents widths. + SizingStretchSame = bitLShift(4, 13), -- Columns default to _WidthStretch with default weights all equal, unless overridden by TableSetupColumn(). + -- Sizing Extra Options + NoHostExtendX = bitLShift(1, 16), -- Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. + NoHostExtendY = bitLShift(1, 17), -- Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible. + NoKeepColumnsVisible = bitLShift(1, 18), -- Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable. + PreciseWidths = bitLShift(1, 19), -- Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth. + -- Clipping + NoClip = bitLShift(1, 20), -- Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze(). + -- Padding + PadOuterX = bitLShift(1, 21), -- Default if BordersOuterV is on. Enable outermost padding. Generally desirable if you have headers. + NoPadOuterX = bitLShift(1, 22), -- Default if BordersOuterV is off. Disable outermost padding. + NoPadInnerX = bitLShift(1, 23), -- Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off). + -- Scrolling + ScrollX = bitLShift(1, 24), -- Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this creates a child window, ScrollY is currently generally recommended when using ScrollX. + ScrollY = bitLShift(1, 25), -- Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. + -- Sorting + SortMulti = bitLShift(1, 26), -- Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1). + SortTristate = bitLShift(1, 27), -- Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0). + -- Miscellaneous + HighlightHoveredColumn = bitLShift(1, 28), -- Highlight column headers when hovered (may evolve into a fuller highlight) } -ImGuiTableFlags.BordersH = bitOr(ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.BordersOuterH) -ImGuiTableFlags.BordersV = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersOuterV) -ImGuiTableFlags.BordersInner = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersInnerH) -ImGuiTableFlags.BordersOuter = bitOr(ImGuiTableFlags.BordersOuterV, ImGuiTableFlags.BordersOuterH) -ImGuiTableFlags.Borders = bitOr(ImGuiTableFlags.BordersInner, ImGuiTableFlags.BordersOuter) +ImGuiTableFlags.BordersH = bitOr(ImGuiTableFlags.BordersInnerH, ImGuiTableFlags.BordersOuterH) -- Draw horizontal borders. +ImGuiTableFlags.BordersV = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersOuterV) -- Draw vertical borders. +ImGuiTableFlags.BordersInner = bitOr(ImGuiTableFlags.BordersInnerV, ImGuiTableFlags.BordersInnerH) -- Draw inner borders. +ImGuiTableFlags.BordersOuter = bitOr(ImGuiTableFlags.BordersOuterV, ImGuiTableFlags.BordersOuterH) -- Draw outer borders. +ImGuiTableFlags.Borders = bitOr(ImGuiTableFlags.BordersInner, ImGuiTableFlags.BordersOuter) -- Draw all borders. +-- [Internal] Combinations and masks ImGuiTableFlags.SizingMask_ = bitOr(ImGuiTableFlags.SizingFixedFit, ImGuiTableFlags.SizingFixedSame, ImGuiTableFlags.SizingStretchProp, ImGuiTableFlags.SizingStretchSame) +-- Flags for ImGui.TableSetupColumn() --- @enum ImGuiTableColumnFlags ImGuiTableColumnFlags = { + -- Input configuration flags None = 0, - Disabled = bitLShift(1, 0), - DefaultHide = bitLShift(1, 1), - DefaultSort = bitLShift(1, 2), - WidthStretch = bitLShift(1, 3), - WidthFixed = bitLShift(1, 4), - NoResize = bitLShift(1, 5), - NoReorder = bitLShift(1, 6), - NoHide = bitLShift(1, 7), - NoClip = bitLShift(1, 8), - NoSort = bitLShift(1, 9), - NoSortAscending = bitLShift(1, 10), - NoSortDescending = bitLShift(1, 11), - NoHeaderLabel = bitLShift(1, 12), - NoHeaderWidth = bitLShift(1, 13), - PreferSortAscending = bitLShift(1, 14), - PreferSortDescending = bitLShift(1, 15), - IndentEnable = bitLShift(1, 16), - IndentDisable = bitLShift(1, 17), - AngledHeader = bitLShift(1, 18), + Disabled = bitLShift(1, 0), -- Overriding/master disable flag: hide column, won't show in context menu (unlike calling TableSetColumnEnabled() which manipulates the user accessible state) + DefaultHide = bitLShift(1, 1), -- Default as a hidden/disabled column. + DefaultSort = bitLShift(1, 2), -- Default as a sorting column. + WidthStretch = bitLShift(1, 3), -- Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp). + WidthFixed = bitLShift(1, 4), -- Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable). + NoResize = bitLShift(1, 5), -- Disable manual resizing. + NoReorder = bitLShift(1, 6), -- Disable manual reordering this column, this will also prevent other columns from crossing over this column. + NoHide = bitLShift(1, 7), -- Disable ability to hide/disable this column. + NoClip = bitLShift(1, 8), -- Disable clipping for this column (all NoClip columns will render in a same draw command). + NoSort = bitLShift(1, 9), -- Disable ability to sort on this field (even if ImGuiTableFlags.Sortable is set on the table). + NoSortAscending = bitLShift(1, 10), -- Disable ability to sort in the ascending direction. + NoSortDescending = bitLShift(1, 11), -- Disable ability to sort in the descending direction. + NoHeaderLabel = bitLShift(1, 12), -- TableHeadersRow() will submit an empty label for this column. Convenient for some small columns. Name will still appear in context menu or in angled headers. You may append into this cell by calling TableSetColumnIndex() right after the TableHeadersRow() call. + NoHeaderWidth = bitLShift(1, 13), -- Disable header text width contribution to automatic column width. + PreferSortAscending = bitLShift(1, 14), -- Make the initial sort direction Ascending when first sorting on this column (default). + PreferSortDescending = bitLShift(1, 15), -- Make the initial sort direction Descending when first sorting on this column. + IndentEnable = bitLShift(1, 16), -- Use current Indent value when entering cell (default for column 0). + IndentDisable = bitLShift(1, 17), -- Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored. + AngledHeader = bitLShift(1, 18), -- TableHeadersRow() will submit an angled header row for this column. Note this will add an extra row. - IsEnabled = bitLShift(1, 24), - IsVisible = bitLShift(1, 25), - IsSorted = bitLShift(1, 26), - IsHovered = bitLShift(1, 27), + -- Output status flags, read-only via TableGetColumnFlags() + IsEnabled = bitLShift(1, 24), -- Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags. + IsVisible = bitLShift(1, 25), -- Status: is visible == is enabled AND not clipped by scrolling. + IsSorted = bitLShift(1, 26), -- Status: is currently part of the sort specs + IsHovered = bitLShift(1, 27), -- Status: is hovered by mouse - NoDirectResize_ = bitLShift(1, 30), + NoDirectResize_ = bitLShift(1, 30), -- [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) } +-- [Internal] Combinations and masks ImGuiTableColumnFlags.WidthMask_ = bitOr(ImGuiTableColumnFlags.WidthStretch, ImGuiTableColumnFlags.WidthFixed) ImGuiTableColumnFlags.IndentMask_ = bitOr(ImGuiTableColumnFlags.IndentEnable, ImGuiTableColumnFlags.IndentDisable) ImGuiTableColumnFlags.StatusMask_ = bitOr(ImGuiTableColumnFlags.IsEnabled, ImGuiTableColumnFlags.IsVisible, ImGuiTableColumnFlags.IsSorted, ImGuiTableColumnFlags.IsHovered) +-- Flags for ImGui.TableNextRow() +-- - Headers: Identify header row (set default background color + width of its contents accounted differently for auto column width) --- @enum ImGuiTableRowFlags ImGuiTableRowFlags = { None = 0, Headers = bitLShift(1, 0) } +-- Enum for ImGui.TableSetBgColor() +-- Background colors are rendering in 3 layers: +-- - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set. +-- - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set. +-- - Layer 2: draw with CellBg color if set. +-- The purpose of the two row/columns layers is to let you decide if a background color change should override or blend with the existing color. +-- When using ImGuiTableFlags.RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows. +-- If you set the color of RowBg0 target, your color will override the existing RowBg0 color. +-- If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color. +-- - RowBg0: Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags.RowBg is used) +-- - RowBg1: Set row background color 1 (generally used for selection marking) +-- - CellBg: Set cell background color (top-most color) --- @enum ImGuiTableBgTarget ImGuiTableBgTarget = { None = 0, RowBg0 = 1, RowBg1 = 2, CellBg = 3 } +-- A sorting direction +-- - Ascending = 0->9, A->Z etc. +-- - Descending = 9->0, Z->A etc. --- @enum ImGuiSortDirection ImGuiSortDirection = { None = 0, Ascending = 1, Descending = 2 } +-- Data payload for Drag and Drop operations: AcceptDragDropPayload(), GetDragDropPayload() --- @class ImGuiPayload --- Drag and drop payload. `Data` is any Lua value (C++ stores raw bytes); `DataSize` kept for API parity. local IM_PAYLOAD = {} @@ -2173,6 +2635,12 @@ function ImGuiPayload_IsDataType(p, t) return p.DataFrameCount ~= -1 and p.DataT function ImGuiPayload_IsPreview(p) return p.Preview end function ImGuiPayload_IsDelivery(p) return p.Delivery end +------------------------------------------------------------------------------- +-- [SECTION] Helpers (ImGuiOnceUponAFrame, ImGuiTextFilter, ImGuiTextBuffer, ImGuiStorage, ImGuiListClipper, Math Operators, ImColor) +------------------------------------------------------------------------------- + +-- Helper: Growable text buffer for logging/accumulating text +-- (this could be called 'ImGuiTextBuilder' / 'ImGuiStringBuilder') --- @class ImGuiTextBuffer # string builder: Buf is a list of string chunks local ImGuiTextBufferMT = {} ImGuiTextBufferMT.__index = ImGuiTextBufferMT diff --git a/imgui_internal.lua b/imgui_internal.lua index 57c327e..74ab171 100644 --- a/imgui_internal.lua +++ b/imgui_internal.lua @@ -1,6 +1,33 @@ ---- Dear ImGui WIP +-- dear imgui, v1.93.0 WIP -- (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. + +-- Index of this file: +-- +-- [SECTION] Context pointer +-- [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 +-- [SECTION] Inputs support +-- [SECTION] Navigation support +-- [SECTION] Viewport support +-- [SECTION] Settings support +-- [SECTION] Localization support +-- [SECTION] Metrics, Debug tools +-- [SECTION] ImGuiContext (main imgui context) +-- [SECTION] ImGuiWindowTempData, ImGuiWindow +-- [SECTION] Tab bar, Tab item support +-- [SECTION] ImGui internal API +-- [SECTION] ImFontLoader +-- [SECTION] ImFontAtlas internal API +-- +-- PORT: the order of declarations in this file does not strictly follow upstream's imgui_internal.h. + --- @meta local type = ImGui._GetTypeFunc() @@ -34,6 +61,9 @@ function ImGui._ByteArrayToString(buf, buf_begin, buf_end) end +-- 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, +-- Indexes have the same lifetime as the associated object. --- ImPool: pool of objects keyed by ID. Public indices are 0-based like upstream (Buf is stored 1-based). --- `ctor` creates a new element. Removed slots are recycled via FreeIdx (-1 = none; free slots chain through `_NextFree`). local IM_POOL = {} @@ -71,8 +101,13 @@ end function IM_POOL:Reserve(n) end -- NOTE: removed slots hold `false`; iterate with `for i = 0, pool:GetMapSize() - 1 do local t = pool:GetByIndex(i) if t then ... end end` +------------------------------------------------------------------------------- +-- [SECTION] Context pointer +-- See implementation of this variable in imgui.cpp for comments and details. +------------------------------------------------------------------------------- + --- @type ImGuiContext? -local GImGui +local GImGui -- Current implicit context pointer -- Sets local `GImGui` in this file(imgui_internal.lua). -- This is currently only used in main code `ImGui.SetCurrentContext()` @@ -85,6 +120,10 @@ local setmetatable = setmetatable local MT = ImGui.GetMetatables() +------------------------------------------------------------------------------- +-- [SECTION] Macros +------------------------------------------------------------------------------- + IM_TABSIZE = 4 FLT_MIN = 1.1754943508223e-38 @@ -94,13 +133,22 @@ INT_MIN = -0x7fffffff - 1 INT_MAX = 0x7fffffff UINT_MAX = 0x7fffffff * 2 + 1 -NAV_WINDOWING_HIGHLIGHT_DELAY = 0.5 -NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10 -NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY = 0.60 +NAV_WINDOWING_HIGHLIGHT_DELAY = 0.5 -- Time before the highlight and screen dimming starts fading in +NAV_ACTIVATE_HIGHLIGHT_TIMER = 0.10 -- Time to highlight an item activated by a shortcut. +NAV_ACTIVATE_INPUT_WITH_GAMEPAD_DELAY = 0.60 -- Time to hold activation button (e.g. FaceDown) to turn the activation into a text input. IM_PI = math.pi -ImPow = math.pow -ImLog = math.log + +------------------------------------------------------------------------------- +-- [SECTION] Generic helpers +-- Note that the ImXXX helpers functions are lower-level than ImGui functions. +-- ImGui functions or the ImGui context are never called/used from other ImXXX functions. +------------------------------------------------------------------------------- + +-- Helpers: Maths +-- - Wrapper for standard libs functions. (Note that imgui_demo.cpp does _not_ use them to keep the code easy to copy) +ImPow = math.pow -- DragBehaviorT/SliderBehaviorT uses ImPow with either float/double and need the precision +ImLog = math.log -- DragBehaviorT/SliderBehaviorT uses ImLog with either float/double and need the precision ImAbs = math.abs ImFabs = math.abs ImFmod = function(a, b) if b < 0 then b = -b end; if a < 0 then return -(-a % b) else return a % b end; end @@ -138,6 +186,7 @@ function ImSubClampOverflow(a, b, mn, mx) return a - b end +-- - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double --- @overload fun(lhs: number, rhs: number): number --- @overload fun(lhs: ImVec2, rhs: ImVec2): ImVec2 @native @@ -154,6 +203,7 @@ function ImMax(lhs, rhs) return ImVec2(mathMax(lhs.x, rhs.x), mathMax(lhs.y, rhs.y)) end +-- Helpers: Sorting --- @param base table --- @param count int --- @param cmp_func fun(lhs, rhs): bool @@ -191,6 +241,7 @@ end ImTrunc64 = _Trunc +-- Consider using the bit-hack version (search for "0x1p120f"). --- @param f float function ImCeilFast(f) local i @@ -203,10 +254,11 @@ function IM_ROUNDUP_TO_EVEN(n) return (ImCeil((n) / 2) * 2) end function ImRsqrt(x) return (1 / ImSqrt(x)) end function IM_TRUNC(VAL) return math.floor(VAL) end -- Positive values only! -function IM_ROUND(VAL) return math.floor(VAL + 0.5) end +function IM_ROUND(VAL) return math.floor(VAL + 0.5) end -- Positive values only! -function ImFloor(f) if f >= 0 or math.floor(f) == f then return math.floor(f) else return math.floor(f) - 1 end end +function ImFloor(f) if f >= 0 or math.floor(f) == f then return math.floor(f) else return math.floor(f) - 1 end end -- Decent replacement for floorf() +-- Helpers: Bit manipulation --- @param v int function ImIsPowerOfTwo(v) return (v ~= 0) and (bitAnd(v, (v - 1)) == 0) @@ -326,8 +378,8 @@ end function ImSaturate(f) return ((f < 0.0 and 0.0) or (f > 1.0 and 1.0) or f) end -IM_F32_TO_INT8_UNBOUND = function(val) return math.floor(val * 255.0 + (val >= 0 and 0.5 or -0.5)) end -IM_F32_TO_INT8_SAT = function(val) return math.floor(ImSaturate(val) * 255.0 + 0.5) end +IM_F32_TO_INT8_UNBOUND = function(val) return math.floor(val * 255.0 + (val >= 0 and 0.5 or -0.5)) end -- Unsaturated, for display purpose +IM_F32_TO_INT8_SAT = function(val) return math.floor(ImSaturate(val) * 255.0 + 0.5) end -- Saturated, always output 0..255 --- @param s ImString --- @param i int @@ -340,6 +392,7 @@ function ImStrByte(s, i) end end +-- Stacked color modifier, backup of modified data so we can restore it --- @class ImGuiColorMod --- @field Col ImGuiCol --- @field BackupValue ImVec4 @@ -434,20 +487,27 @@ IMGUI_FONT_SIZE_THRESHOLD_FOR_LOADADVANCEXONLYMODE = 128.0 IMGUI_WINDOW_HARD_MIN_SIZE = 4.0 -IM_DRAWLIST_ARCFAST_TABLE_SIZE = 48 -IM_DRAWLIST_ARCFAST_SAMPLE_MAX = IM_DRAWLIST_ARCFAST_TABLE_SIZE +-- ImDrawList: Lookup tables +IM_DRAWLIST_ARCFAST_TABLE_SIZE = 48 -- Number of samples in adaptive arc drawing lookup table. +IM_DRAWLIST_ARCFAST_SAMPLE_MAX = IM_DRAWLIST_ARCFAST_TABLE_SIZE -- Sample index _PathArcToFastEx() for 360 angle. +-- Macros used by Recoverable Error handling +-- - Only dispatch error if _EXPR: evaluate as assert (similar to an assert macro). +-- - The message will always be a string literal, in order to increase likelihood of being display by an assert handler. +-- - See 'Demo->Configuration->Error Handling' and ImGuiIO definitions for details on error handling. +-- - Read https://github.com/ocornut/imgui/wiki/Error-Handling for details on error handling. -- Upstream: `if (!(expr) && ErrorLog(msg)) IM_ASSERT(0)`. ErrorLog() returns io.ConfigErrorRecoveryEnableAssert. -function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end +function IM_ASSERT_USER_ERROR(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then if not ImGui.ErrorLog or ImGui.ErrorLog(_MSG) then error(_MSG, 2) end end end -- Recoverable User Error function IM_ASSERT_USER_ERROR_RET(_EXPR, _MSG) if not (_EXPR) or (_EXPR) == 0 then error(_MSG, 2) end end +-- Debug Logging for ShowDebugLogWindow(). This is designed for relatively rare events so please don't spam. local function DebugLogIf(flag, fmt, ...) local g = GImGui if g and bitAnd(g.DebugLogFlags, flag) ~= 0 then ImGui.DebugLog(fmt, ...) end end function IMGUI_DEBUG_LOG_ACTIVEID(...) DebugLogIf(ImGuiDebugLogFlags.EventActiveId, ...) end function IMGUI_DEBUG_LOG_POPUP(...) DebugLogIf(ImGuiDebugLogFlags.EventPopup, ...) end -function IMGUI_DEBUG_LOG_FONT(...) DebugLogIf(ImGuiDebugLogFlags.EventFont, ...) end +function IMGUI_DEBUG_LOG_FONT(...) DebugLogIf(ImGuiDebugLogFlags.EventFont, ...) end -- Called from ImFontAtlas function which may operate without a context. function IMGUI_DEBUG_LOG_VIEWPORT(...) DebugLogIf(ImGuiDebugLogFlags.EventViewport, ...) end function IMGUI_DEBUG_LOG_FOCUS(...) DebugLogIf(ImGuiDebugLogFlags.EventFocus, ...) end function IMGUI_DEBUG_LOG_NAV(...) DebugLogIf(ImGuiDebugLogFlags.EventNav, ...) end @@ -462,9 +522,17 @@ function IMGUI_DEBUG_LOG_ERROR(...) DebugLogIf(ImGuiDebugLogFlags.EventError, .. --- @alias ImGuiSelectionUserData any ImGuiSelectionUserData_Invalid = -1 -ImGuiKeyOwner_Any = 0 -ImGuiKeyOwner_NoOwner = 4294967295 +-- Input function taking an 'ImGuiID owner_id' argument defaults to (ImGuiKeyOwner_Any == 0) aka don't test ownership, which matches legacy behavior. +ImGuiKeyOwner_Any = 0 -- Accept key that have an owner, UNLESS a call to SetKeyOwner() explicitly used ImGuiInputFlags.LockThisFrame or ImGuiInputFlags.LockUntilRelease. +ImGuiKeyOwner_NoOwner = 4294967295 -- Require key to have no owner. +------------------------------------------------------------------------------- +-- [SECTION] ImGui internal API +-- No guarantee of forward compatibility here! +------------------------------------------------------------------------------- + +-- Inputs +-- FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions. --- @param button ImGuiMouseButton --- @return ImGuiKey function ImGui.MouseButtonToKey(button) IM_ASSERT(button >= 0 and button < ImGuiMouseButton.COUNT) return ImGuiKey.MouseLeft + button end @@ -520,6 +588,17 @@ function ImGui.ConvertSingleModFlagToKey(key) return key end +-- [EXPERIMENTAL] Low-Level: Key/Input Ownership +-- - The idea is that instead of "eating" a given input, we can link to an owner id. +-- - Ownership is most often claimed as a result of reacting to a press/down event (but occasionally may be claimed ahead). +-- - Input queries can then read input by specifying ImGuiKeyOwner_Any (== 0), ImGuiKeyOwner_NoOwner (== -1) or a custom ID. +-- - Legacy input queries (without specifying an owner or _Any or _None) are equivalent to using ImGuiKeyOwner_Any (== 0). +-- - Input ownership is automatically released on the frame after a key is released. Therefore: +-- - for ownership registration happening as a result of a down/press event, the SetKeyOwner() call may be done once (common case). +-- - for ownership registration happening ahead of a down/press event, the SetKeyOwner() call needs to be made every frame (happens if e.g. claiming ownership on hover). +-- - SetItemKeyOwner() is a shortcut for common simple case. A custom widget will probably want to call SetKeyOwner() multiple times directly based on its interaction state. +-- - This is marked experimental because not all widgets are fully honoring the Set/Test idioms. We will need to move forward step by step. +-- Please open a GitHub Issue to submit your usage scenario or if there's a use case you need solved. --- @param ctx ImGuiContext --- @param key ImGuiKey function ImGui.GetKeyOwnerData(ctx, key) @@ -528,6 +607,8 @@ function ImGui.GetKeyOwnerData(ctx, key) return ctx.KeysOwnerData[key - ImGuiKey.NamedKey_BEGIN] end +-- This extends ImGuiKeyData but only for named keys (legacy keys don't support the new features) +-- Stored in main context (1 per named key). In the future it might be merged into ImGuiKeyData. --- @class ImGuiKeyOwnerData --- @return ImGuiKeyOwnerData @@ -536,8 +617,8 @@ function ImGuiKeyOwnerData() return { OwnerCurr = ImGuiKeyOwner_NoOwner, OwnerNext = ImGuiKeyOwner_NoOwner, - LockThisFrame = false, - LockUntilRelease = false + LockThisFrame = false, -- Reading this key requires explicit owner id (until end of frame). Set by ImGuiInputFlags.LockThisFrame. + LockUntilRelease = false -- Reading this key requires explicit owner id (until key is released). Set by ImGuiInputFlags.LockUntilRelease. When this is true LockThisFrame is always true as well. } end @@ -580,22 +661,22 @@ function ImCharIsBlankW(c) return c == 32 or c == 9 or c == 0x3000 end ImGuiNavMoveFlags = { None = 0, - LoopX = bitLShift(1, 0), + LoopX = bitLShift(1, 0), -- On failed request, restart from opposite side LoopY = bitLShift(1, 1), - WrapX = bitLShift(1, 2), - WrapY = bitLShift(1, 3), - AllowCurrentNavId = bitLShift(1, 4), - AlsoScoreVisibleSet = bitLShift(1, 5), - ScrollToEdgeY = bitLShift(1, 6), + WrapX = bitLShift(1, 2), -- On failed request, request from opposite side one line down (when NavDir==right) or one line up (when NavDir==left) + WrapY = bitLShift(1, 3), -- This is not super useful but provided for completeness + AllowCurrentNavId = bitLShift(1, 4), -- Allow scoring and considering the current NavId as a move target candidate. This is used when the move source is offset (e.g. pressing PageDown actually needs to send a Up move request, if we are pressing PageDown from the bottom-most item we need to stay in place) + AlsoScoreVisibleSet = bitLShift(1, 5), -- Store alternate result in NavMoveResultLocalVisible that only comprise elements that are already fully visible (used by PageUp/PageDown) + ScrollToEdgeY = bitLShift(1, 6), -- Force scrolling to min/max (used by Home/End) -- FIXME-NAV: Aim to remove or reword as ImGuiScrollFlags Forwarded = bitLShift(1, 7), - DebugNoResult = bitLShift(1, 8), - FocusApi = bitLShift(1, 9), - IsTabbing = bitLShift(1, 10), - IsPageMove = bitLShift(1, 11), - Activate = bitLShift(1, 12), - NoSelect = bitLShift(1, 13), - NoSetNavCursorVisible = bitLShift(1, 14), - NoClearActiveId = bitLShift(1, 15), + DebugNoResult = bitLShift(1, 8), -- Dummy scoring for debug purpose, don't apply result + FocusApi = bitLShift(1, 9), -- Requests from focus API can land/focus/activate items even if they are marked with _NoTabStop (see NavProcessItemForTabbingRequest() for details) + IsTabbing = bitLShift(1, 10), -- == Focus + Activate if item is Inputable + DontChangeNavHighlight + IsPageMove = bitLShift(1, 11), -- Identify a PageDown/PageUp request. + Activate = bitLShift(1, 12), -- Activate/select target item. + NoSelect = bitLShift(1, 13), -- Don't trigger selection by not setting g.NavJustMovedTo + NoSetNavCursorVisible = bitLShift(1, 14), -- Do not alter the nav cursor visible state + NoClearActiveId = bitLShift(1, 15), -- (Experimental) Do not clear active id when applying move result } ImGuiNavMoveFlags.WrapMask_ = bitOr(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.LoopY, ImGuiNavMoveFlags.WrapX, ImGuiNavMoveFlags.WrapY) @@ -603,40 +684,54 @@ ImGuiNavMoveFlags.WrapMask_ = bitOr(ImGuiNavMoveFlags.LoopX, ImGuiNavMoveFlags.L --- @enum ImGuiNavLayer ImGuiNavLayer = { - Main = 0, - Menu = 1, + Main = 0, -- Main scrolling layer + Menu = 1, -- Menu layer (access with Alt) COUNT = 2 } -ImGuiItemFlags.ReadOnly = bitLShift(1, 11) +------------------------------------------------------------------------------- +-- [SECTION] Widgets support: flags, enums, data structures +------------------------------------------------------------------------------- + +-- Extend ImGuiItemFlags +-- - input: PushItemFlag() manipulates g.CurrentItemFlags, g.NextItemData.ItemFlags, ItemAdd() calls may add extra flags too. +-- - output: stored in g.LastItemData.ItemFlags + +-- Controlled by user +ImGuiItemFlags.ReadOnly = bitLShift(1, 11) -- false -- [ALPHA] Allow hovering interactions but underlying value is not changed. ImGuiItemFlags.MixedValue = bitLShift(1, 12) -ImGuiItemFlags.NoWindowHoverableCheck = bitLShift(1, 13) -ImGuiItemFlags.AllowOverlap = bitLShift(1, 14) -ImGuiItemFlags.NoNavDisableMouseHover = bitLShift(1, 15) -ImGuiItemFlags.NoMarkEdited = bitLShift(1, 16) -ImGuiItemFlags.NoFocus = bitLShift(1, 17) +ImGuiItemFlags.NoWindowHoverableCheck = bitLShift(1, 13) -- false -- Disable hoverable check in ItemHoverable() +ImGuiItemFlags.AllowOverlap = bitLShift(1, 14) -- false -- Allow being overlapped by another widget. Not-hovered to Hovered transition deferred by a frame. +ImGuiItemFlags.NoNavDisableMouseHover = bitLShift(1, 15) -- false -- Nav keyboard/gamepad mode doesn't disable hover highlight (behave as if NavHighlightItemUnderNav==false). +ImGuiItemFlags.NoMarkEdited = bitLShift(1, 16) -- false -- Skip calling MarkItemEdited() +ImGuiItemFlags.NoFocus = bitLShift(1, 17) -- false -- [EXPERIMENTAL: Not very well specced] Clicking doesn't take focus. Automatically sets ImGuiButtonFlags.NoFocus + ImGuiButtonFlags.NoNavFocus in ButtonBehavior(). -ImGuiItemFlags.Inputable = bitLShift(1, 20) -ImGuiItemFlags.HasSelectionUserData = bitLShift(1, 21) -ImGuiItemFlags.IsMultiSelect = bitLShift(1, 22) +-- Controlled by widget code +ImGuiItemFlags.Inputable = bitLShift(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. +ImGuiItemFlags.HasSelectionUserData = bitLShift(1, 21) -- false -- Set by SetNextItemSelectionUserData() +ImGuiItemFlags.IsMultiSelect = bitLShift(1, 22) -- false -- Set by SetNextItemSelectionUserData() -ImGuiItemFlags.Default_ = bitOr(ImGuiItemFlags.AutoClosePopups, ImGuiItemFlags.LiveEditOnInputText) +ImGuiItemFlags.Default_ = bitOr(ImGuiItemFlags.AutoClosePopups, ImGuiItemFlags.LiveEditOnInputText) -- Please don't change, use PushItemFlag() instead. +-- Helpers: High-level text functions (DO NOT USE!!! THIS IS A MINIMAL SUBSET OF LARGER UPCOMING CHANGES) --- @enum ImDrawTextFlags ImDrawTextFlags = { None = 0, - CpuFineClip = bitLShift(1, 0), + CpuFineClip = bitLShift(1, 0), -- Must be == 1/true for legacy with 'bool cpu_fine_clip' arg to RenderText() WrapKeepBlanks = bitLShift(1, 1), StopOnNewLine = bitLShift(1, 2) } +-- Flags for FocusWindow(). This is not called ImGuiFocusFlags to avoid confusion with public-facing ImGuiFocusedFlags. +-- FIXME: Once we finishing replacing more uses of GetTopMostPopupModal()+IsWindowWithinBeginStackOf() +-- and FindBlockingModal() with this, we may want to change the flag to be opt-out instead of opt-in. --- @enum ImGuiFocusRequestFlags ImGuiFocusRequestFlags = { None = 0, - RestoreFocusedChild = bitLShift(1, 0), - UnlessBelowModal = bitLShift(1, 1) + RestoreFocusedChild = bitLShift(1, 0), -- Find last focused child (if any) and focus it instead. + UnlessBelowModal = bitLShift(1, 1) -- Do not set focus if the window is below a modal. } --- @enum ImGuiTextFlags @@ -646,6 +741,7 @@ ImGuiTextFlags = NoWidthForLargeClippedText = bitLShift(1, 0) } +-- Character classification for word-wrapping logic --- @enum ImWcharClass ImWcharClass = { @@ -654,6 +750,8 @@ ImWcharClass = Other = 2 } +-- Helper: ImVec1 (1D vector) +-- (this odd construct is used to facilitate the transition between 1D and 2D, and the maintenance of some branches/patches) --- @class ImVec1 --- @field x number local IM_VEC1 = {} @@ -669,11 +767,13 @@ function ImVec1_Copy(dest, src) dest.x = src.x end +-- Helper: ImRect (2D axis aligned bounding-box) +-- NB: we can't rely on ImVec2 math operators being available here! --- @class ImRect --- @field [1] ImVec2 --- @field [2] ImVec2 ---- @field Min ImVec2 ---- @field Max ImVec2 +--- @field Min ImVec2 # Upper-left +--- @field Max ImVec2 # Lower-right local IM_RECT = {} setmetatable(IM_RECT, { __index = function(_, k) if k ~= "Min" and k ~= "Max" then error("ImRect: unknown key " .. tostring(k), 2) end end }) @@ -725,20 +825,22 @@ function IM_RECT:GetHeight() return self.Max.y - self.Min.y end function IM_RECT:GetSize() return ImVec2(self.Max.x - self.Min.x, self.Max.y - self.Min.y) end --- @nodiscard -function IM_RECT:GetTL() return ImVec2(self.Min.x, self.Min.y) end +function IM_RECT:GetTL() return ImVec2(self.Min.x, self.Min.y) end -- Top-left --- @nodiscard -function IM_RECT:GetTR() return ImVec2(self.Max.x, self.Min.y) end +function IM_RECT:GetTR() return ImVec2(self.Max.x, self.Min.y) end -- Top-right --- @nodiscard -function IM_RECT:GetBL() return ImVec2(self.Min.x, self.Max.y) end +function IM_RECT:GetBL() return ImVec2(self.Min.x, self.Max.y) end -- Bottom-left --- @nodiscard -function IM_RECT:GetBR() return ImVec2(self.Max.x, self.Max.y) end +function IM_RECT:GetBR() return ImVec2(self.Max.x, self.Max.y) end -- Bottom-right +-- Simple version, may lead to an inverted rectangle, which is fine for Contains/Overlaps test but not for display. --- @param r ImRect @native function IM_RECT:ClipWith(r) ImVec2_Copy(self.Min, ImMax(self.Min, r.Min)); ImVec2_Copy(self.Max, ImMin(self.Max, r.Max)) end +-- Full version, ensure both points are fully clipped. --- @param r ImRect @native function IM_RECT:ClipWithFull(r) @@ -819,12 +921,15 @@ function ImRect_CopyFromV4(dest, src) dest.Max.x = src.z; dest.Max.y = src.w end +-- Helper: ImBitArray +-- Macro version of ImBitArrayTestBit(): ensure args have side-effect or are costly! --- @param _ARRAY ImU32[] --- @param _N int function IM_BITARRAY_TESTBIT(_ARRAY, _N) return bitAnd(_ARRAY[bitRShift(_N - 1, 5) + 1], bitLShift(1, bitAnd(_N - 1, 31))) ~= 0 end +-- Macro version of ImBitArrayClearBit(): ensure args have side-effect or are costly! --- @param _ARRAY ImU32[] --- @param _N int function IM_BITARRAY_CLEARBIT(_ARRAY, _N) @@ -840,8 +945,11 @@ function ImBitArraySetBit(arr, n) arr[idx] = bitOr(arr[idx], mask) end +-- Bit array for named keys --- @alias ImBitArrayForNamedKeys ImBitArray +-- Helper: ImBitArray class (wrapper over ImBitArray functions) +-- Store 1-bit per value. --- NOTE: This struct is expensive to create --- @class ImBitArray --- @field Data ImU32[] @@ -868,6 +976,9 @@ function ImBitArray(BITCOUNT, OFFSET) return this end +-- 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. +-- so e.g. 'PathArcTo(center, radius, PI * -0.5, PI)' is ok, whereas 'PathArcTo(center, radius, PI, PI * -0.5)' won't have correct anti-aliasing when followed by PathFillConvex(). function MT.ImDrawList:PathClear() self._Path:clear() end --- @param pos ImVec2 @@ -905,24 +1016,32 @@ function ImGui.SetNextItemColorMarker(col) g.NextItemData.ColorMarker = col end +------------------------------------------------------------------------------- +-- [SECTION] ImDrawList support +------------------------------------------------------------------------------- + +-- Data shared between all ImDrawList instances +-- 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. --- @class ImDrawListSharedData ---- @field TexUvWhitePixel ImVec2 ---- @field TexUvLines ImVec4[] ---- @field FontAtlas ImFontAtlas ---- @field Font ImFont ---- @field FontSize float ---- @field FontScale float +--- @field TexUvWhitePixel ImVec2 # UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) +--- @field TexUvLines ImVec4[] # UV of anti-aliased lines in the atlas (== FontAtlas->Builder->TexUvLines) +--- @field FontAtlas ImFontAtlas # Current font atlas +--- @field Font ImFont # Current font (used for simplified AddText overload) +--- @field FontSize float # Current font size (used for simplified AddText overload) +--- @field FontScale float # Current font scale (== FontSize / Font->FontSize) --- @field CurveTessellationTol float ---- @field CircleTessellationMaxError float +--- @field CircleTessellationMaxError float # Number of circle segments to use per pixel of radius for AddCircle() etc --- @field InitialFringeScale float --- @field InitialFlags ImDrawListFlags ---- @field ClipRectFullscreen? ImVec4 ---- @field TempBuffer ImVector ---- @field DrawLists ImVector ---- @field Context? ImGuiContext ---- @field ArcFastVtx table # 1-based table ---- @field ArcFastRadiusCutoff float ---- @field CircleSegmentCounts table # 1-based table +--- @field ClipRectFullscreen? ImVec4 # Value for PushClipRectFullscreen() +--- @field TempBuffer ImVector # Temporary write buffer +--- @field DrawLists ImVector # All draw lists associated to this ImDrawListSharedData +--- @field Context? ImGuiContext # [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case. +--- @field ArcFastVtx table # 1-based table. Sample points on the quarter of the circle. +--- @field ArcFastRadiusCutoff float # Cutoff radius after which arc drawing will fallback to slower PathArcTo() +--- @field CircleSegmentCounts table # 1-based table. Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) MT.ImDrawListSharedData = {} MT.ImDrawListSharedData.__index = MT.ImDrawListSharedData @@ -930,28 +1049,29 @@ MT.ImDrawListSharedData.__index = MT.ImDrawListSharedData --- @nodiscard function ImDrawListSharedData() local this = setmetatable({ - TexUvWhitePixel = nil, - TexUvLines = nil, - FontAtlas = nil, + TexUvWhitePixel = nil, -- UV of white pixel in the atlas (== FontAtlas->TexUvWhitePixel) + TexUvLines = nil, -- UV of anti-aliased lines in the atlas (== FontAtlas->Builder->TexUvLines) + FontAtlas = nil, -- Current font atlas - Font = nil, - FontSize = 0, - FontScale = 0, + Font = nil, -- Current font (used for simplified AddText overload) + FontSize = 0, -- Current font size (used for simplified AddText overload) + FontScale = 0, -- Current font scale (== FontSize / Font->FontSize) CurveTessellationTol = 0, - CircleTessellationMaxError = 0, + CircleTessellationMaxError = 0, -- Number of circle segments to use per pixel of radius for AddCircle() etc InitialFringeScale = 1, InitialFlags = 0, - ClipRectFullscreen = nil, - TempBuffer = ImVector(ImVec2), - DrawLists = ImVector(), + ClipRectFullscreen = nil, -- Value for PushClipRectFullscreen() + TempBuffer = ImVector(ImVec2), -- Temporary write buffer + DrawLists = ImVector(), -- All draw lists associated to this ImDrawListSharedData - ArcFastVtx = {}, - ArcFastRadiusCutoff = nil, - CircleSegmentCounts = {}, + -- Lookup tables + ArcFastVtx = {}, -- Sample points on the quarter of the circle. + ArcFastRadiusCutoff = nil, -- Cutoff radius after which arc drawing will fallback to slower PathArcTo() + CircleSegmentCounts = {}, -- Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) - Context = nil + Context = nil -- [OPTIONAL] Link to Dear ImGui context. 99% of ImDrawList/ImFontAtlas can function without an ImGui context, but this facilitate handling one legacy edge case. }, MT.ImDrawListSharedData) for i = 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE do @@ -962,6 +1082,7 @@ function ImDrawListSharedData() return this end +-- Internal storage for incrementally packing and building a ImFontAtlas --- @class ImFontAtlasBuilder --- @field PackContext stbrp_context --- @field PackNodes ImVector @@ -991,27 +1112,29 @@ function ImFontAtlasBuilder() --- @type ImFontAtlasBuilder local this = setmetatable({}, MT.ImFontAtlasBuilder) - this.PackContext = nil -- struct stbrp_context_opaque { char data[80]; }; + this.PackContext = nil -- struct stbrp_context_opaque { char data[80]; }; -- Actually 'stbrp_context' but we don't want to define this in the header file. this.PackNodes = ImVector() this.Rects = ImVector() - this.RectsIndex = ImVector() - this.TempBuffer = ImVector() - this.RectsIndexFreeListStart = -1 - this.RectsPackedCount = 0 - this.RectsPackedSurface = 0 + this.RectsIndex = ImVector() -- ImFontAtlasRectId -> index into Rects[] + this.TempBuffer = ImVector() -- Misc scratch buffer + this.RectsIndexFreeListStart = -1 -- First unused entry + this.RectsPackedCount = 0 -- Number of packed rectangles. + this.RectsPackedSurface = 0 -- Number of packed pixels. Used when compacting to heuristically find the ideal texture size. this.RectsDiscardedCount = 0 this.RectsDiscardedSurface = 0 - this.FrameCount = -1 - this.MaxRectSize = ImVec2() - this.MaxRectBounds = ImVec2() - this.LockDisableResize = false - this.PreloadedAllGlyphsRanges = false + this.FrameCount = -1 -- Current frame count + this.MaxRectSize = ImVec2() -- Largest rectangle to pack (de-facto used as a "minimum texture size") + this.MaxRectBounds = ImVec2() -- Bottom-right most used pixels + this.LockDisableResize = false -- Disable resizing texture + this.PreloadedAllGlyphsRanges = false -- Set when missing ImGuiBackendFlags.RendererHasTextures features forces atlas to preload everything. + -- Cache of all ImFontBaked this.BakedPool = ImVector() -- ImStableVector - this.BakedMap = {} + this.BakedMap = {} -- BakedId --> ImFontBaked this.BakedDiscardedCount = 0 - this.PackIdMouseCursors = -1 + -- Custom rectangle identifiers + this.PackIdMouseCursors = -1 -- White pixel + mouse cursors. Also happen to be fallback in case of packing failure. this.PackIdLinesTexData = -1 return this @@ -1019,8 +1142,8 @@ end --- @class ImFontStackData --- @field Font ImFont ---- @field FontSizeBeforeScaling float ---- @field FontSizeAfterScaling float +--- @field FontSizeBeforeScaling float # ~~ style.FontSizeBase +--- @field FontSizeAfterScaling float # ~~ g.FontSize --- @return ImFontStackData --- @param font ImFont @@ -1030,14 +1153,18 @@ end function ImFontStackData(font, font_size_before_scaling, font_size_after_scaling) return { Font = font, - FontSizeBeforeScaling = font_size_before_scaling, - FontSizeAfterScaling = font_size_after_scaling + FontSizeBeforeScaling = font_size_before_scaling, -- ~~ style.FontSizeBase + FontSizeAfterScaling = font_size_after_scaling -- ~~ g.FontSize } end +------------------------------------------------------------------------------- +-- [SECTION] Style support +------------------------------------------------------------------------------- + --- `GetVarPtr()` is currently only used on `g.Style` in Dear ImGui, and we don't have pointers! --- @class ImGuiStyleVarInfo ---- @field Count ImU32 +--- @field Count ImU32 # 1+ --- @field DataType ImGuiDataType --- @field Key string # key in parent structure. Note that the cpp Dear ImGui uses `ImU32 Offset`! @@ -1050,6 +1177,7 @@ function ImGuiStyleVarInfo(count, data_type, key) return { Count = count, DataType = data_type, Key = key } end +-- Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. --- @class ImGuiStyleMod --- @field VarIdx ImGuiStyleVar --- @field BackupVal table @@ -1069,36 +1197,42 @@ function ImGuiStyleMod(idx, v) return this end ---- Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo() +------------------------------------------------------------------------------- +-- [SECTION] Data types support +------------------------------------------------------------------------------- + +-- Type information associated to one ImGuiDataType. Retrieve with DataTypeGetInfo(). --- @class ImGuiDataTypeInfo --- @field Size size_t # Size in bytes --- @field Name string # Short descriptive name for the type, for debugging --- @field PrintFmt string # Default printf format for the type --- @field ScanFmt string # Default scanf format for the type +-- Status storage for the last submitted item --- @class ImGuiLastItemData --- @field ID ImGuiID ---- @field ItemFlags ImGuiItemFlags ---- @field StatusFlags ImGuiItemStatusFlags ---- @field Rect ImRect ---- @field NavRect ImRect ---- @field DisplayRect ImRect ---- @field ClipRect ImRect ---- @field Shortcut ImGuiKeyChord +--- @field ItemFlags ImGuiItemFlags # See ImGuiItemFlags (called 'InFlags' before v1.91.4). +--- @field StatusFlags ImGuiItemStatusFlags # See ImGuiItemStatusFlags +--- @field Rect ImRect # Full rectangle +--- @field NavRect ImRect # Navigation scoring rectangle (not displayed) +--- @field DisplayRect ImRect # Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasDisplayRect) is set. +--- @field ClipRect ImRect # Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasClipRect) is set.. +--- @field Shortcut ImGuiKeyChord # Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasShortcut) is set.. --- @return ImGuiLastItemData --- @nodiscard function ImGuiLastItemData() return { ID = 0, - ItemFlags = 0, - StatusFlags = 0, - Rect = ImRect(), - NavRect = ImRect(), + ItemFlags = 0, -- See ImGuiItemFlags (called 'InFlags' before v1.91.4). + StatusFlags = 0, -- See ImGuiItemStatusFlags + Rect = ImRect(), -- Full rectangle + NavRect = ImRect(), -- Navigation scoring rectangle (not displayed) - DisplayRect = ImRect(), - ClipRect = ImRect(), - Shortcut = 0 + -- Rarely used fields are not explicitly cleared, only valid when the corresponding ImGuiItemStatusFlags are set. + DisplayRect = ImRect(), -- Display rectangle. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasDisplayRect) is set. + ClipRect = ImRect(), -- Clip rectangle at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasClipRect) is set.. + Shortcut = 0 -- Shortcut at the time of submitting item. ONLY VALID IF (StatusFlags & ImGuiItemStatusFlags.HasShortcut) is set.. } end @@ -1115,6 +1249,10 @@ function ImGuiLastItemData_Copy(dest, src) dest.Shortcut = src.Shortcut end +-- Store data emitted by TreeNode() for usage by TreePop() +-- - 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. --- @class ImGuiTreeNodeStackData --- @field ID ImGuiID --- @field TreeFlags ImGuiTreeNodeFlags @@ -1130,14 +1268,15 @@ local function ImGuiTreeNodeStackData() return { ID = nil, TreeFlags = nil, - ItemFlags = nil, - NavRect = ImRect(), + ItemFlags = nil, -- Used for nav landing + NavRect = ImRect(), -- Used for nav landing DrawLinesX1 = nil, DrawLinesToNodesY2 = nil, DrawLinesTableColumn = nil } end +-- Storage for SetNextItem** functions --- @class ImGuiNextItemData --- @field HasFlags ImGuiNextItemDataFlags --- @field ItemFlagsSet ImGuiItemFlags @@ -1154,6 +1293,7 @@ end local IMGUI_NEXT_ITEM_DATA = {} IMGUI_NEXT_ITEM_DATA.__index = IMGUI_NEXT_ITEM_DATA +-- Also cleared manually by ItemAdd()! function IMGUI_NEXT_ITEM_DATA:ClearFlags() self.HasFlags = ImGuiNextItemDataFlags.None self.ItemFlagsSet = ImGuiItemFlags.None @@ -1163,22 +1303,24 @@ end --- @nodiscard function ImGuiNextItemData() return setmetatable({ - HasFlags = 0, - ItemFlagsSet = 0, + HasFlags = 0, -- Called HasFlags instead of Flags to avoid mistaking this + ItemFlagsSet = 0, -- Currently only tested/used for ImGuiItemFlags.AllowOverlap and ImGuiItemFlags.HasSelectionUserData. - FocusScopeId = 0, - SelectionUserData = -1, - Width = 0.0, - Shortcut = 0, - ShortcutFlags = 0, - OpenVal = false, - OpenCond = 0, - RefVal = 0, - StorageId = 0, - ColorMarker = 0 + -- Members below are NOT cleared by ItemAdd() meaning they are still valid during e.g. NavProcessItem(). Always rely on HasFlags. + FocusScopeId = 0, -- Set by SetNextItemSelectionUserData() + SelectionUserData = -1, -- Set by SetNextItemSelectionUserData() (note that nil/0 is a valid value, we use -1 == ImGuiSelectionUserData_Invalid to mark invalid values) + Width = 0.0, -- Set by SetNextItemWidth() + Shortcut = 0, -- Set by SetNextItemShortcut() + ShortcutFlags = 0, -- Set by SetNextItemShortcut() + OpenVal = false, -- Set by SetNextItemOpen() + OpenCond = 0, -- Set by SetNextItemOpen() + RefVal = 0, -- Not exposed yet, for ImGuiInputTextFlags.ParseEmptyAsRefVal + StorageId = 0, -- Set by SetNextItemStorageID() + ColorMarker = 0 -- Set by SetNextItemColorMarker(). Not exposed yet, supported by DragScalar,SliderScalar and for ImGuiSliderFlags.ColorMarkers. }, IMGUI_NEXT_ITEM_DATA) end +-- Storage for SetNexWindow** functions --- @class ImGuiNextWindowData --- @field HasFlags ImGuiNextWindowDataFlags --- @field PosCond ImGuiCond @@ -1211,6 +1353,7 @@ function ImGuiNextWindowData() return setmetatable({ HasFlags = 0, + -- Members below are NOT cleared. Always rely on HasFlags. PosCond = 0, SizeCond = 0, CollapsedCond = 0, @@ -1221,9 +1364,9 @@ function ImGuiNextWindowData() ScrollVal = ImVec2(), WindowFlags = nil, ChildFlags = nil, - WindowFlagsSet = 0, + WindowFlagsSet = 0, -- Flags to set. Use SetNextWindowFlags()! WindowFlagsClear = 0, - ChildFlagsSet = 0, + ChildFlagsSet = 0, -- Flags to set. Use SetNextWindowChildFlags(). ChildFlagsClear = 0, ViewportId = 0, DockId = 0, @@ -1234,8 +1377,8 @@ function ImGuiNextWindowData() SizeConstraintRect = nil, SizeCallback = nil, SizeCallbackUserData = nil, - BgAlphaVal = nil, - MenuBarOffsetMinVal = ImVec2(), + BgAlphaVal = nil, -- Override background alpha + MenuBarOffsetMinVal = ImVec2(), -- (Always on) This is not exposed publicly, so we don't clear it and it doesn't have a corresponding flag (could we? for consistency?) RefreshFlagsVal = nil, CacheKeySet = false, -- [Port] SetNextWindowCached() CacheKeyVal = nil @@ -1245,7 +1388,7 @@ end --- @enum ImGuiWindowBgClickFlags ImGuiWindowBgClickFlags = { None = 0, - Move = bitLShift(1, 0), + Move = bitLShift(1, 0), -- Click on bg/void + drag to move window. Cleared by default when using io.ConfigWindowsMoveFromTitleBarOnly. } --- @enum ImGuiNextWindowDataFlags @@ -1267,6 +1410,8 @@ ImGuiNextWindowDataFlags = { HasWindowClass = bitLShift(1, 13) } +-- FIXME: this is in development, not exposed/functional as a generic feature yet. +-- Horizontal/Vertical enums are fixed to 0/1 so they may be used to index ImVec2 --- @enum ImGuiLayoutType ImGuiLayoutType = { @@ -1280,7 +1425,7 @@ ImGuiSeparatorFlags = None = 0, Horizontal = bitLShift(1, 0), -- Axis default to current layout type, so generally Horizontal unless e.g. in a menu bar Vertical = bitLShift(1, 1), - SpanAllColumns = bitLShift(1, 2) -- Make separator cover all columns of a legacy Columns() set + SpanAllColumns = bitLShift(1, 2) -- Make separator cover all columns of a legacy Columns() set. } --- @class ImGuiStyle @@ -1292,111 +1437,114 @@ MT.ImGuiStyle.__index = MT.ImGuiStyle function ImGuiStyle() --- @type ImGuiStyle local this = { - FontSizeBase = 0.0, - FontScaleMain = 1.0, - FontScaleDpi = 1.0, + FontSizeBase = 0.0, -- Will default to io.Fonts.Fonts[0] on first frame. + FontScaleMain = 1.0, -- Main scale factor. May be set by application once, or exposed to end-user. + FontScaleDpi = 1.0, -- Additional scale factor from viewport/monitor contents scale. When io.ConfigDpiScaleFonts is enabled, this is automatically overwritten when changing monitor DPI. - Alpha = 1.0, - DisabledAlpha = 0.60, + Alpha = 1.0, -- Global alpha applies to everything in Dear ImGui. + DisabledAlpha = 0.60, -- Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha. - FramePadding = ImVec2(4, 3), - FrameRounding = 0.0, - FrameBorderSize = 0.0, - WindowPadding = ImVec2(8, 8), + FramePadding = ImVec2(4, 3), -- Padding within a framed rectangle (used by most widgets) + FrameRounding = 0.0, -- Radius of frame corners rounding. Set to 0.0 to have rectangular frames (used by most widgets). + FrameBorderSize = 0.0, -- Thickness of border around frames. Generally set to 0.0 or 1.0. Other values not well tested. + WindowPadding = ImVec2(8, 8), -- Padding within a window - TouchExtraPadding = ImVec2(0, 0), - IndentSpacing = 21.0, + TouchExtraPadding = ImVec2(0, 0), -- Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + IndentSpacing = 21.0, -- Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). - WindowRounding = 0, - WindowBorderSize = 1, + WindowRounding = 0, -- Radius of window corners rounding. Set to 0.0 to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended. + WindowBorderSize = 1, -- Thickness of border around windows. Generally set to 0.0 or 1.0. Other values not well tested. - ScrollbarSize = 14.0, - ScrollbarRounding = 9.0, - ScrollbarPadding = 2.0, - GrabMinSize = 12.0, - GrabRounding = 0.0, - ImageRounding = 0.0, - ImageBorderSize = 0.0, + ScrollbarSize = 14.0, -- Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarRounding = 9.0, -- Radius of grab corners rounding for scrollbar + ScrollbarPadding = 2.0, -- Padding of scrollbar grab within its frame (same for both axes) + GrabMinSize = 12.0, -- Minimum width/height of a grab box for slider/scrollbar + GrabRounding = 0.0, -- Radius of grabs corners rounding. Set to 0.0 to have rectangular slider grabs. + ImageRounding = 0.0, -- Rounding of Image() calls. + ImageBorderSize = 0.0, -- Thickness of border around Image() calls. - WindowBorderHoverPadding = 4.0, + WindowBorderHoverPadding = 4.0, -- 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. TreeLinesFlags = ImGuiTreeNodeFlags.DrawLinesNone, - TreeLinesSize = 1.0, - TreeLinesRounding = 0.0, - MenuItemRounding = 0.0, - SelectableRounding = 0.0, + TreeLinesSize = 1.0, -- Thickness of outlines when using ImGuiTreeNodeFlags.DrawLines. + TreeLinesRounding = 0.0, -- Radius of lines connecting child nodes to the vertical line. + MenuItemRounding = 0.0, -- Radius of MenuItem, BeginMenu rounding. + SelectableRounding = 0.0, -- Radius of selectable rounding. MODIFYING THIS IS DISCOURAGED. CONTIGUOUS SELECTIONS WILL NOT LOOK RIGHT. (#7589) - ColorMarkerSize = 3.0, - ColorButtonPosition = ImGuiDir.Right, + ColorMarkerSize = 3.0, -- Size of R/G/B/A color markers for ColorEdit4() and for Drags/Sliders when using ImGuiSliderFlags.ColorMarkers. + ColorButtonPosition = ImGuiDir.Right, -- Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir.Right. - InputTextCursorSize = 1.0, - SeparatorSize = 1.0, - SeparatorTextBorderSize = 3.0, - SeparatorTextAlign = ImVec2(0.0, 0.5), - SeparatorTextPadding = ImVec2(20.0, 3.0), + InputTextCursorSize = 1.0, -- Thickness of cursor/caret in InputText(). + SeparatorSize = 1.0, -- Thickness of border in Separator(). + SeparatorTextBorderSize = 3.0, -- Thickness of border in SeparatorText(). + SeparatorTextAlign = ImVec2(0.0, 0.5), -- Alignment of text within the separator. Defaults to (0.0, 0.5) (left aligned, center). + SeparatorTextPadding = ImVec2(20.0, 3.0), -- Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y. - DisplaySafeAreaPadding = ImVec2(3, 3), - DisplayWindowPadding = ImVec2(19, 19), + 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. + 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. - AntiAliasedLines = true, - AntiAliasedLinesUseTex = true, - AntiAliasedFill = true, + -- Rendering & Tessellation + AntiAliasedLines = true, -- Enable anti-aliased lines/borders. Used at the beginning of the frame to set ImDrawListFlags.AntiAliasedLines in all draw-lists. + AntiAliasedLinesUseTex = true, -- Enable anti-aliased lines/borders using textures for legacy strokes. Require backend to render with bilinear filtering (NOT point/nearest filtering). + AntiAliasedFill = true, -- Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Used at the beginning of the frame to set ImDrawListFlags.AntiAliasedFill in all draw-lists. - CurveTessellationTol = 1.25, - CircleTessellationMaxError = 0.30, + CurveTessellationTol = 1.25, -- Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + CircleTessellationMaxError = 0.30, -- 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. - HoverStationaryDelay = 0.15, - HoverDelayShort = 0.15, - HoverDelayNormal = 0.40, + -- Behaviors + HoverStationaryDelay = 0.15, -- Delay for IsItemHovered(ImGuiHoveredFlags.Stationary). Time required to consider mouse stationary. + HoverDelayShort = 0.15, -- Delay for IsItemHovered(ImGuiHoveredFlags.DelayShort). Usually used along with HoverStationaryDelay. + HoverDelayNormal = 0.40, -- Delay for IsItemHovered(ImGuiHoveredFlags.DelayNormal). " Colors = {}, - ButtonTextAlign = ImVec2(0.5, 0.5), - SelectableTextAlign = ImVec2(0.0, 0.0), + ButtonTextAlign = ImVec2(0.5, 0.5), -- Alignment of button text when button is larger than text. + SelectableTextAlign = ImVec2(0.0, 0.0), -- Alignment of selectable text. Defaults to (0.0, 0.0) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line. - WindowMinSize = ImVec2(32, 32), - WindowTitleAlign = ImVec2(0.0, 0.5), - WindowMenuButtonPosition = ImGuiDir.Left, - ChildRounding = 0.0, - ChildBorderSize = 1.0, - PopupRounding = 0.0, - PopupBorderSize = 1.0, + WindowMinSize = ImVec2(32, 32), -- Minimum window size + WindowTitleAlign = ImVec2(0.0, 0.5), -- Alignment for title bar text + WindowMenuButtonPosition = ImGuiDir.Left, -- Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir.Left. + ChildRounding = 0.0, -- Radius of child window corners rounding. Set to 0.0 to have rectangular child windows + ChildBorderSize = 1.0, -- Thickness of border around child windows. Generally set to 0.0 or 1.0. Other values not well tested. + PopupRounding = 0.0, -- Radius of popup window corners rounding. Set to 0.0 to have rectangular child windows + PopupBorderSize = 1.0, -- Thickness of border around popup or tooltip windows. Generally set to 0.0 or 1.0. Other values not well tested. - DockingSeparatorSize = 2.0, - DockingNodeHasCloseButton = true, - MouseCursorScale = 1.0, + DockingSeparatorSize = 2.0, -- Thickness of resizing border between docked windows + DockingNodeHasCloseButton = true, -- Docking nodes have their own CloseButton() to close all docked windows. + MouseCursorScale = 1.0, -- Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. - ItemSpacing = ImVec2(8, 4), - ItemInnerSpacing = ImVec2(4, 4), - CellPadding = ImVec2(4, 2), + ItemSpacing = ImVec2(8, 4), -- Horizontal and vertical spacing between widgets/lines + ItemInnerSpacing = ImVec2(4, 4), -- Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + CellPadding = ImVec2(4, 2), -- Padding within a table cell. Cellpadding.x is locked for entire table. CellPadding.y may be altered between different rows. - ColumnsMinSpacing = 6.0, + ColumnsMinSpacing = 6.0, -- Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). - LogSliderDeadzone = 4.0, + LogSliderDeadzone = 4.0, -- The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero. - TabRounding = 5.0, - TabBorderSize = 0.0, - TabMinWidthBase = 1.0, - TabMinWidthShrink = 80.0, - TabCloseButtonMinWidthSelected = -1.0, - TabCloseButtonMinWidthUnselected = 0.0, - TabBarBorderSize = 1.0, - TabBarOverlineSize = 1.0, - TableAngledHeadersAngle = 35.0 * (IM_PI / 180.0), - TableAngledHeadersTextAlign = ImVec2(0.5, 0.0), + TabRounding = 5.0, -- Radius of upper corners of a tab. Set to 0.0 to have rectangular tabs. + TabBorderSize = 0.0, -- Thickness of border around tabs. + TabMinWidthBase = 1.0, -- Minimum tab width, to make tabs larger than their contents. TabBar buttons are not affected. + TabMinWidthShrink = 80.0, -- Minimum tab width after shrinking, when using ImGuiTabBarFlags.FittingPolicyMixed policy. FLT_MAX: never shrink, will behave like ImGuiTabBarFlags.FittingPolicyScroll. + TabCloseButtonMinWidthSelected = -1.0, -- -1: always visible. 0.0: visible when hovered. >0.0: visible when hovered if minimum width. + TabCloseButtonMinWidthUnselected = 0.0, -- -1: always visible. 0.0: visible when hovered. >0.0: visible when hovered if minimum width. FLT_MAX: never show close button when unselected. + TabBarBorderSize = 1.0, -- Thickness of tab-bar separator, which takes on the tab active color to denote focus. + TabBarOverlineSize = 1.0, -- Thickness of tab-bar overline, which highlights the selected tab-bar. + TableAngledHeadersAngle = 35.0 * (IM_PI / 180.0), -- Angle of angled headers (supported values range from -50 degrees to +50 degrees). + TableAngledHeadersTextAlign = ImVec2(0.5, 0.0), -- Alignment of angled headers within the cell - DragDropTargetRounding = 0.0, - DragDropTargetBorderSize = 2.0, - DragDropTargetPadding = 3.0, + DragDropTargetRounding = 0.0, -- Radius of the drag and drop target frame. + DragDropTargetBorderSize = 2.0, -- Thickness of the drag and drop target border. + DragDropTargetPadding = 3.0, -- Size to expand the drag and drop target from actual target item size. - HoverFlagsForTooltipMouse = bitOr(ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.AllowWhenDisabled), - HoverFlagsForTooltipNav = bitOr(ImGuiHoveredFlags.NoSharedDelay, ImGuiHoveredFlags.DelayNormal, ImGuiHoveredFlags.AllowWhenDisabled), + HoverFlagsForTooltipMouse = bitOr(ImGuiHoveredFlags.Stationary, ImGuiHoveredFlags.DelayShort, ImGuiHoveredFlags.AllowWhenDisabled), -- Default flags when using IsItemHovered(ImGuiHoveredFlags.ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse. + HoverFlagsForTooltipNav = bitOr(ImGuiHoveredFlags.NoSharedDelay, ImGuiHoveredFlags.DelayNormal, ImGuiHoveredFlags.AllowWhenDisabled), -- Default flags when using IsItemHovered(ImGuiHoveredFlags.ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad. -- [Internal] _MainScale = 1.0, _NextFrameFontSizeBase = 0.0 } + -- Default theme ImGui.StyleColorsDark(this) setmetatable(this, MT.ImGuiStyle) @@ -1404,6 +1552,7 @@ function ImGuiStyle() return this end +-- Storage for each window pushed into the stack. --- @class ImGuiWindowStackData --- @return ImGuiWindowStackData @@ -1412,12 +1561,13 @@ function ImGuiWindowStackData() return { Window = nil, ParentLastItemDataBackup = ImGuiLastItemData(), - StackSizesInBegin = nil, - DisabledOverrideReenable = nil, + StackSizesInBegin = nil, -- Store size of various stacks for asserting + DisabledOverrideReenable = nil, -- Non-child window override disabled flag DisabledOverrideReenableAlphaBackup = nil } end +-- Storage data for BeginComboPreview()/EndComboPreview() --- @class ImGuiComboPreviewData --- @field PreviewRect ImRect --- @field BackupCursorPos ImVec2 @@ -1443,10 +1593,12 @@ end --- @alias ImStbTexteditState STB_TexteditState +-- Internal state of the currently focused/edited text input box +-- For a given item ID, access with ImGui.GetInputTextState() --- @class ImGuiInputTextState --- @field Ctx ImGuiContext # parent UI context (needs to be set explicitly by parent) --- @field Stb ImStbTexteditState # State for stb_textedit.lua ---- @field Flags ImGuiInputTextFlags +--- @field Flags ImGuiInputTextFlags # copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags.Password is set. --- @field ID ImGuiID # widget id owning the text state --- @field TextLen int # UTF-8 length of the string in TextA (in bytes) --- @field TextSrc ImStringBuffer # == TextA.Data unless read-only, in which case == buf passed to InputText(). For _ReadOnly fields, pointer will be null outside the InputText() call @@ -1468,33 +1620,35 @@ MT.ImGuiInputTextState.__index = MT.ImGuiInputTextState local function ImGuiInputTextState() local this = { - Ctx = nil, - Stb = STB_TexteditState(), -- FIXME: no global! - Flags = 0, - ID = 0, + Ctx = nil, -- parent UI context (needs to be set explicitly by parent). + Stb = STB_TexteditState(), -- FIXME: no global! -- State for stb_textedit.h + Flags = 0, -- copy of InputText() flags. may be used to check if e.g. ImGuiInputTextFlags.Password is set. + ID = 0, -- widget id owning the text state - TextLen = 0, - TextSrc = nil, - TextA = ImVector(), - TextToRevertTo = ImVector(), - CallbackTextBackup = ImVector(), + TextLen = 0, -- UTF-8 length of the string in TextA (in bytes) + TextSrc = nil, -- == TextA.Data unless read-only, in which case == buf passed to InputText(). For _ReadOnly fields, pointer will be null outside the InputText() call. + TextA = ImVector(), -- main UTF8 buffer. TextA.Size is a buffer size! Should always be >= buf_size passed by user (and of course >= CurLenA + 1). + TextToRevertTo = ImVector(), -- value to revert to when pressing Escape = backup of end-user buffer at the time of focus (in UTF-8, unaltered) + CallbackTextBackup = ImVector(), -- temporary storage for callback to support automatic reconcile of undo-stack - BufCapacity = 0, - Scroll = ImVec2(), - LineCount = 0, - WrapWidth = 0.0, + BufCapacity = 0, -- end-user buffer capacity (include zero terminator) + Scroll = ImVec2(), -- horizontal offset (managed manually) + vertical scrolling (pulled from child window's own Scroll.y) + LineCount = 0, -- last line count (solely for debugging) + WrapWidth = 0.0, -- word-wrapping width - CursorAnim = 0.0, - CursorFollow = false, - CursorCenterY = false, - SelectedAllMouseLock = false, - EditedBefore = false, - EditedThisFrame = false, + CursorAnim = 0.0, -- timer for cursor blink, reset on every user action so the cursor reappears immediately + CursorFollow = false, -- set when we want scrolling to follow the current cursor position (not always!) + CursorCenterY = false, -- set when we want scrolling to be centered over the cursor position (while resizing a word-wrapping field) + SelectedAllMouseLock = false, -- after a double-click to select all, we ignore further mouse drags to update selection + EditedBefore = false, -- edited since activated + EditedThisFrame = false, -- edited this frame } return setmetatable(this, MT.ImGuiInputTextState) end +-- Internal temporary state for deactivating InputText() instances. +-- Store as part of ImGuiDeactivatedItemData? --- @class ImGuiInputTextDeactivatedState --- @field ID ImGuiID # widget id owning the text state (which just got deactivated) --- @field ElapseFrame int @@ -1512,19 +1666,20 @@ end --- @nodiscard local function ImGuiInputTextDeactivatedState() return setmetatable({ - ID = 0, + ID = 0, -- widget id owning the text state (which just got deactivated) ElapseFrame = 0, - TextA = ImVector() + TextA = ImVector() -- text buffer }, IMGUI_INPUT_TEXT_DEACTIVATED_STATE) end --- @alias ImGuiKeyRoutingIndex ImS16 +-- Routing table entry (sizeof() == 16 bytes) --- @class ImGuiKeyRoutingData --- @field NextEntryIndex ImGuiKeyRoutingIndex ---- @field Mods ImU16 ---- @field RoutingCurrScore ImU16 ---- @field RoutingNextScore ImU16 +--- @field Mods ImU16 # Technically we'd only need 4-bits but for simplify we store ImGuiMod_ values which need 16-bits. +--- @field RoutingCurrScore ImU16 # [DEBUG] For debug display +--- @field RoutingNextScore ImU16 # Lower is better (0: perfect score) --- @field RoutingCurr ImGuiID --- @field RoutingNext ImGuiID @@ -1533,18 +1688,20 @@ end function ImGuiKeyRoutingData() return { NextEntryIndex = -1, - Mods = 0, - RoutingCurrScore = 0, - RoutingNextScore = 0, + Mods = 0, -- Technically we'd only need 4-bits but for simplify we store ImGuiMod_ values which need 16-bits. + RoutingCurrScore = 0, -- [DEBUG] For debug display + RoutingNextScore = 0, -- Lower is better (0: perfect score) RoutingCurr = ImGuiKeyOwner_NoOwner, RoutingNext = ImGuiKeyOwner_NoOwner } end +-- Routing table: maintain a desired owner for each possible key-chord (key + mods), and setup owner in NewFrame() when mods are matching. +-- Stored in main context (1 instance) --- @class ImGuiKeyRoutingTable ---- @field Index ImGuiKeyRoutingIndex[] +--- @field Index ImGuiKeyRoutingIndex[] # Index of first entry in Entries[] --- @field Entries ImVector ---- @field EntriesNext ImVector +--- @field EntriesNext ImVector # Double-buffer to avoid reallocation (could use a shared buffer) local _ImGuiKeyRoutingTable = {} _ImGuiKeyRoutingTable.__index = _ImGuiKeyRoutingTable @@ -1557,9 +1714,9 @@ end --- @return ImGuiKeyRoutingTable local function ImGuiKeyRoutingTable() local this = setmetatable({ - Index = {}, + Index = {}, -- Index of first entry in Entries[] Entries = ImVector(), - EntriesNext = ImVector() + EntriesNext = ImVector() -- Double-buffer to avoid reallocation (could use a shared buffer) }, _ImGuiKeyRoutingTable) this:Clear() @@ -1567,9 +1724,11 @@ local function ImGuiKeyRoutingTable() return this end +-- Helper: ImGuiTextIndex +-- Maintain a line index for a text buffer. This is a strong candidate to be moved into the public API. --- @class ImGuiTextIndex --- @field Offsets ImVector ---- @field EndOffset int +--- @field EndOffset int # Because we don't own text buffer we need to maintain EndOffset (may bake in LineOffsets?) local IMGUI_TEXT_INDEX = {} IMGUI_TEXT_INDEX.__index = IMGUI_TEXT_INDEX @@ -1599,18 +1758,18 @@ local function ImGuiDebugAllocEntry() end --- @class ImGuiDebugAllocInfo ---- @field TotalAllocCount int +--- @field TotalAllocCount int # Number of call to MemAlloc(). --- @field TotalFreeCount int ---- @field LastEntriesIdx ImS16 ---- @field LastEntriesBuf ImGuiDebugAllocEntry[] +--- @field LastEntriesIdx ImS16 # Current index in buffer +--- @field LastEntriesBuf ImGuiDebugAllocEntry[] # Track last 6 frames that had allocations --- @return ImGuiDebugAllocInfo local function ImGuiDebugAllocInfo() local this = { - TotalAllocCount = 0, + TotalAllocCount = 0, -- Number of call to MemAlloc(). TotalFreeCount = 0, - LastEntriesIdx = 1, - LastEntriesBuf = {nil, nil, nil, nil, nil, nil}, + LastEntriesIdx = 1, -- Current index in buffer + LastEntriesBuf = {nil, nil, nil, nil, nil, nil}, -- Track last 6 frames that had allocations } for i = 1, 6 do @@ -1631,16 +1790,17 @@ local function ImGuiMetricsConfig() } end +-- Storage for navigation query/results --- @class ImGuiNavItemData ---- @field Window ImGuiWindow? ---- @field ID ImGuiID ---- @field FocusScopeId ImGuiID ---- @field RectRel ImRect ---- @field ItemFlags ImGuiItemFlags ---- @field SelectionUserData ImGuiSelectionUserData ---- @field DistBox float ---- @field DistCenter float ---- @field DistAxial float +--- @field Window ImGuiWindow? # Init,Move -- Best candidate window (result->ItemWindow->RootWindowForNav == request->Window) +--- @field ID ImGuiID # Init,Move -- Best candidate item ID +--- @field FocusScopeId ImGuiID # Init,Move -- Best candidate focus scope ID +--- @field RectRel ImRect # Init,Move -- Best candidate bounding box in window relative space +--- @field ItemFlags ImGuiItemFlags # ????,Move -- Best candidate item flags +--- @field SelectionUserData ImGuiSelectionUserData # I+Mov -- Best candidate SetNextItemSelectionUserData() value. Valid if (ItemFlags & ImGuiItemFlags.HasSelectionUserData) +--- @field DistBox float # Move -- Best candidate box distance to current NavId +--- @field DistCenter float # Move -- Best candidate center distance to current NavId +--- @field DistAxial float # Move -- Best candidate axial distance to current NavId local IMGUI_NAV_ITEM_DATA = {} IMGUI_NAV_ITEM_DATA.__index = IMGUI_NAV_ITEM_DATA @@ -1663,10 +1823,14 @@ local function ImGuiNavItemData() return this end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiContext (main Dear ImGui context) +------------------------------------------------------------------------------- + --- @class ImGuiContext --- @field Initialized bool ---- @field WithinFrameScope bool ---- @field WithinFrameScopeWithImplicitWindow bool +--- @field WithinFrameScope bool # Set by NewFrame(), cleared by EndFrame() +--- @field WithinFrameScopeWithImplicitWindow bool # Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed --- @field FrameCount int --- @field FrameCountEnded int --- @field CurrentWindow ImGuiWindow @@ -1726,49 +1890,54 @@ end --- @field DebugAllocInfo ImGuiDebugAllocInfo --- @field TempBuffer ImVector ----------------------------------------------------------------- --- [SECTION] Tab bar, Tab item support (public flags from imgui.h + private extensions) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Tab bar, Tab item support +-- PORT: public flags from imgui.h + private extensions +------------------------------------------------------------------------------- +-- Flags for ImGui.BeginTabBar() --- @enum ImGuiTabBarFlags ImGuiTabBarFlags = { None = 0, - Reorderable = bitLShift(1, 0), - AutoSelectNewTabs = bitLShift(1, 1), - TabListPopupButton = bitLShift(1, 2), - NoCloseWithMiddleMouseButton = bitLShift(1, 3), - NoTabListScrollingButtons = bitLShift(1, 4), - NoTooltip = bitLShift(1, 5), - DrawSelectedOverline = bitLShift(1, 6), - FittingPolicyMixed = bitLShift(1, 7), - FittingPolicyShrink = bitLShift(1, 8), - FittingPolicyScroll = bitLShift(1, 9), + Reorderable = bitLShift(1, 0), -- Allow manually dragging tabs to re-order them + New tabs are appended at the end of list + AutoSelectNewTabs = bitLShift(1, 1), -- Automatically select new tabs when they appear + TabListPopupButton = bitLShift(1, 2), -- Disable buttons to open the tab list popup + NoCloseWithMiddleMouseButton = bitLShift(1, 3), -- Disable behavior of closing tabs (that are submitted with p_open ~= nil) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) p_open = false. + NoTabListScrollingButtons = bitLShift(1, 4), -- Disable scrolling buttons (apply when fitting policy is ImGuiTabBarFlags.FittingPolicyScroll) + NoTooltip = bitLShift(1, 5), -- Disable tooltips when hovering a tab + DrawSelectedOverline = bitLShift(1, 6), -- Draw selected overline markers over selected tab + + -- Fitting/Resize policy + FittingPolicyMixed = bitLShift(1, 7), -- Shrink down tabs when they don't fit, until width is style.TabMinWidthShrink, then enable scrolling. Setting TabMinWidthShrink to FLT_MAX makes this behave like ImGuiTabBarFlags.FittingPolicyScroll. + FittingPolicyShrink = bitLShift(1, 8), -- Shrink down tabs when they don't fit + FittingPolicyScroll = bitLShift(1, 9), -- Enable scrolling buttons when tabs don't fit -- Private - DockNode = bitLShift(1, 20), + DockNode = bitLShift(1, 20), -- Part of a dock node [we don't use this in the master branch but it facilitate branch syncing to keep this around] IsFocused = bitLShift(1, 21), - SaveSettings = bitLShift(1, 22), + SaveSettings = bitLShift(1, 22), -- FIXME: Settings are handled by the docking system, this only request the tab bar to mark settings dirty when reordering tabs } ImGuiTabBarFlags.FittingPolicyMask_ = bitOr(ImGuiTabBarFlags.FittingPolicyMixed, ImGuiTabBarFlags.FittingPolicyShrink, ImGuiTabBarFlags.FittingPolicyScroll) ImGuiTabBarFlags.FittingPolicyDefault_ = ImGuiTabBarFlags.FittingPolicyMixed -ImGuiTabBarFlags.FittingPolicyResizeDown = ImGuiTabBarFlags.FittingPolicyShrink +ImGuiTabBarFlags.FittingPolicyResizeDown = ImGuiTabBarFlags.FittingPolicyShrink -- Renamed in 1.92.2 +-- Flags for ImGui.BeginTabItem() --- @enum ImGuiTabItemFlags ImGuiTabItemFlags = { None = 0, - UnsavedDocument = bitLShift(1, 0), - SetSelected = bitLShift(1, 1), - NoCloseWithMiddleMouseButton = bitLShift(1, 2), - NoPushId = bitLShift(1, 3), - NoTooltip = bitLShift(1, 4), - NoReorder = bitLShift(1, 5), - Leading = bitLShift(1, 6), - Trailing = bitLShift(1, 7), - NoAssumedClosure = bitLShift(1, 8), + UnsavedDocument = bitLShift(1, 0), -- Display a dot next to the title + set ImGuiTabItemFlags.NoAssumedClosure. + SetSelected = bitLShift(1, 1), -- Trigger flag to programmatically make the tab selected when calling BeginTabItem() + NoCloseWithMiddleMouseButton = bitLShift(1, 2), -- Disable behavior of closing tabs (that are submitted with p_open ~= nil) with middle mouse button. You may handle this behavior manually on user's side with if (IsItemHovered() && IsMouseClicked(2)) p_open = false. + NoPushId = bitLShift(1, 3), -- Don't call PushID()/PopID() on BeginTabItem()/EndTabItem() + NoTooltip = bitLShift(1, 4), -- Disable tooltip for the given tab + NoReorder = bitLShift(1, 5), -- Disable reordering this tab or having another tab cross over this tab + Leading = bitLShift(1, 6), -- Enforce the tab position to the left of the tab bar (after the tab list popup button) + Trailing = bitLShift(1, 7), -- Enforce the tab position to the right of the tab bar (before the scrolling buttons) + NoAssumedClosure = bitLShift(1, 8), -- Tab is selected when trying to close + closure is not immediately assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar. -- Private - NoCloseButton = bitLShift(1, 20), - Button = bitLShift(1, 21), - Invisible = bitLShift(1, 22), - Unsorted = bitLShift(1, 23), + NoCloseButton = bitLShift(1, 20), -- Track whether p_open was set or not (we'll need this info on the next frame to recompute ContentWidth during layout) + Button = bitLShift(1, 21), -- Used by TabItemButton, change the tab item behavior to mimic a button + Invisible = bitLShift(1, 22), -- To reserve space e.g. with ImGuiTabItemFlags.Leading + Unsorted = bitLShift(1, 23), -- [Docking] Trailing tabs with the _Unsorted flag will be sorted based on the DockOrder of their Window. } ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing) @@ -1777,13 +1946,17 @@ ImGuiTabItemFlags.SectionMask_ = bitOr(ImGuiTabItemFlags.Leading, ImGuiTabItemFl --- @return ImGuiTabItem function ImGuiTabItem() return { - ID = 0, Flags = 0, Window = nil, - LastFrameVisible = -1, LastFrameSelected = -1, + ID = 0, Flags = 0, Window = nil, -- Window: When TabItem is part of a DockNode's TabBar, we hold on to a window. + LastFrameVisible = -1, LastFrameSelected = -1, -- LastFrameSelected: This allows us to infer an ordered list of the last activated tabs with little maintenance + -- Offset: Position relative to beginning of tab bar + -- Width: Width currently displayed + -- ContentWidth: Width of label + padding, stored during BeginTabItem() call (misnamed as "Content" would normally imply width of label only) + -- RequestedWidth: Width optionally requested by caller, -1.0 is unused Offset = 0.0, Width = 0.0, ContentWidth = 0.0, RequestedWidth = -1.0, NameOffset = -1, Name = nil, - BeginOrder = -1, -- 0-based - IndexDuringLayout = -1, -- 0-based - WantClose = false, + BeginOrder = -1, -- 0-based -- BeginTabItem() order, used to re-order tabs after toggling ImGuiTabBarFlags.Reorderable + IndexDuringLayout = -1, -- 0-based -- Index only used during TabBarLayout(). Tabs gets reordered so 'Tabs[n].IndexDuringLayout == n' but may mismatch during additions. + WantClose = false, -- Marked as closed by SetTabItemClosed() } end @@ -1792,19 +1965,24 @@ end --- @return ImGuiTabBar function ImGuiTabBar() return { - Window = nil, Tabs = ImVector(), Flags = 0, ID = 0, + Window = nil, Tabs = ImVector(), Flags = 0, ID = 0, -- ID: Zero for tab-bars used by docking + -- SelectedTabId: Selected tab/window + -- NextSelectedTabId: Next selected tab/window. Will also trigger a scrolling animation + -- VisibleTabId: Can occasionally be != SelectedTabId (e.g. when previewing contents for Ctrl+Tab preview) SelectedTabId = 0, NextSelectedTabId = 0, NextScrollToTabId = 0, VisibleTabId = 0, CurrFrameVisible = -1, PrevFrameVisible = -1, - BarRect = ImRect(), BarRectPrevWidth = 0.0, - CurrTabsContentsHeight = 0.0, PrevTabsContentsHeight = 0.0, + BarRect = ImRect(), BarRectPrevWidth = 0.0, -- BarRectPrevWidth: Backup of previous width. When width change we enforce keep horizontal scroll on focused tab. + CurrTabsContentsHeight = 0.0, PrevTabsContentsHeight = 0.0, -- PrevTabsContentsHeight: Record the height of contents submitted below the tab bar + -- WidthAllTabs: Actual width of all tabs (locked during layout) + -- WidthAllTabsIdeal: Ideal width if all tabs were visible and not clipped WidthAllTabs = 0.0, WidthAllTabsIdeal = 0.0, ScrollingAnim = 0.0, ScrollingTarget = 0.0, ScrollingTargetDistToVisibility = 0.0, ScrollingSpeed = 0.0, ScrollingRectMinX = 0.0, ScrollingRectMaxX = 0.0, SeparatorMinX = 0.0, SeparatorMaxX = 0.0, ReorderRequestTabId = 0, ReorderRequestOffset = 0, BeginCount = 0, - WantLayout = false, VisibleTabWasSubmitted = false, TabsAddedNew = false, ScrollButtonEnabled = false, - TabsActiveCount = 0, - LastTabItemIdx = -1, -- 0-based - ItemSpacingY = 0.0, FramePadding = ImVec2(), BackupCursorPos = ImVec2(), + WantLayout = false, VisibleTabWasSubmitted = false, TabsAddedNew = false, ScrollButtonEnabled = false, -- TabsAddedNew: Set to true when a new tab item or button has been added to the tab bar during last frame + TabsActiveCount = 0, -- Number of tabs submitted this frame. + LastTabItemIdx = -1, -- 0-based -- Index of last BeginTabItem() tab for use by EndTabItem() + ItemSpacingY = 0.0, FramePadding = ImVec2(), BackupCursorPos = ImVec2(), -- FramePadding: style.FramePadding locked at the time of BeginTabBar() } end @@ -1817,86 +1995,86 @@ function ImGuiShrinkWidthItem() return { Index = 0, Width = 0.0, InitialWidth = function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this structure local this = { Style = ImGuiStyle(), - ColorStack = ImVector(), - StyleVarStack = ImVector(), + ColorStack = ImVector(), -- Stack for PushStyleColor()/PopStyleColor() - inherited by Begin() + StyleVarStack = ImVector(), -- Stack for PushStyleVar()/PopStyleVar() - inherited by Begin() Config = nil, Initialized = false, - WithinFrameScope = false, - WithinFrameScopeWithImplicitWindow = false, + WithinFrameScope = false, -- Set by NewFrame(), cleared by EndFrame() + WithinFrameScopeWithImplicitWindow = false, -- Set by NewFrame(), cleared by EndFrame() when the implicit debug window has been pushed Windows = ImVector(), -- Windows sorted in display order, back to front WindowsById = {}, -- Map window's ID to window ref - WindowsBorderHoverPadding = 0, + WindowsBorderHoverPadding = 0, -- 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. - WindowsActiveCount = 0, + WindowsActiveCount = 0, -- Number of unique windows submitted by frame - WindowsTempSortBuffer = ImVector(), + WindowsTempSortBuffer = ImVector(), -- Temporary buffer used in EndFrame() to reorder windows so parents are kept before their child CurrentWindowStack = ImVector(), - CurrentWindow = nil, + CurrentWindow = nil, -- Window being drawn into - WindowsFocusOrder = ImVector(), + WindowsFocusOrder = ImVector(), -- Root windows, sorted in focus order, back to front. IO = ImGuiIO(), PlatformIO = ImGuiPlatformIO(), - ConfigFlagsCurrFrame = ImGuiConfigFlags.None, + ConfigFlagsCurrFrame = ImGuiConfigFlags.None, -- = g.IO.ConfigFlags at the time of NewFrame() ConfigFlagsLastFrame = ImGuiConfigFlags.None, MouseLastValidPos = ImVec2(), - KeysMayBeCharInput = ImBitArray(ImGuiKey.NamedKey_COUNT, -ImGuiKey.NamedKey_BEGIN), + KeysMayBeCharInput = ImBitArray(ImGuiKey.NamedKey_COUNT, -ImGuiKey.NamedKey_BEGIN), -- Lookup to tell if a key can emit char input, see IsKeyChordPotentiallyCharInput(). KeysOwnerData = {}, -- size = ImGuiKey.NamedKey_COUNT KeysRoutingTable = ImGuiKeyRoutingTable(), - InputEventsQueue = ImVector(), + InputEventsQueue = ImVector(), -- Input events which will be trickled/written into IO structure. InputEventsNextMouseSource = ImGuiMouseSource.Mouse, InputEventsNextEventId = 1, - MovingWindow = nil, + MovingWindow = nil, -- Track the window we clicked on (in order to preserve focus). The actual window that is moved is generally MovingWindow.RootWindowDockTree. - WheelingWindow = nil, - WheelingWindowStartFrame = -1, WheelingWindowScrolledFrame = -1, + WheelingWindow = nil, -- Track the window we started mouse-wheeling on. Until a timer elapse or mouse has moved, generally keep scrolling the same window even if during the course of scrolling the mouse ends up hovering a child window. + WheelingWindowStartFrame = -1, WheelingWindowScrolledFrame = -1, -- This may be set one frame before WheelingWindow is ~= nil WheelingWindowReleaseTimer = 0.0, WheelingWindowRefMousePos = ImVec2(), WheelingWindowWheelRemainder = ImVec2(), WheelingAxisAvg = ImVec2(), - ActiveIdClickOffset = ImVec2(), + ActiveIdClickOffset = ImVec2(), -- Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) - HoveredWindow = nil, - HoveredWindowUnderMovingWindow = nil, - HoveredIdIsDisabled = false, + HoveredWindow = nil, -- Window the mouse is hovering. Will typically catch mouse inputs. + HoveredWindowUnderMovingWindow = nil, -- Hovered window ignoring MovingWindow. Only set if MovingWindow is set. + HoveredIdIsDisabled = false, -- At least one widget passed the rect test, but has been discarded by disabled flag or popup inhibit. May be true even if HoveredId == 0. ActiveIdFromShortcut = false, AnyIdHasBeenEditedThisFrame = false, - ActiveId = 0, + ActiveId = 0, -- Active widget ActiveIdWindow = nil, ActiveIdMouseButton = -1, - ActiveIdIsJustActivated = false, + ActiveIdIsJustActivated = false, -- Set at the time of activation for one frame - ActiveIdWasSelected = false, ActiveIdWasSoleSelected = false, + ActiveIdWasSelected = false, ActiveIdWasSoleSelected = false, -- Active ID was selected at the time of activating LastActiveIdWasSelected = false, LastActiveIdWasSoleSelected = false, - ActiveIdNoClearOnFocusLoss = false, - ActiveIdHasBeenPressedBefore = false, + ActiveIdNoClearOnFocusLoss = false, -- Disable losing active id if the active id window gets unfocused. + ActiveIdHasBeenPressedBefore = false, -- Track whether the active id led to a press (this is to allow changing between PressOnClick and PressOnRelease without pressing twice). Used by range_select branch. - ActiveIdIsAlive = nil, + ActiveIdIsAlive = nil, -- Active widget has been seen this frame (we can't use a bool as the ActiveId may change within the frame) ActiveIdPreviousFrame = 0, ActiveIdTimer = 0.0, - LastActiveId = 0, - LastActiveIdTimer = 0.0, + LastActiveId = 0, -- Store the last non-zero ActiveId, useful for animation. + LastActiveIdTimer = 0.0, -- Store the last non-zero ActiveId timer since the beginning of activation, useful for animation. - ActiveIdUsingNavDirMask = 0x00, - ActiveIdUsingAllKeyboardKeys = false, + ActiveIdUsingNavDirMask = 0x00, -- Active widget will want to read those nav move requests (e.g. can activate a button and move away from it) + ActiveIdUsingAllKeyboardKeys = false, -- Active widget will want to read all keyboard keys inputs. (this is a shortcut for not taking ownership of 100+ keys, frequently used by drag operations) DeactivatedItemData = { ID = 0, @@ -1905,64 +2083,64 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct IsAlive = false }, - HoveredId = 0, - HoveredIdTimer = 0.0, - HoveredIdNotActiveTimer = 0.0, + HoveredId = 0, -- Hovered widget, filled during the frame + HoveredIdTimer = 0.0, -- Measure contiguous hovering time + HoveredIdNotActiveTimer = 0.0, -- Measure contiguous hovering time where the item has not been active HoveredIdAllowOverlap = false, HoverItemDelayId = 0, HoverItemDelayIdPreviousFrame = 0, HoverItemUnlockedStationaryId = 0, HoverWindowUnlockedStationaryId = 0, - HoverItemDelayTimer = 0.0, HoverItemDelayClearTimer = 0.0, + HoverItemDelayTimer = 0.0, HoverItemDelayClearTimer = 0.0, -- Currently used by IsItemHovered() - ActiveIdAllowOverlap = false, + ActiveIdAllowOverlap = false, -- Active widget allows another widget to steal active id (generally for overlapping widgets, but not always) - NavLayer = ImGuiNavLayer.Main, - NavId = 0, + NavLayer = ImGuiNavLayer.Main, -- Focused layer (main scrolling layer, or menu/title bar layer) + NavId = 0, -- Focused item for navigation NavOpenContextMenuItemId = 0, NavOpenContextMenuWindowId = 0, - NavWindow = nil, + NavWindow = nil, -- Focused window for navigation. Could be called 'FocusedWindow' NavHighlightActivatedId = 0, NavHighlightActivatedTimer = 0.0, - NavCursorVisible = false, + NavCursorVisible = false, -- Nav focus cursor/rectangle is visible? We hide it after a mouse click. We show it after a nav move. NavCursorHideFrames = 0, - NavHighlightItemUnderNav = false, - NavIdIsAlive = false, - NavInputSource = ImGuiInputSource.Keyboard, - NavWindowingTarget = nil, NavWindowingTargetAnim = nil, NavWindowingListWindow = nil, + NavHighlightItemUnderNav = false, -- Disable mouse hovering highlight. Highlight navigation focused item instead of mouse hovered item. + NavIdIsAlive = false, -- Nav widget has been seen this frame ~~ NavRectRel is valid + NavInputSource = ImGuiInputSource.Keyboard, -- Keyboard or Gamepad mode? THIS CAN ONLY BE ImGuiInputSource.Keyboard or ImGuiInputSource.Gamepad + NavWindowingTarget = nil, NavWindowingTargetAnim = nil, NavWindowingListWindow = nil, -- Target window when doing Ctrl+Tab (or Pad Menu + FocusPrev/Next), this window is temporarily displayed top-most! NavWindowingTimer = 0.0, NavWindowingHighlightAlpha = 0.0, - NavWindowingToggleLayer = false, - NavWindowingToggleKey = ImGuiKey.None, + NavWindowingToggleLayer = false, -- Set while Alt or GamepadMenu is held, may be cleared by other operations, and processed when releasing the key. + NavWindowingToggleKey = ImGuiKey.None, -- Keyboard/gamepad key used when toggling to menu layer. NavWindowingInputSource = ImGuiInputSource.None, NavWindowingAccumDeltaPos = ImVec2(0.0, 0.0), NavWindowingAccumDeltaSize = ImVec2(0.0, 0.0), - DimBgRatio = 0.0, - LastKeyboardKeyPressTime = -1.0, LastKeyModsChangeTime = -1.0, LastKeyModsChangeFromNoneTime = -1.0, - ConfigNavWindowingKeyNext = bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Tab), - ConfigNavWindowingKeyPrev = bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Tab), - ConfigNavWindowingWithGamepad = true, + DimBgRatio = 0.0, -- 0.0..1.0 animation when fading in a dimming background (for modal window and Ctrl+Tab list) + LastKeyboardKeyPressTime = -1.0, LastKeyModsChangeTime = -1.0, LastKeyModsChangeFromNoneTime = -1.0, -- Record the last time a keyboard key (ignore mouse/gamepad ones) was pressed. + ConfigNavWindowingKeyNext = bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Tab), -- = ImGuiMod_Ctrl | ImGuiKey.Tab (or ImGuiMod_Super | ImGuiKey.Tab on OS X). Set to 0 to disable. For reconfiguration (see #4828) + ConfigNavWindowingKeyPrev = bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Tab), -- = ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey.Tab (or ImGuiMod_Super | ImGuiMod_Shift | ImGuiKey.Tab on OS X) + ConfigNavWindowingWithGamepad = true, -- = true. Enable Ctrl+Tab by holding ImGuiKey.GamepadFaceLeft (== ImGuiKey.NavGamepadMenu). When false, the button may still be used to toggle Menu layer. - NavFocusRoute = ImVector(), + NavFocusRoute = ImVector(), -- Reversed copy focus scope stack for NavId (should contains NavFocusScopeId). This essentially follow the window.ParentWindowForFocusRoute chain. - NavAnyRequest = false, - NavInitRequest = false, + NavAnyRequest = false, -- ~~ NavMoveRequest || NavInitRequest this is to perform early out in ItemAdd() + NavInitRequest = false, -- Init request for appearing window to select first item NavInitRequestFromMove = false, - NavInitResult = ImGuiNavItemData(), - NavMoveSubmitted = false, - NavMoveScoringItems = false, + NavInitResult = ImGuiNavItemData(), -- Init request result (first item of the window, or one for which SetItemDefaultFocus() was called) + NavMoveSubmitted = false, -- Move request submitted, will process result on next NewFrame() + NavMoveScoringItems = false, -- Move request submitted, still scoring incoming items NavMoveForwardToNextFrame = false, NavMoveFlags = ImGuiNavMoveFlags.None, NavMoveScrollFlags = ImGuiScrollFlags.None, NavMoveKeyMods = ImGuiMod_None, - NavMoveDir = ImGuiDir.None, NavMoveDirForDebug = ImGuiDir.None, NavMoveClipDir = ImGuiDir.None, - NavMoveResultLocal = ImGuiNavItemData(), - NavMoveResultOther = ImGuiNavItemData(), - NavMoveResultLocalVisible = ImGuiNavItemData(), - NavTabbingResultFirst = ImGuiNavItemData(), - NavScoringRect = ImRect(), - NavScoringNoClipRect = ImRect(), - ConfigNavEnableTabbing = true, - NavTabbingCounter = 0, - NavTabbingDir = 0, - NavNextActivateId = 0, + NavMoveDir = ImGuiDir.None, NavMoveDirForDebug = ImGuiDir.None, NavMoveClipDir = ImGuiDir.None, -- Direction of the move request (left/right/up/down) + NavMoveResultLocal = ImGuiNavItemData(), -- Best move request candidate within NavWindow + NavMoveResultOther = ImGuiNavItemData(), -- Best move request candidate within NavWindow's flattened hierarchy (when using ImGuiWindowFlags.NavFlattened flag) + NavMoveResultLocalVisible = ImGuiNavItemData(), -- Best move request candidate within NavWindow that are mostly visible (when using ImGuiNavMoveFlags.AlsoScoreVisibleSet flag) + NavTabbingResultFirst = ImGuiNavItemData(), -- First tabbing request candidate within NavWindow and flattened hierarchy + NavScoringRect = ImRect(), -- Rectangle used for scoring, in screen space. Based of window.NavRectRel[], modified for directional navigation scoring. + NavScoringNoClipRect = ImRect(), -- Some nav operations (such as PageUp/PageDown) enforce a region which clipper will attempt to always keep submitted. Unset/invalid if inverted. + ConfigNavEnableTabbing = true, -- = true. Enable tabbing (Tab, Shift+Tab). PLEASE LET ME KNOW IF YOU USE THIS. + NavTabbingCounter = 0, -- >0 when counting items for tabbing + NavTabbingDir = 0, -- Generally -1 or +1, 0 when tabbing without a nav id + NavNextActivateId = 0, -- Set by ActivateItemByID(), queued until next frame. NavNextActivateFlags = ImGuiActivateFlags.None, - NavActivateId = 0, NavActivateDownId = 0, NavActivatePressedId = 0, + NavActivateId = 0, NavActivateDownId = 0, NavActivatePressedId = 0, -- ~~ (g.ActiveId == 0) && (IsKeyPressed(ImGuiKey.Space) || IsKeyDown(ImGuiKey.Enter) || IsKeyPressed(ImGuiKey.NavGamepadActivate)) ? NavId : 0, also set when calling ActivateItemByID() NavActivateFlags = ImGuiActivateFlags.None, FrameCount = -1, @@ -1973,67 +2151,67 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct Time = 0, - NextItemData = ImGuiNextItemData(), - LastItemData = ImGuiLastItemData(), - NextWindowData = ImGuiNextWindowData(), + NextItemData = ImGuiNextItemData(), -- Storage for SetNextItem** functions + LastItemData = ImGuiLastItemData(), -- Storage for last submitted item (setup by ItemAdd) + NextWindowData = ImGuiNextWindowData(), -- Storage for SetNextWindow** functions - Viewports = ImVector(), + Viewports = ImVector(), -- Active viewports (always 1+, and generally 1 unless multi-viewports are enabled). Each viewports hold their copy of ImDrawData. - FallbackMonitor = nil, + FallbackMonitor = nil, -- Virtual monitor used as fallback if backend doesn't provide monitor information. - GcCompactAll = false, + GcCompactAll = false, -- Request full GC CurrentViewport = nil, MouseViewport = nil, MouseLastHoveredViewport = nil, PlatformLastFocusedViewportId = 1, - ViewportCreatedCount = 0, PlatformWindowsCreatedCount = 0, - ViewportFocusedStampCount = 0, + ViewportCreatedCount = 0, PlatformWindowsCreatedCount = 0, -- Unique sequential creation counter (mostly for testing/debugging) + ViewportFocusedStampCount = 0, -- Every time the front-most window changes, we stamp its viewport with an incrementing counter - Font = nil, - FontSize = 0.0, - FontSizeBase = 0.0, - CurrentDpiScale = 0.0, + Font = nil, -- Currently bound font. (== FontStack.back().Font) + FontSize = 0.0, -- Currently bound font size == line height (== FontSizeBase + externals scales applied in the UpdateCurrentFontSize() function). + FontSizeBase = 0.0, -- Font size before scaling == style.FontSizeBase == value passed to PushFont() when specified. + CurrentDpiScale = 0.0, -- Current window/viewport DpiScale == CurrentViewport.DpiScale FontRefSize = 0.0, FontRasterizerDensity = 1.0, - FontAtlases = ImVector(), + FontAtlases = ImVector(), -- List of font atlases used by the context (generally only contains g.IO.Fonts aka the main font atlas) - FontStack = ImVector(), + FontStack = ImVector(), -- Stack for PushFont()/PopFont() - inherited by Begin() - OpenPopupStack = ImVector(), - BeginPopupStack = ImVector(), + OpenPopupStack = ImVector(), -- Which popups are open (persistent) + BeginPopupStack = ImVector(), -- Which level of BeginPopup() we are in (reset every frame) TreeNodeStack = ImVector(ImGuiTreeNodeStackData), - WithinEndChildID = 0, WithinEndPopupID = 0, + WithinEndChildID = 0, WithinEndPopupID = 0, -- Set within EndChild() BeginMenuDepth = 0, BeginComboDepth = 0, - ColorEditCurrentID = 0, ColorEditSavedID = 0, - ColorEditSavedHue = 0.0, ColorEditSavedSat = 0.0, - ColorEditSavedColor = 0, - ColorPickerRef = ImVec4(), + ColorEditCurrentID = 0, ColorEditSavedID = 0, -- Set temporarily while inside of the parent-most ColorEdit4/ColorPicker4 (because they call each others). + ColorEditSavedHue = 0.0, ColorEditSavedSat = 0.0, -- Backup of last Hue associated to LastColor, so we can restore Hue in lossy RGB<>HSV round trips + ColorEditSavedColor = 0, -- RGB value with alpha set to 0. + ColorPickerRef = ImVec4(), -- Initial/reference color at the time of opening the color picker. - MenusIdSubmittedThisFrame = ImVector(), + MenusIdSubmittedThisFrame = ImVector(), -- A list of menu IDs that were rendered at least once DrawListSharedData = ImDrawListSharedData(), StackSizesInBeginForCurrentWindow = nil, MouseCursor = ImGuiMouseCursor.Arrow, - MouseStationaryTimer = 0.0, + MouseStationaryTimer = 0.0, -- Time the mouse has been stationary (with some loose heuristic) InputTextState = ImGuiInputTextState(), - InputTextLineIndex = ImGuiTextIndex(), + InputTextLineIndex = ImGuiTextIndex(), -- Temporary storage InputTextDeactivatedState = ImGuiInputTextDeactivatedState(), InputTextPasswordFontBackupBaked = ImFontBaked(), - InputTextReactivateId = 0, - TempInputId = 0, + InputTextReactivateId = 0, -- ID of InputText to reactivate on next frame (for io.ConfigInputTextEnterKeepActive behavior) + TempInputId = 0, -- Temporary text input when using Ctrl+Click on a slider, etc. - ActiveIdValueOnActivation = 0, - DataTypeZeroValue = 0, + ActiveIdValueOnActivation = 0, -- Backup of initial value at the time of activation. ONLY SET BY SPECIFIC WIDGETS: DragXXX and SliderXXX. + DataTypeZeroValue = 0, -- 0 for all data types ComboPreviewData = ImGuiComboPreviewData(), @@ -2042,97 +2220,97 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct -- Docking DockContext = ImGuiDockContext(), DockNodeWindowMenuHandler = nil, - DebugHoveredDockNode = nil, + DebugHoveredDockNode = nil, -- Hovered dock node. CurrentTabBarStack = ImVector(), -- holds ImGuiTabBar references directly (no ImGuiPtrOrIndex needed in Lua) ShrinkWidthBuffer = ImVector(), -- ImGuiShrinkWidthItem - WindowResizeBorderExpectedRect = ImRect(), + WindowResizeBorderExpectedRect = ImRect(), -- Expected border rect, switch to relative edit if moving WindowResizeRelativeMode = false, - ScrollbarSeekMode = 0, - ScrollbarClickDeltaToGrabCenter = 0.0, + ScrollbarSeekMode = 0, -- 0: scroll to clicked location, -1/+1: prev/next page. + ScrollbarClickDeltaToGrabCenter = 0.0, -- When scrolling to mouse location: distance between mouse and center of grab box, normalized in parent space. SliderGrabClickOffset = 0.0, - SliderCurrentAccum = 0.0, - SliderCurrentAccumDirty = false, + SliderCurrentAccum = 0.0, -- Accumulated slider delta when using navigation controls. + SliderCurrentAccumDirty = false, -- Has the accumulated slider delta changed since last time we tried to apply it? DragCurrentAccumDirty = false, - DragCurrentAccum = 0.0, - DragSpeedDefaultRatio = 1.0 / 100.0, + DragCurrentAccum = 0.0, -- Accumulator for dragging modification. Always high-precision, not rounded by end-user precision settings + DragSpeedDefaultRatio = 1.0 / 100.0, -- If speed == 0.0, uses (max-min) * DragSpeedDefaultRatio TooltipOverrideCount = 0, - TooltipPreviousWindow = nil, + TooltipPreviousWindow = nil, -- Window of last tooltip submitted during the frame - FocusScopeStack = ImVector(), - CurrentFocusScopeId = 0, - CurrentItemFlags = ImGuiItemFlags.None, + FocusScopeStack = ImVector(), -- Stack for PushFocusScope()/PopFocusScope() - inherited by BeginChild(), pushed into by Begin() + CurrentFocusScopeId = 0, -- Value for currently appending items == g.FocusScopeStack.back(). Not to be mistaken with g.NavFocusScopeId. + CurrentItemFlags = ImGuiItemFlags.None, -- Value for currently appending items == g.ItemFlagsStack.back() - DisabledAlphaBackup = 0.0, + DisabledAlphaBackup = 0.0, -- Backup for style.Alpha for BeginDisabled() DisabledStackSize = 0, - ItemFlagsStack = ImVector(), - GroupStack = ImVector(), + ItemFlagsStack = ImVector(), -- Stack for PushItemFlag()/PopItemFlag() - inherited by Begin() + GroupStack = ImVector(), -- Stack for BeginGroup()/EndGroup() - not inherited by Begin() - PlatformImeData = ImGuiPlatformImeData(), - PlatformImeDataPrev = ImGuiPlatformImeData(), + PlatformImeData = ImGuiPlatformImeData(), -- 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. + PlatformImeDataPrev = ImGuiPlatformImeData(), -- Previous frame data. When changed we call the platform_io.Platform_SetImeDataFn() handler. -- Extensions - UserTextures = ImVector(), + UserTextures = ImVector(), -- List of textures created/managed by user or third-party extension. Automatically appended into platform_io.Textures[]. -- Settings SettingsLoaded = false, - SettingsDirtyTimer = 0.0, + SettingsDirtyTimer = 0.0, -- Save .ini Settings to memory when time reaches zero SettingsIniData = "", -- In memory .ini settings (string) SettingsHandlers = ImVector(), -- List of .ini settings handlers - SettingsWindows = ImVector(), - SettingsTables = ImVector(), + SettingsWindows = ImVector(), -- ImGuiWindow .ini settings entries + SettingsTables = ImVector(), -- ImGuiTable .ini settings entries -- Hooks - Hooks = ImVector(), - HookIdNext = 0, + Hooks = ImVector(), -- Hooks for extensions (e.g. test engine) + HookIdNext = 0, -- Next available HookId -- Drag and Drop DragDropActive = false, - DragDropWithinSource = false, - DragDropWithinTarget = false, + DragDropWithinSource = false, -- Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag source. + DragDropWithinTarget = false, -- Set when within a BeginDragDropXXX/EndDragDropXXX block for a drag target. DragDropSourceFlags = 0, DragDropSourceFrameCount = -1, DragDropMouseButton = -1, DragDropPayload = ImGuiPayload(), - DragDropTargetRect = ImRect(), - DragDropTargetClipRect = ImRect(), + DragDropTargetRect = ImRect(), -- Store rectangle of current target candidate (we favor small targets when overlapping) + DragDropTargetClipRect = ImRect(), -- Store ClipRect at the time of item's drawing DragDropTargetId = 0, DragDropTargetFullViewport = 0, DragDropAcceptFlagsCurr = 0, DragDropAcceptFlagsPrev = 0, - DragDropAcceptIdCurrRectSurface = 0.0, - DragDropAcceptFrameCount = -1, - DragDropHoldJustPressedId = 0, + DragDropAcceptIdCurrRectSurface = 0.0, -- Target item surface (we resolve overlapping targets by prioritizing the smaller surface) + DragDropAcceptFrameCount = -1, -- Last time a target expressed a desire to accept the source + DragDropHoldJustPressedId = 0, -- Set when holding a payload just made ButtonBehavior() return a press. - DragDropAcceptIdPrev = 0, DragDropAcceptIdCurr = 0, + DragDropAcceptIdPrev = 0, DragDropAcceptIdCurr = 0, -- Target item id from previous frame (we need to store this to allow for overlapping drag and drop targets) -- Clipper ClipperTempDataStacked = 0, ClipperTempData = ImVector(), -- Logging - LogEnabled = false, + LogEnabled = false, -- Currently capturing LogLineFirstItem = false, - LogFlags = 0, + LogFlags = 0, -- Capture flags/type LogWindow = nil, - LogFile = nil, - LogBuffer = ImGuiTextBuffer(), - LogNextPrefix = nil, LogNextSuffix = nil, + LogFile = nil, -- If ~= nil log to stdout/ file + LogBuffer = ImGuiTextBuffer(), -- Accumulation buffer when log to clipboard. + LogNextPrefix = nil, LogNextSuffix = nil, -- See comment in LogSetNextTextDecoration(): doesn't copy underlying data, use carefully! LogLinePosY = FLT_MAX, LogDepthRef = 0, LogDepthToExpand = 2, LogDepthToExpandDefault = 2, -- Error handling - ErrorCallback = nil, ErrorCallbackUserData = nil, + ErrorCallback = nil, ErrorCallbackUserData = nil, -- = nil. May be exposed in public API eventually. ErrorTooltipLockedPos = ImVec2(), ErrorFirst = true, - ErrorCountCurrentFrame = 0, - StackSizesInNewFrame = nil, - ContextName = "", - DebugBreakInWindow = 0, + ErrorCountCurrentFrame = 0, -- [Internal] Number of errors submitted this frame. + StackSizesInNewFrame = nil, -- [Internal] + ContextName = "", -- Storage for a context name (to facilitate debugging multi-context setups) + DebugBreakInWindow = 0, -- Set to break in Begin() call. LocalizationTable = {}, @@ -2140,7 +2318,7 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct DebugFlashStyleColorIdx = nil, DebugMetricsConfig = ImGuiMetricsConfig(), - DebugHookIdInfoId = 0, + DebugHookIdInfoId = 0, -- Will call core hooks: DebugHookIdInfo() from GetID functions, used by ID Stack Tool DebugAllocInfo = ImGuiDebugAllocInfo(), --- Misc @@ -2149,16 +2327,16 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct FramerateSecPerFrameCount = 0, FramerateSecPerFrameAccum = 0, - WantCaptureMouseNextFrame = -1, - WantCaptureKeyboardNextFrame = -1, - WantTextInputNextFrame = -1, - TempBuffer = ImVector(), + WantCaptureMouseNextFrame = -1, -- Explicit capture override via SetNextFrameWantCaptureMouse()/SetNextFrameWantCaptureKeyboard(). Default to -1. + WantCaptureKeyboardNextFrame = -1, -- " + WantTextInputNextFrame = -1, -- Copied in EndFrame() from g.PlatformImeData.WantTextInput. Needs to be set for some backends (SDL3) to emit character inputs. + TempBuffer = ImVector(), -- Temporary text buffer -- Tables (imgui_tables.lua) CurrentTable = nil, - DebugBreakInTable = 0, - TablesTempDataStacked = 0, - TablesTempData = ImVector(), + DebugBreakInTable = 0, -- Set to break in BeginTable() call. + TablesTempDataStacked = 0, -- Temporary table data size (because we leave previous instances undestructed, we generally don't use TablesTempData.Size) + TablesTempData = ImVector(), -- Temporary table data (buffers reused/shared across instances, support nesting) Tables = ImPool(), -- ImPool, 0-based indices (imgui_tables.lua) TablesLastTimeActive = ImVector(), -- [table_idx + 1] = float DrawChannelsTempMergeBuffer = ImVector(), @@ -2184,6 +2362,11 @@ function ImGuiContext(shared_font_atlas) -- TODO: tidy up / complete this struct return this end +------------------------------------------------------------------------------- +-- [SECTION] Settings support +------------------------------------------------------------------------------- + +-- Windows data saved in imgui.ini file --- @class ImGuiWindowSettings --- @field ID int # Window ID --- @field Pos ImVec2 # Window position @@ -2203,22 +2386,23 @@ end function ImGuiWindowSettings() return setmetatable({ ID = 0, - Pos = ImVec2(0, 0), + Pos = ImVec2(0, 0), -- NB: Settings position are stored RELATIVE to the viewport! Whereas runtime ones are absolute positions. Size = ImVec2(0, 0), Collapsed = false, IsChild = false, - WantApply = false, - WantDelete = false, + WantApply = false, -- Set when loaded from .ini data (to enable merging/loading .ini data into an already running context) + WantDelete = false, -- Set to invalidate/delete the settings entry Name = "", ViewportId = 0, ViewportPos = ImVec2(0, 0), - DockId = 0, - DockOrder = -1, - ClassId = 0, + DockId = 0, -- ID of last known DockNode (even if the DockNode is invisible because it has only 1 active window), or 0 if none. + DockOrder = -1, -- Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. + ClassId = 0, -- ID of window class if specified LastUsedDate = 0, }, IMGUI_WINDOW_SETTINGS) end +-- Simple column measurement, currently used for MenuItem() only.. This is very short-sighted/throw-away code and NOT a generic helper. --- @class ImGuiMenuColumns --- @field TotalWidth ImU32 --- @field NextTotalWidth ImU32 @@ -2237,14 +2421,20 @@ local function ImGuiMenuColumns() TotalWidth = 0, NextTotalWidth = 0, Spacing = 0, - OffsetIcon = 0, - OffsetLabel = 0, + OffsetIcon = 0, -- Always zero for now + OffsetLabel = 0, -- Offsets are locked in Update() OffsetShortcut = 0, OffsetMark = 0, - Widths = {0, 0, 0, 0} + Widths = {0, 0, 0, 0} -- Width of: Icon, Label, Shortcut, Mark (accumulators for current frame) }, MT.ImGuiMenuColumns) end +------------------------------------------------------------------------------- +-- [SECTION] ImGuiWindowTempData, ImGuiWindow +------------------------------------------------------------------------------- + +-- Transient per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the DC variable name in ImGuiWindow. +-- (That's theory, in practice the delimitation between ImGuiWindow and ImGuiWindowTempData is quite tenuous and could be reconsidered..) --- @class ImGuiWindowTempData --- @field CursorPos ImVec2 --- @field CursorPosPrevLine ImVec2 @@ -2278,48 +2468,49 @@ local function ImGuiWindowTempData() return { DockTabItemStatusFlags = 0, DockTabItemRect = ImRect(), - CursorPos = ImVec2(), + CursorPos = ImVec2(), -- Current emitting position, in absolute coordinates. CursorPosPrevLine = ImVec2(), - CursorStartPos = ImVec2(), - CursorMaxPos = ImVec2(), - IdealMaxPos = ImVec2(), + CursorStartPos = ImVec2(), -- Initial position after Begin(), generally ~ window position + WindowPadding. + CursorMaxPos = ImVec2(), -- Used to implicitly calculate ContentSize at the beginning of next frame, for scrolling range and auto-resize. Always growing during the frame. + IdealMaxPos = ImVec2(), -- Used to implicitly calculate ContentSizeIdeal at the beginning of next frame, for auto-resize only. Always growing during the frame. CurrLineSize = ImVec2(), PrevLineSize = ImVec2(), - CurrLineTextBaseOffset = 0, + CurrLineTextBaseOffset = 0, -- Baseline offset (0.0 by default on a new line, generally == style.FramePadding.y when a framed item has been added). PrevLineTextBaseOffset = 0, IsSameLine = false, IsSetPos = false, - NavLayersActiveMask = 0, NavLayersActiveMaskNext = 0, + NavLayersActiveMask = 0, NavLayersActiveMaskNext = 0, -- Which layers have been written to (result from previous frame) - Indent = ImVec1(), - ColumnsOffset = ImVec1(), + Indent = ImVec1(), -- Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + ColumnsOffset = ImVec1(), -- Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree.Column.Tree. Need revamp columns API. GroupOffset = ImVec1(), - CursorStartPosLossyness = ImVec2(), + CursorStartPosLossyness = ImVec2(), -- Record the loss of precision of CursorStartPos due to really large scrolling amount. This is used by clipper to compensate and fix the most common use case of large scroll area. - ItemWidth = 0, + ItemWidth = 0, -- Current item width (>0.0: width in pixels, <0.0: align xx pixels to the right of window). ItemWidthDefault = 0, - TextWrapPos = 0, - ItemWidthStack = ImVector(), - TextWrapPosStack = ImVector(), + TextWrapPos = 0, -- Current text wrap pos. + ItemWidthStack = ImVector(), -- Store item widths to restore (attention: .back() is not == ItemWidth) + TextWrapPosStack = ImVector(), -- Store text wrap pos to restore (attention: .back() is not == TextWrapPos) MenuBarAppending = false, -- FIXME: Remove this - MenuBarOffset = ImVec2(), - MenuColumns = ImGuiMenuColumns(), - TreeDepth = 0, - TreeHasStackDataDepthMask = nil, - TreeRecordsClippedNodesY2Mask = nil, + MenuBarOffset = ImVec2(), -- 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. + MenuColumns = ImGuiMenuColumns(), -- Simplified columns storage for menu items measurement + TreeDepth = 0, -- Current tree depth. + TreeHasStackDataDepthMask = nil, -- Store whether given depth has ImGuiTreeNodeStackData data. Could be turned into a ImU64 if necessary. Sync any changes with TREE_NODE_MAX_DEPTH/TREE_NODE_GET_DEPTH_MASK! + TreeRecordsClippedNodesY2Mask = nil, -- Store whether we should keep recording Y2. Cleared when passing clip max. Equivalent TreeHasStackDataDepthMask value should always be set. ChildWindows = ImVector(), CurrentTableIdx = -1, -- 0-based index into g.Tables, -1 if none CurrentColumns = nil, -- ImGuiOldColumns (legacy Columns API) - StateStorage = nil, + StateStorage = nil, -- Current persistent per-window storage (store e.g. tree node open/close state) LayoutType = nil } end +-- Storage for one window --- @class ImGuiWindow --- @field Ctx ImGuiContext --- @field Name string @@ -2363,6 +2554,7 @@ end MT.ImGuiWindow = {} MT.ImGuiWindow.__index = MT.ImGuiWindow +-- We don't use g.FontSize because the window may be != g.CurrentWindow. --- @return ImRect --- @nodiscard function MT.ImGuiWindow:Rect() @@ -2386,58 +2578,58 @@ end --- @nodiscard function ImGuiWindow(ctx, name) local this = { - ID = 0, + ID = 0, -- == ImHashStr(Name) - MoveId = 0, + MoveId = 0, -- == window.GetID("#MOVE") - Ctx = ctx, - Name = name, + Ctx = ctx, -- Parent UI context (needs to be set explicitly by parent). + Name = name, -- Window name Flags = 0, - ChildFlags = 0, - WindowClass = ImGuiWindowClass(), + ChildFlags = 0, -- Set when window is a child window. See enum ImGuiChildFlags + WindowClass = ImGuiWindowClass(), -- Advanced users only. Set with SetNextWindowClass() - Pos = ImVec2(), + Pos = ImVec2(), -- Position (always rounded-up to nearest pixel) Size = ImVec2(), -- Current size (==SizeFull or collapsed title bar size) - SizeFull = ImVec2(), + SizeFull = ImVec2(), -- Size when non collapsed - Active = false, + Active = false, -- Set to true on Begin(), unless Collapsed WasActive = false, - Collapsed = false, + Collapsed = false, -- Set when collapsing window to become only title-bar - SkipItems = false, + SkipItems = false, -- Set when items can safely be all clipped (e.g. window not visible or collapsed) - SkipRefresh = false, + SkipRefresh = false, -- [EXPERIMENTAL] Reuse previous frame drawn contents, Begin() returns false. CacheSnap = nil, -- [Port] SetNextWindowCached(): state at the last refresh CacheSkipItemsBackup = nil, - Appearing = false, + Appearing = false, -- Set during the frame where the window is appearing (or re-appearing) - Hidden = false, - IsFallbackWindow = false, + Hidden = false, -- Do not display (== HiddenFrames*** > 0) + IsFallbackWindow = false, -- Set on the "Debug##Default" window. - IsExplicitChild = nil, + IsExplicitChild = nil, -- Set when passed _ChildWindow, left to false by BeginDocked() - ResizeBorderHovered = -1, - ResizeBorderHeld = -1, + ResizeBorderHovered = -1, -- Current border being hovered for resize (-1: none, otherwise 0-3) + ResizeBorderHeld = -1, -- Current border being held for resize (-1: none, otherwise 0-3) - BeginCount = 0, - BeginCountPreviousFrame = 0, - BeginOrderWithinParent = 0, - BeginOrderWithinContext = 0, + BeginCount = 0, -- Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) + BeginCountPreviousFrame = 0, -- Number of Begin() during the previous frame + BeginOrderWithinParent = 0, -- Begin() order within immediate parent window, if we are a child window. Otherwise 0. + BeginOrderWithinContext = 0, -- Begin() order within entire imgui context. This is mostly used for debugging submission order related issues. - FocusOrder = nil, + FocusOrder = nil, -- Order within WindowsFocusOrder[], altered when windows are focused. - HiddenFramesCanSkipItems = 0, - HiddenFramesCannotSkipItems = 0, - HiddenFramesForRenderOnly = 0, + HiddenFramesCanSkipItems = 0, -- Hide the window for N frames + HiddenFramesCannotSkipItems = 0, -- Hide the window for N frames while allowing items to be submitted so we can measure their size + HiddenFramesForRenderOnly = 0, -- Hide the window until frame N at Render() time only - DisableInputsFrames = 0, + DisableInputsFrames = 0, -- Disable window interactions for N frames - WindowRounding = 0, - WindowBorderSize = 1, + WindowRounding = 0, -- Window rounding at the time of Begin(). May be clamped lower to avoid rendering artifacts with title bar, menu bar etc. + WindowBorderSize = 1, -- Window border size at the time of Begin(). TitleBarHeight = 0, MenuBarHeight = 0, @@ -2445,83 +2637,83 @@ function ImGuiWindow(ctx, name) DecoOuterSizeX2 = 0, DecoOuterSizeY2 = 0, DecoInnerSizeX1 = 0, DecoInnerSizeY1 = 0, - ContentSize = ImVec2(), + ContentSize = ImVec2(), -- Size of contents/scrollable client area (calculated from the extents reach of the cursor) from previous frame. Does not include window decoration or window padding. ContentSizeIdeal = ImVec2(), - ContentSizeExplicit = ImVec2(), + ContentSizeExplicit = ImVec2(), -- Size of contents/scrollable client area explicitly request by the user via SetNextWindowContentSize(). AutoFitFramesX = -1, AutoFitFramesY = -1, AutoFitOnlyGrows = false, - HasCloseButton = true, + HasCloseButton = true, -- Set when the window has a close button (p_open ~= nil) - BgClickFlags = 0, + BgClickFlags = 0, -- Configure behavior of click+dragging on window bg/void or over items. Default sets by io.ConfigWindowsMoveFromTitleBarOnly. If you use this please report in #3379. - SetWindowPosAllowFlags = 0, SetWindowSizeAllowFlags = 0, SetWindowCollapsedAllowFlags = 0, - SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX), - SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX), + SetWindowPosAllowFlags = 0, SetWindowSizeAllowFlags = 0, SetWindowCollapsedAllowFlags = 0, -- store acceptable condition flags for SetNextWindowPos() use. + SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX), -- store window position when using a non-zero Pivot (position set needs to be processed when we know the window size) + SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX), -- store window pivot for positioning. ImVec2(0, 0) when positioning from top-left corner; ImVec2(0.5, 0.5) for centering; ImVec2(1, 1) for bottom right. - SettingsOffset = -1, + SettingsOffset = -1, -- Offset into SettingsWindows[] (offsets are always valid as we only grow the array from the back) - ScrollbarSizes = ImVec2(), + ScrollbarSizes = ImVec2(), -- 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. Scroll = ImVec2(), ScrollbarX = false, - ScrollbarY = false, + ScrollbarY = false, -- Are scrollbars visible? ScrollMax = ImVec2(), - ScrollTarget = ImVec2(FLT_MAX, FLT_MAX), - ScrollTargetCenterRatio = ImVec2(0.5, 0.5), - ScrollTargetEdgeSnapDist = ImVec2(), + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX), -- target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0. (FLT_MAX for no change) + ScrollTargetCenterRatio = ImVec2(0.5, 0.5), -- 0.0 = scroll so that target position is at top, 0.5 = scroll so that target position is centered + ScrollTargetEdgeSnapDist = ImVec2(), -- 0.0 = no snapping, >0.0 snapping threshold - ScrollbarXStabilizeToggledHistory = 0, + ScrollbarXStabilizeToggledHistory = 0, -- Used to stabilize scrollbar visibility in case of feedback loops - DrawList = nil, + DrawList = nil, -- == DrawListInst DrawListInst = ImDrawList(ctx.DrawListSharedData), - RootWindow = nil, - RootWindowPopupTree = nil, - RootWindowDockTree = nil, + RootWindow = nil, -- Point to ourself or first ancestor that is not a child window. Doesn't cross through popups/dock nodes. + RootWindowPopupTree = nil, -- Point to ourself or first ancestor that is not a child window. Cross through popups parent<>child. + RootWindowDockTree = nil, -- Point to ourself or first ancestor that is not a child window. Cross through dock nodes. - ParentWindow = nil, + ParentWindow = nil, -- If we are a child _or_ popup _or_ docked window, this is pointing to our parent. Otherwise nil. ParentWindowInBeginStack = nil, - IDStack = ImVector(), + IDStack = ImVector(), -- ID stack. ID are hashes seeded with the value at the top of the stack. (In theory this should be in the TempData structure) - ViewportAllowPlatformMonitorExtend = -1, - Viewport = nil, - ViewportId = 0, - ViewportPos = ImVec2(FLT_MAX, FLT_MAX), + ViewportAllowPlatformMonitorExtend = -1, -- Reset to -1 every frame (index is guaranteed to be valid between NewFrame..EndFrame), only used in the Appearing frame of a tooltip/popup to enforce clamping to a given monitor + Viewport = nil, -- Always set in Begin(). Inactive windows may have a nil value here if their viewport was discarded. + ViewportId = 0, -- We backup the viewport id (since the viewport may disappear or never be created if the window is inactive) + ViewportPos = ImVec2(FLT_MAX, FLT_MAX), -- We backup the viewport position (since the viewport may disappear or never be created if the window is inactive) ViewportOwned = nil, - DC = ImGuiWindowTempData(), + DC = ImGuiWindowTempData(), -- Temporary per-window data, reset at the beginning of the frame. This used to be called ImGuiDrawContext, hence the "DC" variable name. - OuterRectClipped = ImRect(), - InnerRect = ImRect(), - InnerClipRect = ImRect(), - WorkRect = ImRect(), - ParentWorkRect = ImRect(), - ContentRegionRect = ImRect(), + OuterRectClipped = ImRect(), -- == Window.Rect() just after setup in Begin(). == window.Rect() for root window. + InnerRect = ImRect(), -- Inner rectangle (omit title bar, menu bar, scroll bar) + InnerClipRect = ImRect(), -- == InnerRect shrunk by WindowPadding*0.5 on each side, clipped within viewport or parent clip rect. + WorkRect = ImRect(), -- Initially covers the whole scrolling region. Reduced by containers e.g columns/tables when active. Shrunk by WindowPadding*1.0 on each side. This is meant to replace ContentRegionRect over time (from 1.71+ onward). + ParentWorkRect = ImRect(), -- Backup of WorkRect before entering a container such as columns/tables. Used by e.g. SpanAllColumns functions to easily access. Stacked containers are responsible for maintaining this. -- FIXME-WORKRECT: Could be a stack? + ContentRegionRect = ImRect(), -- FIXME: This is currently confusing/misleading. It is essentially WorkRect but not handling of scrolling. We currently rely on it as right/bottom aligned sizing operation need some size to rely on. - ClipRect = ImRect(), + ClipRect = ImRect(), -- Current clipping/scissoring rectangle, evolve as we are using PushClipRect(), etc. == DrawList.clip_rect_stack.back(). - LastFrameActive = -1, - LastFrameJustFocused = -1, - LastTimeActive = -1.0, + LastFrameActive = -1, -- Last frame number the window was Active. + LastFrameJustFocused = -1, -- Last frame number the window was made Focused. + LastTimeActive = -1.0, -- Last timestamp the window was Active (using float as we don't need high precision there) StateStorage = {}, ColumnsStorage = ImVector(), -- ImVector - WriteAccessed = false, + WriteAccessed = false, -- Set to true when any widget access the current window - FontWindowScale = 1.0, + FontWindowScale = 1.0, -- User scale multiplier per-window, via SetWindowFontScale() FontWindowScaleParents = 1.0, - HitTestHoleSize = ImVec2(), + HitTestHoleSize = ImVec2(), -- Define an optional rectangular hole where mouse will pass-through the window. - NavLastChildNavWindow = nil, + NavLastChildNavWindow = nil, -- When going to the menu bar, we remember the child window we came from. (This could probably be made implicit if we kept g.Windows sorted by last focused including child window.) NavLastIds = {[0] = 0, [1] = 0}, -- FIXME: 1-based instead - NavRectRel = {[0] = ImRect(), [1] = ImRect()}, - NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, - NavRootFocusScopeId = 0 + NavRectRel = {[0] = ImRect(), [1] = ImRect()}, -- Reference rectangle, in window relative space + NavPreferredScoringPosRel = {[0] = ImVec2(), [1] = ImVec2()}, -- Preferred X/Y position updated when moving on a given axis, reset to FLT_MAX. + NavRootFocusScopeId = 0 -- Focus Scope ID at the time of Begin() } this.DrawList = this.DrawListInst @@ -2532,27 +2724,27 @@ function ImGuiWindow(ctx, name) this.ID = ImHashStr(name) this.IDStack:push_back(this.ID) this.MoveId = this:GetID("#MOVE") - this.TabId = this:GetID("#TAB") + this.TabId = this:GetID("#TAB") -- == window.GetID("#TAB") -- Docking - this.ChildId = this.ChildId or 0 - this.SetWindowDockAllowFlags = 0 - this.ParentWindowForFocusRoute = nil - this.DockIsActive = false + this.ChildId = this.ChildId or 0 -- ID of corresponding item in parent window (for navigation to return from child window to parent window) + this.SetWindowDockAllowFlags = 0 -- store acceptable condition flags for SetNextWindowDock() use. + this.ParentWindowForFocusRoute = nil -- Set to manual link a window to its logical parent so that Shortcut() chain are honored (e.g. Tool linked to Document) + this.DockIsActive = false -- When docking artifacts are actually visible. When this is set, DockNode is guaranteed to be != nil. ~~ (DockNode != nil) && (DockNode.Windows.Size > 1). this.DockNodeIsVisible = false - this.DockTabIsVisible = false + this.DockTabIsVisible = false -- Is our window visible this frame? ~~ is the corresponding tab selected? this.DockTabWantClose = false - this.DockOrder = -1 + this.DockOrder = -1 -- Order of the last time the window was visible within its DockNode. This is used to reorder windows that are reappearing on the same frame. Same value between windows that were active and windows that were none are possible. this.DockStyle = { Colors = {} } for i = 0, 8 do this.DockStyle.Colors[i] = 0 end - this.DockNode = nil - this.DockNodeAsHost = nil - this.DockId = 0 + this.DockNode = nil -- 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. + this.DockNodeAsHost = nil -- Which node are we owning (for parent windows) + this.DockId = 0 -- Backup of last valid DockNode.ID, so single window remember their dock node id even when they are not bound any more return this end --- @class ImDrawDataBuilder ---- @field Layers [ImVector?, ImVector?] +--- @field Layers [ImVector?, ImVector?] # Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData. --- @field LayerData1 ImVector --- @return ImDrawDataBuilder @@ -2560,11 +2752,17 @@ end local function ImDrawDataBuilder() return { - Layers = {nil, nil}, + Layers = {nil, nil}, -- Pointers to global layers for: regular, tooltip. LayersP[0] is owned by DrawData. LayerData1 = ImVector() } end +------------------------------------------------------------------------------- +-- [SECTION] Viewport support +------------------------------------------------------------------------------- + +-- ImGuiViewport Private/Internals fields (cardinal sin: we are using inheritance!) +-- Every instance of ImGuiViewport is in fact a ImGuiViewportP. --- @class ImGuiViewportP : ImGuiViewport --- @field Window? ImGuiWindow --- @field Idx int # Initial value = -1, then becomes 1-based index @@ -2599,6 +2797,7 @@ function IMGUI_VIEWPORT_P:ClearRequestFlags() self.PlatformRequestResize = false end +-- Calculate work rect pos/size given a set of offset (we have 1 pair of offset for rect locked from last frame data, and 1 pair for currently building rect) function IMGUI_VIEWPORT_P:CalcWorkRectPos(inset_min) return ImVec2(self.Pos.x + inset_min.x, self.Pos.y + inset_min.y) end @@ -2607,11 +2806,13 @@ function IMGUI_VIEWPORT_P:CalcWorkRectSize(inset_min, inset_max) return ImVec2(ImMax(0.0, self.Size.x - inset_min.x - inset_max.x), ImMax(0.0, self.Size.y - inset_min.y - inset_max.y)) end +-- Update public fields function IMGUI_VIEWPORT_P:UpdateWorkRect() self.WorkPos = self:CalcWorkRectPos(self.WorkInsetMin) self.WorkSize = self:CalcWorkRectSize(self.WorkInsetMin, self.WorkInsetMax) end +-- Helpers to retrieve ImRect (we don't need to store BuildWorkRect as every access tend to change it, hence the code asymmetry) --- @nodiscard function IMGUI_VIEWPORT_P:GetMainRect() return ImRect(self.Pos.x, self.Pos.y, @@ -2638,38 +2839,49 @@ end function ImGuiViewportP() local this = setmetatable(ImGuiViewport(), IMGUI_VIEWPORT_P) --- @cast this ImGuiViewportP - this.Window = nil + this.Window = nil -- Set when the viewport is owned by a window (and ImGuiViewportFlags.CanHostOtherWindows is NOT set) this.Idx = -1 - this.LastFrameActive = -1 - this.LastFocusedStampCount = -1 + this.LastFrameActive = -1 -- Last frame number this viewport was activated by a window + this.LastFocusedStampCount = -1 -- Last stamp number from when a window hosted by this viewport was focused (by comparing this value between two viewport we have an implicit viewport z-order we use as fallback) this.LastNameHash = 0 this.LastPos = ImVec2() -- ImGuiViewport() { memset(this, 0, sizeof(*this)); } this.LastSize = ImVec2() - this.Alpha = 1.0 + this.Alpha = 1.0 -- Window opacity (when dragging dockable windows/viewports we make them transparent) this.LastAlpha = 1.0 - this.LastFocusedHadNavWindow = false + this.LastFocusedHadNavWindow = false -- Instead of maintaining a LastFocusedWindow (which may harder to correctly maintain), we merely store weither NavWindow ~= nil last time the viewport was focused. this.PlatformMonitor = -1 - this.BgFgDrawListsLastTimeActive = {-1, -1} - this.BgFgDrawLists = {nil, nil} + this.BgFgDrawListsLastTimeActive = {-1, -1} -- Timestamps for Gc. + this.BgFgDrawLists = {nil, nil} -- Convenience background [1] and foreground [2] draw lists. We use them to draw software mouser cursor when io.MouseDrawCursor is set and to draw most debug overlays. this.DrawDataP = ImDrawData() - this.DrawDataBuilder = ImDrawDataBuilder() + this.DrawDataBuilder = ImDrawDataBuilder() -- Temporary data while building final ImDrawData this.LastPlatformPos = ImVec2(FLT_MAX, FLT_MAX) this.LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX) this.LastRendererSize = ImVec2(FLT_MAX, FLT_MAX) - this.WorkInsetMin = ImVec2(0, 0) - this.WorkInsetMax = ImVec2(0, 0) - this.BuildWorkInsetMin = ImVec2(0, 0) - this.BuildWorkInsetMax = ImVec2(0, 0) + -- Per-viewport work area + -- - Insets are >= 0.0 values, distance from viewport corners to work area. + -- - BeginMainMenuBar() and DockspaceOverViewport() tend to use work area to avoid stepping over existing contents. + -- - Generally 'safeAreaInsets' in iOS land, 'DisplayCutout' in Android land. + this.WorkInsetMin = ImVec2(0, 0) -- Work Area inset locked for the frame. GetWorkRect() always fits within GetMainRect(). + this.WorkInsetMax = ImVec2(0, 0) -- " + this.BuildWorkInsetMin = ImVec2(0, 0) -- Work Area inset accumulator for current frame, to become next frame's WorkInset + this.BuildWorkInsetMax = ImVec2(0, 0) -- " return this end +------------------------------------------------------------------------------- +-- [SECTION] ImFontLoader +------------------------------------------------------------------------------- + +-- 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. --- @class ImFontLoader --- @field Name string --- @field LoaderInit? fun(atlas: ImFontAtlas): bool @@ -2698,13 +2910,24 @@ function ImFontLoader() this.FontSrcContainsGlyph = nil this.FontBakedInit = nil this.FontBakedDestroy = nil - this.FontBakedLoadGlyph = nil + this.FontBakedLoadGlyph = nil -- Required + -- 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? this.FontBakedSrcLoaderDataSize = 0 return this end +------------------------------------------------------------------------------- +-- [SECTION] ImFontAtlas internal API +------------------------------------------------------------------------------- + +-- 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. --- @class ImFontAtlasRectEntry --- @field TargetIndex int # 0-based! When IsUsed = true, TargetIndex = this rect's index in Rects; IsUsed = false, TargetIndex = the next unused RectsIndex entry's index --- @field Generation unsigned_int # How many times this entry is reused @@ -2720,8 +2943,9 @@ function ImFontAtlasRectEntry() } end -local ImFontAtlasRectId_IndexMask_ = 0x0007FFFF -local ImFontAtlasRectId_GenerationMask_ = 0x3FF00000 +-- Refer to ImFontAtlasPackGetRect() to better understand how this works. +local ImFontAtlasRectId_IndexMask_ = 0x0007FFFF -- 20-bits signed: index to access builder.RectsIndex[]. +local ImFontAtlasRectId_GenerationMask_ = 0x3FF00000 -- 10-bits: entry generation, so each ID is unique and get can safely detected old identifiers. local ImFontAtlasRectId_GenerationShift_ = 20 --- @param id ImFontAtlasRectId # Expects 0-based! @@ -2740,6 +2964,7 @@ function ImFontAtlasRectId_Make(index_idx, gen_idx) return bitOr(index_idx, bitLShift(gen_idx, ImFontAtlasRectId_GenerationShift_)) end +-- Data available to potential texture post-processing functions --- @class ImFontAtlasPostProcessData --- @field FontAtlas ImFontAtlas --- @field Font ImFont @@ -2774,6 +2999,7 @@ function ImFontAtlasPostProcessData(atlas, font, font_src, font_baked, glyph, pi FontBaked = font_baked, Glyph = glyph, + -- Pixel data Pixels = pixels, _PixelsBase = pixels_base, Format = format, @@ -2783,10 +3009,14 @@ function ImFontAtlasPostProcessData(atlas, font, font_src, font_baked, glyph, pi } end +------------------------------------------------------------------------------- +-- [SECTION] Inputs support +------------------------------------------------------------------------------- + --- @enum ImGuiInputSource ImGuiInputSource = { None = 0, - Mouse = 1, + Mouse = 1, -- Note: may be Mouse or TouchScreen or Pen. See io.MouseSource to distinguish them. Keyboard = 2, Gamepad = 3, COUNT = 4 @@ -2871,7 +3101,7 @@ function ImGuiInputEvent() return { Type = 0, Source = 0, - EventId = 0, + EventId = 0, -- Unique, sequential increasing integer to identify an event (if you need to correlate them to other data). -- union MousePos = nil, -- if Type == ImGuiInputEventType.MousePos @@ -2884,6 +3114,7 @@ function ImGuiInputEvent() } end +-- [Internal] Key ranges ImGuiKey_Keyboard_BEGIN = ImGuiKey.NamedKey_BEGIN ImGuiKey_Keyboard_END = ImGuiKey.GamepadStart ImGuiKey_Gamepad_BEGIN = ImGuiKey.GamepadStart @@ -2893,12 +3124,13 @@ ImGuiKey_Mouse_END = ImGuiKey.MouseWheelY + 1 ImGuiKey_Aliases_BEGIN = ImGuiKey_Mouse_BEGIN ImGuiKey_Aliases_END = ImGuiKey_Mouse_END +-- [Internal] Named shortcuts for Navigation ImGuiKey.NavKeyboardTweakSlow = ImGuiMod_Ctrl ImGuiKey.NavKeyboardTweakFast = ImGuiMod_Shift ImGuiKey.NavGamepadTweakSlow = ImGuiKey.GamepadL1 ImGuiKey.NavGamepadTweakFast = ImGuiKey.GamepadR1 -ImGuiKey.NavGamepadMenu = ImGuiKey.GamepadFaceLeft -ImGuiKey.NavGamepadContextMenu = ImGuiKey.GamepadFaceUp +ImGuiKey.NavGamepadMenu = ImGuiKey.GamepadFaceLeft -- Toggle menu layer. Hold to enable Windowing. +ImGuiKey.NavGamepadContextMenu = ImGuiKey.GamepadFaceUp -- Open context menu (same as Shift+F10) --- @enum ImGuiInputEventType ImGuiInputEventType = { @@ -2913,19 +3145,33 @@ ImGuiInputEventType = { COUNT = 8 } -ImGuiInputFlags.RepeatRateDefault = bitLShift(1, 1) -ImGuiInputFlags.RepeatRateNavMove = bitLShift(1, 2) -ImGuiInputFlags.RepeatRateNavTweak = bitLShift(1, 3) -ImGuiInputFlags.RepeatUntilRelease = bitLShift(1, 4) -ImGuiInputFlags.RepeatUntilKeyModsChange = bitLShift(1, 5) -ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone = bitLShift(1, 6) -ImGuiInputFlags.RepeatUntilOtherKeyPress = bitLShift(1, 7) -ImGuiInputFlags.LockThisFrame = bitLShift(1, 20) -ImGuiInputFlags.LockUntilRelease = bitLShift(1, 21) -ImGuiInputFlags.CondHovered = bitLShift(1, 22) -ImGuiInputFlags.CondActive = bitLShift(1, 23) +-- Extend ImGuiInputFlags +-- Flags for extended versions of IsKeyPressed(), IsMouseClicked(), Shortcut(), SetKeyOwner(), SetItemKeyOwner() +-- Don't mistake with ImGuiInputTextFlags! (which is for ImGui.InputText() function) + +-- Flags for IsKeyPressed(), IsKeyChordPressed(), IsMouseClicked(), Shortcut() +-- - Repeat mode: Repeat rate selection +ImGuiInputFlags.RepeatRateDefault = bitLShift(1, 1) -- Repeat rate: Regular (default) +ImGuiInputFlags.RepeatRateNavMove = bitLShift(1, 2) -- Repeat rate: Fast +ImGuiInputFlags.RepeatRateNavTweak = bitLShift(1, 3) -- Repeat rate: Faster +-- - Repeat mode: Specify when repeating key pressed can be interrupted. +-- - In theory ImGuiInputFlags.RepeatUntilOtherKeyPress may be a desirable default, but it would break too many behavior so everything is opt-in. +ImGuiInputFlags.RepeatUntilRelease = bitLShift(1, 4) -- Stop repeating when released (default for all functions except Shortcut). This only exists to allow overriding Shortcut() default behavior. +ImGuiInputFlags.RepeatUntilKeyModsChange = bitLShift(1, 5) -- Stop repeating when released OR if keyboard mods are changed (default for Shortcut) +ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone = bitLShift(1, 6) -- Stop repeating when released OR if keyboard mods are leaving the None state. Allows going from Mod+Key to Key by releasing Mod. +ImGuiInputFlags.RepeatUntilOtherKeyPress = bitLShift(1, 7) -- Stop repeating when released OR if any other keyboard key is pressed during the repeat + +-- Flags for SetKeyOwner(), SetItemKeyOwner() +-- - Locking key away from non-input aware code. Locking is useful to make input-owner-aware code steal keys from non-input-owner-aware code. If all code is input-owner-aware locking would never be necessary. +ImGuiInputFlags.LockThisFrame = bitLShift(1, 20) -- Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared at end of frame. +ImGuiInputFlags.LockUntilRelease = bitLShift(1, 21) -- Further accesses to key data will require EXPLICIT owner ID (ImGuiKeyOwner_Any/0 will NOT accepted for polling). Cleared when the key is released or at end of each frame if key is released. + +-- - Condition for SetItemKeyOwner() +ImGuiInputFlags.CondHovered = bitLShift(1, 22) -- Only set if item is hovered (default to both) +ImGuiInputFlags.CondActive = bitLShift(1, 23) -- Only set if item is active (default to both) ImGuiInputFlags.CondDefault_ = bitOr(ImGuiInputFlags.CondHovered, ImGuiInputFlags.CondActive) +-- [Internal] Mask of which function support which flags ImGuiInputFlags.RepeatRateMask_ = bitOr(ImGuiInputFlags.RepeatRateDefault, ImGuiInputFlags.RepeatRateNavMove, ImGuiInputFlags.RepeatRateNavTweak) ImGuiInputFlags.RepeatUntilMask_ = bitOr(ImGuiInputFlags.RepeatUntilRelease, ImGuiInputFlags.RepeatUntilKeyModsChange, ImGuiInputFlags.RepeatUntilKeyModsChangeFromNone, ImGuiInputFlags.RepeatUntilOtherKeyPress) ImGuiInputFlags.RepeatMask_ = bitOr(ImGuiInputFlags.Repeat, ImGuiInputFlags.RepeatRateMask_, ImGuiInputFlags.RepeatUntilMask_) @@ -2954,32 +3200,39 @@ ImGuiPlotType = Histogram = 1 } +------------------------------------------------------------------------------- +-- [SECTION] Navigation support +------------------------------------------------------------------------------- + --- @enum ImGuiActivateFlags ImGuiActivateFlags = { None = 0, - PreferInput = bitLShift(1, 0), - PreferTweak = bitLShift(1, 1), - TryToPreserveState = bitLShift(1, 2), - FromTabbing = bitLShift(1, 3), - FromShortcut = bitLShift(1, 4), - FromFocusApi = bitLShift(1, 5) + PreferInput = bitLShift(1, 0), -- Favor activation that requires keyboard text input (e.g. for Slider/Drag). Default for Enter key. + PreferTweak = bitLShift(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. + TryToPreserveState = bitLShift(1, 2), -- Request widget to preserve state if it can (e.g. InputText will try to preserve cursor/selection) + FromTabbing = bitLShift(1, 3), -- Activation requested by a tabbing request (ImGuiNavMoveFlags.IsTabbing) + FromShortcut = bitLShift(1, 4), -- Activation requested by an item shortcut via SetNextItemShortcut() function. + FromFocusApi = bitLShift(1, 5) -- Activation requested by an api request (ImGuiNavMoveFlags.FocusApi) } +-- Early work-in-progress API for ScrollToItem() +-- FIXME: Missing flags to request making both edges visible when possible. --- @enum ImGuiScrollFlags ImGuiScrollFlags = { None = 0, - KeepVisibleEdgeX = bitLShift(1, 0), - KeepVisibleEdgeY = bitLShift(1, 1), - KeepVisibleCenterX = bitLShift(1, 2), - KeepVisibleCenterY = bitLShift(1, 3), - AlwaysCenterX = bitLShift(1, 4), - AlwaysCenterY = bitLShift(1, 5), - NoScrollParent = bitLShift(1, 6), + KeepVisibleEdgeX = bitLShift(1, 0), -- If item is not visible: scroll as little as possible on X axis to bring item back into view [default for X axis] + KeepVisibleEdgeY = bitLShift(1, 1), -- If item is not visible: scroll as little as possible on Y axis to bring item back into view [default for Y axis for windows that are already visible] + KeepVisibleCenterX = bitLShift(1, 2), -- If item is not visible: scroll to make the item centered on X axis [rarely used] + KeepVisibleCenterY = bitLShift(1, 3), -- If item is not visible: scroll to make the item centered on Y axis + AlwaysCenterX = bitLShift(1, 4), -- Always center the result item on X axis [rarely used] + AlwaysCenterY = bitLShift(1, 5), -- Always center the result item on Y axis [default for Y axis for appearing window) + NoScrollParent = bitLShift(1, 6), -- Disable forwarding scrolling to parent window if required to keep item/rect visible (only scroll window the function was applied to). } ImGuiScrollFlags.MaskX_ = bitOr(ImGuiScrollFlags.KeepVisibleEdgeX, ImGuiScrollFlags.KeepVisibleCenterX, ImGuiScrollFlags.AlwaysCenterX) ImGuiScrollFlags.MaskY_ = bitOr(ImGuiScrollFlags.KeepVisibleEdgeY, ImGuiScrollFlags.KeepVisibleCenterY, ImGuiScrollFlags.AlwaysCenterY) +-- Stacked storage data for BeginGroup()/EndGroup() --- @class ImGuiGroupData --- @field WindowID ImGuiID --- @field BackupCursorPos ImVec2 @@ -3022,9 +3275,13 @@ end ImGuiTooltipFlags = { None = 0, - OverridePrevious = bitLShift(1, 1) + OverridePrevious = bitLShift(1, 1) -- Clear/ignore previously submitted tooltip (defaults to append) } +------------------------------------------------------------------------------- +-- [SECTION] Popup support +------------------------------------------------------------------------------- + --- @enum ImGuiPopupPositionPolicy ImGuiPopupPositionPolicy = { @@ -3033,6 +3290,7 @@ ImGuiPopupPositionPolicy = Tooltip = 2 } +-- Storage for popup stacks (g.OpenPopupStack and g.BeginPopupStack) --- @class ImGuiPopupData --- @field PopupId ImGuiID --- @field Window ImGuiWindow @@ -3047,32 +3305,38 @@ ImGuiPopupPositionPolicy = --- @nodiscard function ImGuiPopupData() return { - PopupId = 0, - Window = nil, - RestoreNavWindow = nil, - ParentNavLayer = -1, - OpenFrameCount = -1, - OpenParentId = 0, - OpenPopupPos = ImVec2(), - OpenMousePos = ImVec2() + PopupId = 0, -- Set on OpenPopup() + Window = nil, -- Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() + RestoreNavWindow = nil, -- Set on OpenPopup(), a NavWindow that will be restored on popup close + ParentNavLayer = -1, -- Resolved on BeginPopup(). Actually a ImGuiNavLayer type (declared down below), initialized to -1 which is not part of an enum, but serves well-enough as "not any of layers" value + OpenFrameCount = -1, -- Set on OpenPopup() + OpenParentId = 0, -- Set on OpenPopup(), we need this to differentiate multiple menu sets from each others (e.g. inside menu bar vs loose menu items) + OpenPopupPos = ImVec2(), -- Set on OpenPopup(), preferred popup position (typically == OpenMousePos when using mouse) + OpenMousePos = ImVec2() -- Set on OpenPopup(), copy of mouse position at the time of opening popup } end --- @enum ImGuiWindowRefreshFlags ImGuiWindowRefreshFlags = { None = 0, - TryToAvoidRefresh = bitLShift(1, 0), - RefreshOnHover = bitLShift(1, 1), - RefreshOnFocus = bitLShift(1, 2) + TryToAvoidRefresh = bitLShift(1, 0), -- [EXPERIMENTAL] Try to keep existing contents, USER MUST NOT HONOR BEGIN() RETURNING FALSE AND NOT APPEND. + RefreshOnHover = bitLShift(1, 1), -- [EXPERIMENTAL] Always refresh on hover + RefreshOnFocus = bitLShift(1, 2) -- [EXPERIMENTAL] Always refresh on focus + -- Refresh policy/frequency, Load Balancing etc. } --- @enum ImGuiNavRenderCursorFlags ImGuiNavRenderCursorFlags = { None = 0, Compact = bitLShift(1, 1), -- Compact highlight, no padding/distance from focused item - AlwaysDraw = bitLShift(1, 2), -- Draw rectangular highlight if (g.NavId == id) even when g.NavCursorVisible == false, aka even when using the mouse + AlwaysDraw = bitLShift(1, 2), -- Draw rectangular highlight if (g.NavId == id) even when g.NavCursorVisible == false, aka even when using the mouse. } +------------------------------------------------------------------------------- +-- [SECTION] Metrics, Debug Tools +------------------------------------------------------------------------------- + +-- See IMGUI_DEBUG_LOG() and IMGUI_DEBUG_LOG_XXX() macros. --- @enum ImGuiDebugLogFlags ImGuiDebugLogFlags = { -- Event types @@ -3091,7 +3355,7 @@ ImGuiDebugLogFlags = { EventViewport = bitLShift(1, 11), EventTable = bitLShift(1, 12), - OutputToTTY = bitLShift(1, 20), + OutputToTTY = bitLShift(1, 20), -- Also send output to TTY OutputToDebugger = bitLShift(1, 21), OutputToTestEngine = bitLShift(1, 22), } @@ -3112,6 +3376,11 @@ ImGuiDebugLogFlags.EventMask_ = bitOr( ImGuiDebugLogFlags.EventViewport ) +------------------------------------------------------------------------------- +-- [SECTION] Localization support +------------------------------------------------------------------------------- + +-- This is experimental and not officially supported, it'll probably fall short of features, if/when it does we may backtrack. --- @enum ImGuiLocKey ImGuiLocKey = { VersionStr = 1, @@ -3150,6 +3419,7 @@ function ImGui.TempInputIsActive(id) return (g.TempInputId == id and g.ActiveId == id) or (g.InputTextDeactivatedState.ID == id) end +-- Get input text state if active --- @param id ImGuiID --- @return ImGuiInputTextState? function ImGui.GetInputTextState(id) diff --git a/imgui_tables.lua b/imgui_tables.lua index a7922d6..18b07ab 100644 --- a/imgui_tables.lua +++ b/imgui_tables.lua @@ -1,7 +1,181 @@ --- Dear ImGui WIP --- (Tables and Columns Code) +-- (tables and columns code) -- 1:1 port of imgui_tables.cpp (docking branch, 1.93 WIP) + +-- Index of this file: -- +-- [SECTION] Commentary +-- [SECTION] Structs (port: struct constructors from imgui_internal.h / imgui.h) +-- [SECTION] Tables: Main code +-- [SECTION] Tables: Simple accessors +-- [SECTION] Tables: Row changes +-- [SECTION] Tables: Columns changes +-- [SECTION] Tables: Columns width management +-- [SECTION] Tables: Drawing +-- [SECTION] Tables: Sorting +-- [SECTION] Tables: Headers +-- [SECTION] Tables: Context Menu +-- [SECTION] Tables: Settings (.ini data) +-- [SECTION] Tables: Garbage Collection +-- [SECTION] Columns, BeginColumns, EndColumns, etc. + +------------------------------------------------------------------------------- +-- [SECTION] Commentary +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- Typical tables call flow: (root level is generally public API): +------------------------------------------------------------------------------- +-- - BeginTable() user begin into a table +-- | BeginChild() - (if ScrollX/ScrollY is set) +-- | TableBeginInitMemory() - first time table is used +-- | TableResetSettings() - on settings reset +-- | TableLoadSettings() - on settings load +------------------------------------------------------------------------------- +-- - TableSetupColumn() user submit columns details (optional) +-- - TableSetupScrollFreeze() user submit scroll freeze information (optional) +------------------------------------------------------------------------------- +-- - TableUpdateLayout() [Internal] followup to BeginTable(): setup everything: widths, columns positions, clipping rectangles. Automatically called by the FIRST call to TableNextRow() or TableHeadersRow(). +-- | TableApplyQueuedRequests() - apply queued resizing/reordering/hiding requests +-- | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame) +-- | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width +-- | - TableSetColumnDisplayOrder() - apply reordering a column +-- | TableSetupDrawChannels() - setup ImDrawList channels +-- | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission +-- | TableBeginContextMenuPopup() +-- | - TableDrawDefaultContextMenu() - draw right-click context menu contents +------------------------------------------------------------------------------- +-- - TableHeadersRow() or TableHeader() user submit a headers row (optional) +-- | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction +-- | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu +-- - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers) +-- - TableNextRow() user begin into a new row (also automatically called by TableHeadersRow()) +-- | TableEndRow() - finish existing row +-- | TableBeginRow() - add a new row +-- - TableSetColumnIndex() / TableNextColumn() user begin into a cell +-- | TableEndCell() - close existing column/cell +-- | TableBeginCell() - enter into current column/cell +-- - [...] user emit contents +------------------------------------------------------------------------------- +-- - EndTable() user ends the table +-- | TableDrawBorders() - draw outer borders, inner vertical borders +-- | TableMergeDrawChannels() - merge draw channels if clipping isn't required +-- | EndChild() - (if ScrollX/ScrollY is set) +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- TABLE SIZING +------------------------------------------------------------------------------- +-- (Read carefully because this is subtle but it does make sense!) +------------------------------------------------------------------------------- +-- About 'outer_size': +-- Its meaning needs to differ slightly depending on if we are using ScrollX/ScrollY flags. +-- Default value is ImVec2(0.0, 0.0). +-- X +-- - outer_size.x <= 0.0 -> Right-align from window/work-rect right-most edge. With -FLT_MIN or 0.0 will align exactly on right-most edge. +-- - outer_size.x > 0.0 -> Set Fixed width. +-- Y with ScrollX/ScrollY disabled: we output table directly in current window +-- - outer_size.y < 0.0 -> Bottom-align (but will auto extend, unless _NoHostExtendY is set). Not meaningful if parent window can vertically scroll. +-- - outer_size.y = 0.0 -> No minimum height (but will auto extend, unless _NoHostExtendY is set) +-- - outer_size.y > 0.0 -> Set Minimum height (but will auto extend, unless _NoHostExtendY is set) +-- Y with ScrollX/ScrollY enabled: using a child window for scrolling +-- - outer_size.y < 0.0 -> Bottom-align. Not meaningful if parent window can vertically scroll. +-- - outer_size.y = 0.0 -> Bottom-align, consistent with BeginChild(). Not recommended unless table is last item in parent window. +-- - outer_size.y > 0.0 -> Set Exact height. Recommended when using Scrolling on any axis. +------------------------------------------------------------------------------- +-- Outer size is also affected by the NoHostExtendX/NoHostExtendY flags. +-- Important to note how the two flags have slightly different behaviors! +-- - ImGuiTableFlags.NoHostExtendX -> Make outer width auto-fit to columns (overriding outer_size.x value). Only available when ScrollX/ScrollY are disabled and Stretch columns are not used. +-- - ImGuiTableFlags.NoHostExtendY -> Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY is disabled. Data below the limit will be clipped and not visible. +-- In theory ImGuiTableFlags.NoHostExtendY could be the default and any non-scrolling tables with outer_size.y ~= 0.0 would use exact height. +-- This would be consistent but perhaps less useful and more confusing (as vertically clipped items are not useful and not easily noticeable). +------------------------------------------------------------------------------- +-- About 'inner_width': +-- With ScrollX disabled: +-- - inner_width -> *ignored* +-- With ScrollX enabled: +-- - inner_width < 0.0 -> *illegal* fit in known width (right align from outer_size.x) <-- weird +-- - inner_width = 0.0 -> fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns. +-- - inner_width > 0.0 -> override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space! +------------------------------------------------------------------------------- +-- Details: +-- - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept +-- of "available space" doesn't make sense. +-- - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding +-- of what the value does. +------------------------------------------------------------------------------- + +------------------------------------------------------------------------------- +-- COLUMNS SIZING POLICIES +-- (Reference: ImGuiTableFlags.SizingXXX flags and ImGuiTableColumnFlags.WidthXXX flags) +------------------------------------------------------------------------------- +-- About overriding column sizing policy and width/weight with TableSetupColumn(): +-- We use a default parameter of -1 for 'init_width'/'init_weight'. +-- - with ImGuiTableColumnFlags.WidthFixed, init_width <= 0 (default) --> width is automatic +-- - with ImGuiTableColumnFlags.WidthFixed, init_width > 0 (explicit) --> width is custom +-- - with ImGuiTableColumnFlags.WidthStretch, init_weight <= 0 (default) --> weight is 1.0 +-- - with ImGuiTableColumnFlags.WidthStretch, init_weight > 0 (explicit) --> weight is custom +-- Widths are specified _without_ CellPadding. If you specify a width of 100.0, the column will be cover (100.0 + Padding * 2.0) +-- and you can fit a 100.0 wide item in it without clipping and with padding honored. +------------------------------------------------------------------------------- +-- About default sizing policy (if you don't specify a ImGuiTableColumnFlags.WidthXXXX flag) +-- - with Table policy ImGuiTableFlags.SizingFixedFit --> default Column policy is ImGuiTableColumnFlags.WidthFixed, default Width is equal to contents width +-- - with Table policy ImGuiTableFlags.SizingFixedSame --> default Column policy is ImGuiTableColumnFlags.WidthFixed, default Width is max of all contents width +-- - with Table policy ImGuiTableFlags.SizingStretchSame --> default Column policy is ImGuiTableColumnFlags.WidthStretch, default Weight is 1.0 +-- - with Table policy ImGuiTableFlags.SizingStretchWeight --> default Column policy is ImGuiTableColumnFlags.WidthStretch, default Weight is proportional to contents +-- Default Width and default Weight can be overridden when calling TableSetupColumn(). +------------------------------------------------------------------------------- +-- About mixing Fixed/Auto and Stretch columns together: +-- - the typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns. +-- - using mixed policies with ScrollX does not make much sense, as using Stretch columns with ScrollX does not make much sense in the first place! +-- that is, unless 'inner_width' is passed to BeginTable() to explicitly provide a total width to layout columns in. +-- - when using ImGuiTableFlags.SizingFixedSame with mixed columns, only the Fixed/Auto columns will match their widths to the width of the maximum contents. +-- - when using ImGuiTableFlags.SizingStretchSame with mixed columns, only the Stretch columns will match their weights/widths. +------------------------------------------------------------------------------- +-- About using column width: +-- If a column is manually resizable or has a width specified with TableSetupColumn(): +-- - you may use GetContentRegionAvail().x to query the width available in a given column. +-- - right-side alignment features such as SetNextItemWidth(-x) or PushItemWidth(-x) will rely on this width. +-- If the column is not resizable and has no width specified with TableSetupColumn(): +-- - its width will be automatic and be set to the max of items submitted. +-- - therefore you generally cannot have ALL items of the columns use e.g. SetNextItemWidth(-FLT_MIN). +-- - but if the column has one or more items of known/fixed size, this will become the reference width used by SetNextItemWidth(-FLT_MIN). +------------------------------------------------------------------------------- + + +------------------------------------------------------------------------------- +-- TABLES CLIPPING/CULLING +------------------------------------------------------------------------------- +-- About clipping/culling of Rows in Tables: +-- - For large numbers of rows, it is recommended you use ImGuiListClipper to submit only visible rows. +-- ImGuiListClipper is reliant on the fact that rows are of equal height. +-- See 'Demo->Tables->Vertical Scrolling' or 'Demo->Tables->Advanced' for a demo of using the clipper. +-- - Note that auto-resizing columns don't play well with using the clipper. +-- By default a table with _ScrollX but without _Resizable will have column auto-resize. +-- So, if you want to use the clipper, make sure to either enable _Resizable, either setup columns width explicitly with _WidthFixed. +------------------------------------------------------------------------------- +-- About clipping/culling of Columns in Tables: +-- - Both TableSetColumnIndex() and TableNextColumn() return true when the column is visible or performing +-- width measurements. Otherwise, you may skip submitting the contents of a cell/column, BUT ONLY if you know +-- it is not going to contribute to row height. +-- In many situations, you may skip submitting contents for every column but one (e.g. the first one). +-- - Case A: column is not hidden by user, and at least partially in sight (most common case). +-- - Case B: column is clipped / out of sight (because of scrolling or parent ClipRect): TableNextColumn() return false as a hint but we still allow layout output. +-- - Case C: column is hidden explicitly by the user (e.g. via the context menu, or _DefaultHide column flag, etc.). +-- +-- [A] [B] [C] +-- TableNextColumn(): true false false -> [userland] when TableNextColumn() / TableSetColumnIndex() returns false, user can skip submitting items but only if the column doesn't contribute to row height. +-- SkipItems: false false true -> [internal] when SkipItems is true, most widgets will early out if submitted, resulting is no layout output. +-- ClipRect: normal zero-width zero-width -> [internal] when ClipRect is zero, ItemAdd() will return false and most widgets will early out mid-way. +-- ImDrawList output: normal dummy dummy -> [internal] when using the dummy channel, ImDrawList submissions (if any) will be wasted (because cliprect is zero-width anyway). +-- +-- - We need to distinguish those cases because non-hidden columns that are clipped outside of scrolling bounds should still contribute their height to the row. +-- However, in the majority of cases, the contribution to row height is the same for all columns, or the tallest cells are known by the programmer. +------------------------------------------------------------------------------- +-- About clipping/culling of whole Tables: +-- - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false. +------------------------------------------------------------------------------- + -- Port notes: -- - Column indices / display orders / draw channel indices are 0-based VALUES like upstream. -- Per-column arrays (table.Columns, table.DisplayOrderToIndex, table.RowCellData) are Lua tables with 0-based keys. @@ -27,32 +201,40 @@ end local bit32 = bit32 local band, bor, bnot, lshift, rshift = bit32.band, bit32.bor, bit32.bnot, bit32.lshift, bit32.rshift -IM_COL32_DISABLE = IM_COL32(0, 0, 0, 1) -IMGUI_TABLE_MAX_COLUMNS = 512 +IM_COL32_DISABLE = IM_COL32(0, 0, 0, 1) -- Special sentinel code which cannot be used as a regular color. +IMGUI_TABLE_MAX_COLUMNS = 512 -- Arbitrary "safety" maximum, may be lifted in the future if needed. Must fit in ImGuiTableColumnIdx/ImGuiTableDrawChannelIdx. local function IMGUI_DEBUG_LOG_TABLE(fmt, ...) local g = GImGui if band(g.DebugLogFlags, ImGuiDebugLogFlags.EventTable) ~= 0 then ImGui.DebugLog(fmt, ...) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Structs ----------------------------------------------------------------- +------------------------------------------------------------------------------- local function BitArrayClearAll(arr) table.clear(arr) end local function BitArraySet(arr, n) arr[n] = true end local function BitTest(arr, n) return arr[n] == true end +-- Sorting specification for one column of a table --- @class ImGuiTableColumnSortSpecs function ImGuiTableColumnSortSpecs() return { ColumnUserID = 0, ColumnIndex = 0, SortOrder = 0, SortDirection = ImGuiSortDirection.None } end +-- Sorting specifications for a table (often handling sort specs for a single column, occasionally more) +-- Obtained by calling TableGetSortSpecs(). +-- When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time. +-- Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame! --- @class ImGuiTableSortSpecs function ImGuiTableSortSpecs() return { Specs = nil, SpecsCount = 0, SpecsDirty = false } end +-- We use the terminology "Enabled" to refer to a column that is not Hidden by user/api. +-- We use the terminology "Clipped" to refer to a column that is out of sight because of scrolling/clipping. +-- This is in contrast with some user-facing api such as IsItemVisible() / IsRectVisible() which use "Visible" to mean "not clipped". --- @class ImGuiTableColumn function ImGuiTableColumn() return { @@ -83,11 +265,16 @@ local function TableColumnClone(src) return TableColumnCopy(ImGuiTableColumn(), src) end +-- Per-instance data that needs preserving across frames (seemingly most others do not need to be preserved aside from debug needs. Does that means they could be moved to ImGuiTableTempData?) --- @class ImGuiTableInstanceData function ImGuiTableInstanceData() return { TableInstanceID = 0, LastOuterHeight = 0.0, LastTopHeadersRowHeight = 0.0, LastFrozenHeight = 0.0, HoveredRowLast = -1, HoveredRowNext = -1 } end +-- Transient data that are only needed between BeginTable() and EndTable(), those buffers are shared (1 per level of stacked table). +-- - Accessing those requires chasing an extra pointer so for very frequently used data we leave them in the main table structure. +-- - We also leave out of this structure data that tend to be particularly useful for debugging/metrics. +-- FIXME-TABLE: more transient data could be stored in a stacked ImGuiTableTempData: e.g. SortSpecs. --- @class ImGuiTableTempData function ImGuiTableTempData() return { @@ -101,6 +288,7 @@ function ImGuiTableTempData() } end +-- Storage for a table --- @class ImGuiTable function ImGuiTable() return { @@ -140,11 +328,13 @@ function ImGuiTableColumnSettings() IsEnabled = -1, IsStretch = 0, IsLoaded = false } end +-- Storage for a table .ini settings --- @class ImGuiTableSettings function ImGuiTableSettings() return { ID = 0, SaveFlags = 0, RefScale = 0.0, ColumnsCount = 0, ColumnsCountMax = 0, LastUsedDate = 0, WantApply = false, Columns = {} } end +-- Storage data for a single column for legacy Columns() api --- @class ImGuiOldColumnData function ImGuiOldColumnData() return { OffsetNorm = 0.0, OffsetNormBeforeResize = 0.0, Flags = 0, ClipRect = ImRect() } @@ -157,28 +347,42 @@ function ImGuiOldColumns() HostBackupClipRect = ImRect(), HostBackupParentWorkRect = ImRect(), Columns = ImVector(), Splitter = ImDrawListSplitter() } end +-- Flags for internal's BeginColumns(). This is an obsolete API. Prefer using BeginTable() nowadays! ImGuiOldColumnFlags = ImGuiOldColumnFlags or { None = 0, - NoBorder = lshift(1, 0), - NoResize = lshift(1, 1), - NoPreserveWidths = lshift(1, 2), - NoForceWithinWindow = lshift(1, 3), - GrowParentContentsSize = lshift(1, 4), + NoBorder = lshift(1, 0), -- Disable column dividers + NoResize = lshift(1, 1), -- Disable resizing columns when clicking on the dividers + NoPreserveWidths = lshift(1, 2), -- Disable column width preservation when adjusting columns + NoForceWithinWindow = lshift(1, 3), -- Disable forcing columns to fit within window + GrowParentContentsSize = lshift(1, 4), -- Restore pre-1.51 behavior of extending the parent window contents size but _without affecting the columns width at all_. Will eventually remove. } -ImGuiTableColumnFlags.NoDirectResize_ = ImGuiTableColumnFlags.NoDirectResize_ or lshift(1, 30) +ImGuiTableColumnFlags.NoDirectResize_ = ImGuiTableColumnFlags.NoDirectResize_ or lshift(1, 30) -- [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge) local function Rect(r) return ImRect(r.Min.x, r.Min.y, r.Max.x, r.Max.y) end local function V2(v) return ImVec2(v.x, v.y) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Main code ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableFixFlags() [Internal] +-- - TableFindByID() [Internal] +-- - BeginTable() +-- - BeginTableEx() [Internal] +-- - TableBeginInitMemory() [Internal] +-- - TableApplyQueuedRequests() [Internal] +-- - TableSetupColumnFlags() [Internal] +-- - TableUpdateLayout() [Internal] +-- - TableUpdateBorders() [Internal] +-- - EndTable() +-- - TableSetupColumn() +-- - TableSetupScrollFreeze() +------------------------------------------------------------------------------- -- Configuration local TABLE_DRAW_CHANNEL_BG0 = 0 local TABLE_DRAW_CHANNEL_BG2_FROZEN = 1 -local TABLE_DRAW_CHANNEL_NOCLIP = 2 -- When using ImGuiTableFlags_NoClip (this becomes the last visible channel) +local TABLE_DRAW_CHANNEL_NOCLIP = 2 -- When using ImGuiTableFlags.NoClip (this becomes the last visible channel) local TABLE_BORDER_SIZE = 1.0 -- FIXME-TABLE: Currently hard-coded because of clipping assumptions with outer borders rendering. local TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0 -- Extend outside inner borders. local TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06 -- Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped. @@ -190,7 +394,7 @@ local function TableFixFlags(flags, outer_window) flags = bor(flags, (band(flags, ImGuiTableFlags.ScrollX) ~= 0 or band(outer_window.Flags, ImGuiWindowFlags.AlwaysAutoResize) ~= 0) and ImGuiTableFlags.SizingFixedFit or ImGuiTableFlags.SizingStretchSame) end - -- Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags_SizingFixedSame + -- Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags.SizingFixedSame if band(flags, ImGuiTableFlags.SizingMask_) == ImGuiTableFlags.SizingFixedSame then flags = bor(flags, ImGuiTableFlags.NoKeepColumnsVisible) end @@ -270,6 +474,12 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi end -- If an outer size is specified ahead we will be able to early out when not visible. Exact clipping criteria may evolve. + -- FIXME: coarse clipping because access to table data causes two issues: + -- - instance numbers varying/unstable. may not be a direct problem for users, but could make outside access broken or confusing, e.g. TestEngine. + -- - can't implement support for ImGuiChildFlags.ResizeY as we need to somehow pull the height data from somewhere. this also needs stable instance numbers. + -- The side-effects of accessing table data on coarse clip would be: + -- - always reserving the pooled ImGuiTable data ahead for a fully clipped table (minor IMHO). Also the 'outer_window_is_measuring_size' criteria may already be defeating this in some situations. + -- - always performing the GetOrAddByKey() O(log N) query in g.Tables.Map[]. local use_child_window = band(flags, bor(ImGuiTableFlags.ScrollX, ImGuiTableFlags.ScrollY)) ~= 0 local avail_size = ImGui.GetContentRegionAvail() local actual_outer_size = ImTrunc(ImGui.CalcItemSize(outer_size, ImMax(avail_size.x, IMGUI_WINDOW_HARD_MIN_SIZE), use_child_window and ImMax(avail_size.y, IMGUI_WINDOW_HARD_MIN_SIZE) or 0.0)) @@ -297,7 +507,7 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi local temp_data = g.TablesTempData.Data[g.TablesTempDataStacked] table_.TempData = temp_data temp_data.TableIndex = table_idx - temp_data.ReconcileColumnsRequests:resize(0) + temp_data.ReconcileColumnsRequests:resize(0) -- FIXME: Use shrink(0) everywhere? table_.DrawSplitter = table_.TempData.DrawSplitter table_.DrawSplitter:Clear() @@ -339,12 +549,16 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi -- When not using a child window, WorkRect.Max will grow as we append contents. if use_child_window then -- Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent + -- (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing) local override_content_size = ImVec2(FLT_MAX, FLT_MAX) if band(flags, ImGuiTableFlags.ScrollX) ~= 0 and band(flags, ImGuiTableFlags.ScrollY) == 0 then override_content_size.y = FLT_MIN end - -- Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and never lead to any scrolling). + -- Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and + -- never lead to any scrolling). We don't handle inner_width < 0.0, we could potentially use it to right-align + -- based on the right side of the child window work rect, which would require knowing ahead if we are going to + -- have decoration taking horizontal spaces (typically a vertical scrollbar). if band(flags, ImGuiTableFlags.ScrollX) ~= 0 and inner_width > 0.0 then override_content_size.x = inner_width end @@ -382,18 +596,19 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi table_.HasScrollbarYCurr = table_.HasScrollbarYCurr or table_.InnerWindow.ScrollbarY else -- For non-scrolling tables, WorkRect == OuterRect == InnerRect. + -- But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable(). ImRect_Copy(table_.WorkRect, outer_rect) ImRect_Copy(table_.OuterRect, outer_rect) ImRect_Copy(table_.InnerRect, outer_rect) table_.HasScrollbarYPrev = false table_.HasScrollbarYCurr = false - table_.InnerWindow.DC.TreeDepth = table_.InnerWindow.DC.TreeDepth + 1 -- This is designed to always linking ImGuiTreeNodeFlags_DrawLines linking across a table + table_.InnerWindow.DC.TreeDepth = table_.InnerWindow.DC.TreeDepth + 1 -- This is designed to always linking ImGuiTreeNodeFlags.DrawLines linking across a table end -- Push a standardized ID for both child-using and not-child-using tables ImGui.PushOverrideID(id) if instance_no > 0 then - ImGui.PushOverrideID(instance_id) + ImGui.PushOverrideID(instance_id) -- FIXME: Somehow this is not resolved by stack-tool, even tho GetIDWithSeed() submitted the symbol. end -- Backup a copy of host window members we will modify @@ -414,7 +629,13 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi inner_window.DC.CurrLineSize.x = 0.0; inner_window.DC.CurrLineSize.y = 0.0 -- Make borders not overlap our contents by offsetting HostClipRect (#6765, #7428, #3752) + -- (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the + -- limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap + -- problem only affect scrolling tables in this case we can get away with doing it without extra cost). if inner_window ~= outer_window then + -- FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window.WindowBorderSize, + -- it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with + -- different x/y values to BeginChild(). local border_size = TABLE_BORDER_SIZE if band(flags, ImGuiTableFlags.BordersOuterV) ~= 0 then table_.HostClipRect.Min.x = ImMin(table_.HostClipRect.Min.x + border_size, table_.HostClipRect.Max.x) @@ -431,6 +652,10 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi end -- Padding and Spacing + -- - None ........Content..... Pad .....Content........ + -- - PadOuter | Pad ..Content..... Pad .....Content.. Pad | + -- - PadInner ........Content.. Pad | Pad ..Content........ + -- - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad | local pad_outer_x if band(flags, ImGuiTableFlags.NoPadOuterX) ~= 0 then pad_outer_x = false elseif band(flags, ImGuiTableFlags.PadOuterX) ~= 0 then pad_outer_x = true @@ -551,9 +776,12 @@ function ImGui.BeginTableEx(name, id, columns_count, flags, outer_size, inner_wi end -- Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call.. + -- This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user. + -- Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option. inner_window.SkipItems = true -- Clear names + -- At this point the .NameOffset field of each column will be invalid until TableUpdateLayout() or the first call to TableSetupColumn() if #table_.ColumnsNames > 0 then table.clear(table_.ColumnsNames) end @@ -581,6 +809,8 @@ end -- Apply queued resizing/reordering/hiding requests function ImGui.TableApplyQueuedRequests(table_) -- Handle resizing request + -- (We process this in the TableBegin() of the first instance of each table) + -- FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling? if table_.InstanceCurrent == 0 then if table_.ResizedColumn ~= -1 and table_.ResizedColumnNextWidth ~= FLT_MAX then ImGui.TableSetColumnWidth(table_.ResizedColumn, table_.ResizedColumnNextWidth) @@ -590,6 +820,7 @@ function ImGui.TableApplyQueuedRequests(table_) table_.ResizedColumn = -1 -- Process auto-fit for single column, which is a special case for stretch columns and fixed columns with FixedSame policy. + -- FIXME-TABLE: Would be nice to redistribute available stretch space accordingly to other weights, instead of giving it all to siblings. if table_.AutoFitSingleColumn ~= -1 then ImGui.TableSetColumnWidth(table_.AutoFitSingleColumn, table_.Columns[table_.AutoFitSingleColumn].WidthAuto) table_.AutoFitSingleColumn = -1 @@ -597,6 +828,7 @@ function ImGui.TableApplyQueuedRequests(table_) end -- Handle reordering request + -- Note: we don't clear ReorderColumn after handling the request (FIXME: clarify why or add a test). if table_.InstanceCurrent == 0 then table_.LastHeldHeaderColumn = table_.HeldHeaderColumn table_.HeldHeaderColumn = -1 @@ -610,6 +842,8 @@ function ImGui.TableApplyQueuedRequests(table_) if g.ActiveId == 0 then -- FIXME: Need to revisit. See 38f5e5a. table_.ReorderColumn = -1 end + --if (table.HeldHeaderColumn == -1 and table.ReorderColumn ~= -1) + -- table.ReorderColumn = -1 end -- Handle display order / visibility reset requests @@ -651,8 +885,10 @@ function ImGui.TableSetColumnDisplayOrder(table_, column_n, dst_order) c.DisplayOrder = c.DisplayOrder - reorder_dir order_n = order_n + reorder_dir end + --IM_ASSERT(dst_column.DisplayOrder == dst_order - reorder_dir) - -- Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[]. Rebuild later from the former. + -- Display order is stored in both columns.IndexDisplayOrder and table.DisplayOrder[]. Rebuild later from the former. + -- FIXME-OPT: If this is called multiple times we'd effectively have a O(N^2) thing going on. for n = 0, table_.ColumnsCount - 1 do table_.DisplayOrderToIndex[table_.Columns[n].DisplayOrder] = n end @@ -666,11 +902,12 @@ local function TableGetMaxDisplayOrderAllowed(table_, src_order, dst_order) end -- Cannot cross over the frozen column limit when interactively reordering. + -- TableSetupScrollFreeze() enforce a display order range for frozen columns. Reordering across the frozen column barrier is illegal and will be undone. if table_.FreezeColumnsRequest > 0 then dst_order = (src_order < table_.FreezeColumnsRequest) and ImMin(dst_order, table_.FreezeColumnsRequest - 1) or ImMax(dst_order, table_.FreezeColumnsRequest) end - -- Cannot cross over a column with the ImGuiTableColumnFlags_NoReorder flag. + -- Cannot cross over a column with the ImGuiTableColumnFlags.NoReorder flag. local reorder_dir = (src_order < dst_order) and 1 or -1 local order_n = src_order while (src_order < dst_order and order_n <= dst_order) or (dst_order < src_order and order_n >= dst_order) do @@ -726,6 +963,11 @@ local function TableSetupColumnFlags(table_, column, column_n, flags_in) flags = bor(flags, (column_n == 0) and ImGuiTableColumnFlags.IndentEnable or ImGuiTableColumnFlags.IndentDisable) end + -- Alignment + --if (flags & ImGuiTableColumnFlags.AlignMask_) == 0 then + -- flags = bor(flags, ImGuiTableColumnFlags.AlignCenter) + --IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags.AlignMask_)) -- Check that only 1 of each set is used. + -- Preserve status flags column.Flags = bor(flags, band(column.Flags, ImGuiTableColumnFlags.StatusMask_)) @@ -748,6 +990,8 @@ end -- Layout columns for the frame. This is in essence the followup to BeginTable() and this is our largest function. -- Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() and other TableSetupXXXXX() functions to be called first. +-- FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns. +-- Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns? function ImGui.TableUpdateLayout(table_) local g = GImGui local temp_data = table_.TempData @@ -787,7 +1031,11 @@ function ImGui.TableUpdateLayout(table_) ImGui.TableApplyQueuedRequests(table_) -- Handle DPI/font resize - local new_ref_scale_unit = g.FontSize + -- This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well. + -- It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition. + -- FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory. + -- This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path. + local new_ref_scale_unit = g.FontSize -- g.Font.GetCharAdvance('A') ? if table_.RefScale ~= 0.0 and table_.RefScale ~= new_ref_scale_unit then local scale_factor = new_ref_scale_unit / table_.RefScale for n = 0, columns_count - 1 do @@ -802,11 +1050,12 @@ function ImGui.TableUpdateLayout(table_) BitArrayClearAll(table_.EnabledMaskByIndex) BitArrayClearAll(table_.EnabledMaskByDisplayOrder) table_.LeftMostEnabledColumn = -1 - table_.MinColumnWidth = ImMax(1.0, g.Style.FramePadding.x * 1.0) -- g.Style.ColumnsMinSpacing; // FIXME-TABLE + table_.MinColumnWidth = ImMax(1.0, g.Style.FramePadding.x * 1.0) -- g.Style.ColumnsMinSpacing -- FIXME-TABLE -- [Part 1] Apply/lock Enabled and Order states. Calculate auto/ideal width for columns. Count fixed/stretch columns. - local count_fixed = 0 - local count_stretch = 0 + -- Process columns in their visible orders as we are building the Prev/Next indices. + local count_fixed = 0 -- Number of columns that have fixed sizing policies + local count_stretch = 0 -- Number of columns that have stretch sizing policies local prev_visible_column_idx = -1 local has_auto_fit_request = false local has_resizable = false @@ -817,6 +1066,8 @@ function ImGui.TableUpdateLayout(table_) local column = table_.Columns[column_n] -- Clear column setup if not submitted by user. Currently we make it mandatory to call TableSetupColumn() every frame. + -- It would easily work without but we're not ready to guarantee it since e.g. names need resubmission anyway. + -- We take a slight shortcut but in theory we could be calling TableSetupColumn() here with dummy values, it should yield the same effect. if table_.DeclColumnsCount <= column_n then TableSetupColumnFlags(table_, column, column_n, ImGuiTableColumnFlags.None) column.NameOffset = -1 @@ -880,6 +1131,7 @@ function ImGui.TableUpdateLayout(table_) IM_ASSERT(column.IndexWithinEnabledSet <= column.DisplayOrder) -- Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping) + -- Combine width from regular rows + width from headers unless requested not to. if not column.IsPreserveWidthAuto and table_.InstanceCurrent == 0 then column.WidthAuto = ImGui.TableGetColumnWidthAuto(table_, column) end @@ -911,7 +1163,9 @@ function ImGui.TableUpdateLayout(table_) table_.RightMostEnabledColumn = prev_visible_column_idx IM_ASSERT(table_.LeftMostEnabledColumn >= 0 and table_.RightMostEnabledColumn >= 0) - -- [Part 2] Disable child window clipping while fitting columns. + -- [Part 2] Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid + -- the column fitting having to wait until the first visible frame of the child container (may or not be a good thing). Also see #6510. + -- FIXME-TABLE: for always auto-resizing columns may not want to do that all the time. if has_auto_fit_request and table_.OuterWindow ~= table_.InnerWindow then table_.InnerWindow.SkipItems = false end @@ -920,8 +1174,8 @@ function ImGui.TableUpdateLayout(table_) end -- [Part 3] Fix column flags and record a few extra information. - local sum_width_requests = 0.0 - local stretch_sum_weights = 0.0 + local sum_width_requests = 0.0 -- Sum of all width for fixed and auto-resize columns, excluding width contributed by Stretch columns but including spacing/padding. + local stretch_sum_weights = 0.0 -- Sum of all weights for stretch columns. table_.LeftMostStretchedColumn = -1; table_.RightMostStretchedColumn = -1 for column_n = 0, columns_count - 1 do if BitTest(table_.EnabledMaskByIndex, column_n) then @@ -936,6 +1190,7 @@ function ImGui.TableUpdateLayout(table_) end -- Apply automatic width + -- Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!) if column.AutoFitQueue ~= 0x00 then column.WidthRequest = width_auto elseif band(column.Flags, ImGuiTableColumnFlags.WidthFixed) ~= 0 and not column_is_resizable and column.IsRequestOutput then @@ -943,6 +1198,11 @@ function ImGui.TableUpdateLayout(table_) end -- FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets + -- (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very + -- large height (= first frame scrollbar display very off + clipper would skip lots of items). + -- This is merely making the side-effect less extreme, but doesn't properly fixes it. + -- FIXME: Move this to .WidthGiven to avoid temporary lossyness? + -- FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller. if column.AutoFitQueue > 0x01 and table_.IsInitializing and not column.IsPreserveWidthAuto then column.WidthRequest = ImMax(column.WidthRequest, table_.MinColumnWidth * 4.0) -- FIXME-TABLE: Another constant/scale? end @@ -994,6 +1254,7 @@ function ImGui.TableUpdateLayout(table_) end -- [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column + -- See additional comments in TableSetColumnWidth(). if column.NextEnabledColumn == -1 and table_.LeftMostStretchedColumn ~= -1 then column.Flags = bor(column.Flags, ImGuiTableColumnFlags.NoDirectResize_) end @@ -1004,7 +1265,8 @@ function ImGui.TableUpdateLayout(table_) end end - -- [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0f * number of Stretch column). + -- [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0 * number of Stretch column). + -- Using right-to-left distribution (more likely to match resizing cursor). if width_remaining_for_stretched_columns >= 1.0 and band(table_.Flags, ImGuiTableFlags.PreciseWidths) == 0 then local order_n = columns_count - 1 while stretch_sum_weights > 0.0 and width_remaining_for_stretched_columns >= 1.0 and order_n >= 0 do @@ -1021,6 +1283,10 @@ function ImGui.TableUpdateLayout(table_) end -- Determine if table is hovered which will be used to flag columns as hovered. + -- - In principle we'd like to use the equivalent of IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem), + -- but because our item is partially submitted at this point we use ItemHoverable() and a workaround (temporarily + -- clear ActiveId, which is equivalent to the change provided by _AllowWhenBLockedByActiveItem). + -- - This allows columns to be marked as hovered when e.g. clicking a button inside the column, or using drag and drop. local table_instance = ImGui.TableGetInstanceData(table_, table_.InstanceCurrent) table_instance.HoveredRowLast = table_instance.HoveredRowNext table_instance.HoveredRowNext = -1 @@ -1040,10 +1306,12 @@ function ImGui.TableUpdateLayout(table_) end -- [Part 6] Setup final position, offset, skip/clip states and clipping rectangles, detect hovered column + -- Process columns in their visible orders as we are comparing the visible order and adjusting host_clip_rect while looping. local has_at_least_one_column_requesting_output = false local offset_x_frozen = (table_.FreezeColumnsCount > 0) local offset_x = ((table_.FreezeColumnsCount > 0) and table_.OuterRect.Min.x or work_rect.Min.x) + table_.OuterPaddingX - table_.CellSpacingX1 local host_clip_rect = Rect(table_.InnerClipRect) + --host_clip_rect.Max.x += table.CellPaddingX + table.CellSpacingX2 BitArrayClearAll(table_.VisibleMaskByIndex) for order_n = 0, columns_count - 1 do local column_n = table_.DisplayOrderToIndex[order_n] @@ -1062,6 +1330,7 @@ function ImGui.TableUpdateLayout(table_) if not BitTest(table_.EnabledMaskByDisplayOrder, order_n) then -- Hidden column: clear a few fields and we are done with it for the remainder of the function. + -- We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper. column.MinX = offset_x; column.MaxX = offset_x; column.WorkMinX = offset_x column.ClipRect.Min.x = offset_x; column.ClipRect.Max.x = offset_x column.WidthGiven = 0.0 @@ -1082,20 +1351,30 @@ function ImGui.TableUpdateLayout(table_) column.MaxX = offset_x + column.WidthGiven + table_.CellSpacingX1 + table_.CellSpacingX2 + table_.CellPaddingX * 2.0 -- Lock other positions + -- - ClipRect.Min.x: Because merging draw commands doesn't compare min boundaries, we make ClipRect.Min.x match left bounds to be consistent regardless of merging. + -- - ClipRect.Max.x: using WorkMaxX instead of MaxX (aka including padding) makes things more consistent when resizing down, tho slightly detrimental to visibility in very-small column. + -- - ClipRect.Max.x: using MaxX makes it easier for header to receive hover highlight with no discontinuity and display sorting arrow. + -- - FIXME-TABLE: We want equal width columns to have equal (ClipRect.Max.x - WorkMinX) width, which means ClipRect.max.x cannot stray off host_clip_rect.Max.x else right-most column may appear shorter. local previous_instance_work_min_x = column.WorkMinX column.WorkMinX = column.MinX + table_.CellPaddingX + table_.CellSpacingX1 column.WorkMaxX = column.MaxX - table_.CellPaddingX - table_.CellSpacingX2 -- Expected max column.ItemWidth = ImTrunc(column.WidthGiven * 0.65) column.ClipRect.Min.x = column.MinX column.ClipRect.Min.y = work_rect.Min.y - column.ClipRect.Max.x = column.MaxX --column->WorkMaxX; + column.ClipRect.Max.x = column.MaxX --column.WorkMaxX column.ClipRect.Max.y = FLT_MAX column.ClipRect:ClipWithFull(host_clip_rect) -- Mark column as Clipped (not in sight) + -- Note that scrolling tables (where inner_window ~= outer_window) handle Y clipped earlier in BeginTable() so IsVisibleY really only applies to non-scrolling tables. + -- FIXME-TABLE: Because InnerClipRect.Max.y is conservatively ==outer_window.ClipRect.Max.y, we never can mark columns _Above_ the scroll line as not IsVisibleY. + -- Taking advantage of LastOuterHeight would yield good results there... + -- FIXME-TABLE: Y clipping is disabled because it effectively means not submitting will reduce contents width which is fed to outer_window.DC.CursorMaxPos.x, + -- and this may be used (e.g. typically by outer_window using AlwaysAutoResize or outer_window's horizontal scrollbar, but could be something else). + -- Possible solution to preserve last known content width for clipped column. Test 'table_reported_size' fails when enabling Y clipping and window is resized small. column.IsVisibleX = (column.ClipRect.Max.x > column.ClipRect.Min.x) - column.IsVisibleY = true -- (column->ClipRect.Max.y > column->ClipRect.Min.y); - local is_visible = column.IsVisibleX --&& column->IsVisibleY; + column.IsVisibleY = true -- (column.ClipRect.Max.y > column.ClipRect.Min.y) + local is_visible = column.IsVisibleX --and column.IsVisibleY if is_visible then BitArraySet(table_.VisibleMaskByIndex, column_n) end @@ -1104,6 +1383,7 @@ function ImGui.TableUpdateLayout(table_) column.IsRequestOutput = is_visible or column.AutoFitQueue ~= 0 or column.CannotSkipItemsQueue ~= 0 -- Mark column as SkipItems (ignoring all items/layout) + -- (table.HostSkipItems is a copy of inner_window.SkipItems before we cleared it above in Part 2) column.IsSkipItems = not column.IsEnabled or table_.HostSkipItems if column.IsSkipItems then IM_ASSERT(not is_visible) @@ -1127,6 +1407,15 @@ function ImGui.TableUpdateLayout(table_) table_.HoveredColumnBody = column_n end + -- Alignment + -- FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in + -- many cases (to be able to honor this we might be able to store a log of cells width, per row, for + -- visible rows, but nav/programmatic scroll would have visible artifacts.) + --if (column.Flags & ImGuiTableColumnFlags.AlignRight) + -- column.WorkMinX = ImMax(column.WorkMinX, column.MaxX - column.ContentWidthRowsUnfrozen) + --else if (column.Flags & ImGuiTableColumnFlags.AlignCenter) + -- column.WorkMinX = ImLerp(column.WorkMinX, ImMax(column.StartX, column.MaxX - column.ContentWidthRowsUnfrozen), 0.5) + -- Reset content width variables if table_.InstanceCurrent == 0 then column.ContentMaxXFrozen = column.WorkMinX @@ -1157,12 +1446,15 @@ function ImGui.TableUpdateLayout(table_) end -- In case the table is visible (e.g. decorations) but all columns clipped, we keep a column visible. + -- Else if give no chance to a clipper-savvy user to submit rows and therefore total contents height used by scrollbar. if has_at_least_one_column_requesting_output == false then table_.Columns[table_.LeftMostEnabledColumn].IsRequestOutput = true table_.Columns[table_.LeftMostEnabledColumn].IsSkipItems = false end -- [Part 7] Detect/store when we are hovering the unused space after the right-most column (so e.g. context menus can react on it) + -- Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either + -- because of using _WidthAuto/_WidthStretch). This will hide the resizing option from the context menu. local unused_x1 = ImMax(table_.WorkRect.Min.x, table_.Columns[table_.RightMostEnabledColumn].ClipRect.Max.x) if is_hovering_table and table_.HoveredColumnBody == -1 then if mouse_skewed_x >= unused_x1 then @@ -1176,6 +1468,8 @@ function ImGui.TableUpdateLayout(table_) table_.IsActiveIdAliveBeforeTable = (g.ActiveIdIsAlive ~= 0) -- [Part 8] Lock actual OuterRect/WorkRect right-most position. + -- This is done late to handle the case of fixed-columns tables not claiming more widths that they need. + -- Because of this we are careful with uses of WorkRect and InnerClipRect before this point. if table_.RightMostStretchedColumn ~= -1 then table_.Flags = band(table_.Flags, bnot(ImGuiTableFlags.NoHostExtendX)) end @@ -1218,12 +1512,17 @@ function ImGui.TableUpdateLayout(table_) end -- [Part 11] Default context menu + -- - To append to this menu: you can 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 and ImGui.TableBeginContextMenuPopup(table_) then ImGui.TableDrawDefaultContextMenu(table_, table_.Flags) ImGui.EndPopup() end -- [Part 12] Sanitize and build sort specs before we have a chance to use them for display. + -- This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change) if table_.IsSortSpecsDirty and band(table_.Flags, ImGuiTableFlags.Sortable) ~= 0 then ImGui.TableSortSpecsBuild(table_) end @@ -1247,7 +1546,7 @@ function ImGui.TableUpdateLayout(table_) if band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0 then table_.DrawSplitter:SetCurrentChannel(inner_window.DrawList, TABLE_DRAW_CHANNEL_NOCLIP) else - inner_window.DrawList:PushClipRect(inner_window.InnerClipRect.Min, inner_window.InnerClipRect.Max, false) -- FIXME: use table->InnerClipRect? + inner_window.DrawList:PushClipRect(inner_window.InnerClipRect.Min, inner_window.InnerClipRect.Max, false) -- FIXME: use table.InnerClipRect? end end @@ -1267,10 +1566,15 @@ function ImGui.TableApplyExternalUnclipRect(table_, rect) end -- Process hit-testing on resizing borders. Actual size change will be applied in EndTable() +-- - Set table.HoveredColumnBorder with a short delay/timer to reduce visual feedback noise. function ImGui.TableUpdateBorders(table_) local g = GImGui IM_ASSERT(band(table_.Flags, ImGuiTableFlags.Resizable) ~= 0) + -- At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and + -- use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not + -- really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height). + -- Actual columns highlight/render will be performed in EndTable() and not be affected. local table_instance = ImGui.TableGetInstanceData(table_, table_.InstanceCurrent) local hit_half_width = ImTrunc(TABLE_RESIZE_SEPARATOR_HALF_THICKNESS * g.CurrentDpiScale) local hit_y1 = ((table_.FreezeRowsCount >= 1) and table_.OuterRect.Min.y or table_.WorkRect.Min.y) + table_.AngledHeadersHeight @@ -1289,7 +1593,7 @@ function ImGui.TableUpdateBorders(table_) break end - -- ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders() + -- ImGuiTableFlags.NoBordersInBodyUntilResize will be honored in TableDrawBorders() local border_y2_hit = (band(table_.Flags, ImGuiTableFlags.NoBordersInBody) ~= 0) and hit_y2_head or hit_y2_body if band(table_.Flags, ImGuiTableFlags.NoBordersInBody) ~= 0 and table_.IsUsingHeaders == false then break @@ -1302,6 +1606,7 @@ function ImGui.TableUpdateBorders(table_) local column_id = ImGui.TableGetColumnResizeID(table_, column_n, table_.InstanceCurrent) local hit_rect = ImRect(column.MaxX - hit_half_width, hit_y1, column.MaxX + hit_half_width, border_y2_hit) ImGui.ItemAdd(hit_rect, column_id, nil, ImGuiItemFlags.NoNav) + --ImGui.GetForegroundDrawList():AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100)) local pressed, hovered, held = ImGui.ButtonBehavior(hit_rect, column_id, bor(ImGuiButtonFlags.FlattenChildren, ImGuiButtonFlags.PressedOnClick, ImGuiButtonFlags.PressedOnDoubleClick, ImGuiButtonFlags.NoNavFocus)) if pressed and ImGui.IsMouseDoubleClicked(0) then @@ -1329,7 +1634,12 @@ function ImGui.EndTable() local table_ = g.CurrentTable IM_ASSERT_USER_ERROR_RET(table_ ~= nil, "EndTable() call should only be done while in BeginTable() scope!") - -- If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves. + -- This assert would be very useful to catch a common error... unfortunately it would probably trigger in some + -- cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border) + --IM_ASSERT(table.IsLayoutLocked, "Table unused: never called TableNextRow(), is that the intent?") + + -- If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our + -- code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc. if not table_.IsLayoutLocked then ImGui.TableUpdateLayout(table_) end @@ -1357,7 +1667,7 @@ function ImGui.EndTable() ImVec2_Copy(inner_window.DC.PrevLineSize, temp_data.HostBackupPrevLineSize) ImVec2_Copy(inner_window.DC.CurrLineSize, temp_data.HostBackupCurrLineSize) ImVec2_Copy(inner_window.DC.CursorMaxPos, temp_data.HostBackupCursorMaxPos) - local inner_content_max_y = ImCeil(table_.RowPosY2) -- Rounding final position is important as we currently don't round row height + local inner_content_max_y = ImCeil(table_.RowPosY2) -- Rounding final position is important as we currently don't round row height ('Demo->Tables->Outer Size' demo uses non-integer heights) IM_ASSERT(table_.RowPosY2 == inner_window.DC.CursorPos.y) if inner_window ~= outer_window then inner_window.DC.CursorMaxPos.y = inner_content_max_y @@ -1369,6 +1679,8 @@ function ImGui.EndTable() table_instance.LastOuterHeight = table_.OuterRect:GetHeight() -- Setup inner scrolling range + -- FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window.DC.CursorMaxPos.y, + -- but since the later is likely to be impossible to do we'd rather update both axes together. if band(table_.Flags, ImGuiTableFlags.ScrollX) ~= 0 then local outer_padding_for_border = (band(table_.Flags, ImGuiTableFlags.BordersOuterV) ~= 0) and TABLE_BORDER_SIZE or 0.0 local max_pos_x = inner_window.DC.CursorMaxPos.x @@ -1469,6 +1781,8 @@ function ImGui.EndTable() outer_window.DC.ColumnsOffset.x = temp_data.HostBackupColumnsOffset -- Layout in outer window + -- (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding + -- CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414) if inner_window ~= outer_window then local backup_nav_layers_active_mask = inner_window.DC.NavLayersActiveMask inner_window.DC.NavLayersActiveMask = bor(inner_window.DC.NavLayersActiveMask, lshift(1, table_.NavLayer)) -- So empty table don't appear to navigate differently. @@ -1484,9 +1798,13 @@ function ImGui.EndTable() -- Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar if band(table_.Flags, ImGuiTableFlags.NoHostExtendX) ~= 0 then + -- FIXME-TABLE: Could we remove this section? + -- ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents IM_ASSERT(band(table_.Flags, ImGuiTableFlags.ScrollX) == 0) outer_window.DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table_.OuterRect.Min.x + table_.ColumnsAutoFitWidth) elseif temp_data.UserOuterSize.x <= 0.0 then + -- Some references for this: #7651 + tests "table_reported_size", "table_reported_size_outer" equivalent Y block, #9352 + -- - FIXME-TABLE: Would make sense to pre-compute expected scrollbar visibility/sizes to generally save a frame of feedback? See broken test in 'table_reported_size_outer' local outer_content_max_x = table_.OuterRect.Min.x + table_.ColumnsAutoFitWidth local decoration_size = table_.TempData.AngledHeadersExtraWidth + ((inner_window ~= outer_window) and inner_window.ScrollbarSizes.x or 0.0) outer_window.DC.IdealMaxPos.x = ImMax(outer_window.DC.IdealMaxPos.x, outer_content_max_x + decoration_size - temp_data.UserOuterSize.x) @@ -1495,13 +1813,14 @@ function ImGui.EndTable() outer_window.DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table_.OuterRect.Max.x) end if temp_data.UserOuterSize.y <= 0.0 then + -- (same comment as above) local outer_content_size_y = (inner_window == outer_window) and (inner_content_max_y - table_.InnerRect.Min.y) or (inner_content_max_y - inner_window.DC.CursorStartPos.y) local outer_content_max_y = table_.OuterRect.Min.y + outer_content_size_y local decoration_size = (inner_window ~= outer_window) and inner_window.ScrollbarSizes.y or 0.0 outer_window.DC.IdealMaxPos.y = ImMax(outer_window.DC.IdealMaxPos.y, outer_content_max_y + decoration_size - temp_data.UserOuterSize.y) outer_window.DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, ImMin(table_.OuterRect.Max.y, outer_content_max_y + decoration_size)) else - -- OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set) + -- OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags.NoHostExtendY is set) outer_window.DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, table_.OuterRect.Max.y) end @@ -1557,16 +1876,18 @@ function ImGui.TableInitColumnDefaults(table_, column, column_n, init_mask) end -- See "COLUMNS SIZING POLICIES" comments at the top of this file --- If (init_width_or_weight <= 0.0f) it is ignored +-- If (init_width_or_weight <= 0.0) it is ignored local function TableSetupColumnApply(table_, idx, id, name_offset, flags, init_width_or_weight, user_data) local column = table_.Columns[idx] -- Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa. + -- Give a grace to users of ImGuiTableFlags.ScrollX. if table_.IsDefaultSizingPolicy and band(flags, ImGuiTableColumnFlags.WidthMask_) == 0 and band(flags, ImGuiTableFlags.ScrollX) == 0 then IM_ASSERT_USER_ERROR_RET(init_width_or_weight <= 0.0, "TableSetupColumn(): can only specify width/weight if sizing policy is set explicitly in either Table or Column.") end -- When passing a width automatically enforce WidthFixed policy + -- (whereas TableSetupColumnFlags would default to WidthAuto if table is not resizable) if band(flags, ImGuiTableColumnFlags.WidthMask_) == 0 and init_width_or_weight > 0.0 then if band(table_.Flags, ImGuiTableFlags.SizingMask_) == ImGuiTableFlags.SizingFixedFit or band(table_.Flags, ImGuiTableFlags.SizingMask_) == ImGuiTableFlags.SizingFixedSame then flags = bor(flags, ImGuiTableColumnFlags.WidthFixed) @@ -1597,10 +1918,11 @@ function ImGui.TableSetupColumn(label, flags, init_width_or_weight, user_data) local table_ = g.CurrentTable IM_ASSERT_USER_ERROR_RET(table_ ~= nil, "Call should only be done while in BeginTable() scope!") IM_ASSERT_USER_ERROR_RET(table_.DeclColumnsCount < table_.ColumnsCount, "TableSetupColumn(): called too many times!") - IM_ASSERT_USER_ERROR_RET(table_.IsLayoutLocked == false, "TableSetupColumn(): need to call before first row!") + IM_ASSERT_USER_ERROR_RET(table_.IsLayoutLocked == false, "TableSetupColumn(): need to call before first row!") -- Table layout is locked when submitting a row or when calling BeginMultiSelect() with box-select. IM_ASSERT(band(flags, ImGuiTableColumnFlags.StatusMask_) == 0, "Illegal to pass StatusMask values to TableSetupColumn()") -- Store name + -- FIXME: If we recorded the number of \n in names we could compute header row height local name_offset = -1 if label ~= nil and label ~= "" then name_offset = #table_.ColumnsNames @@ -1630,6 +1952,9 @@ function ImGui.TableSetupColumn(label, flags, init_width_or_weight, user_data) end -- Reconcile path: defer applying data to TableUpdateLayout() -> TableReconcileMovedColumns() -> TableSetupColumnApply(). + -- On column count change: search the previous columns: + -- - the live Columns[] array is truncated on shrink, so a moved column may only exist in old data. + -- - the live Columns[] array may already be partially reset. local reconcile_data = { ID = column_id, NameOffset = name_offset, Flags = flags, InitWidthOrWeight = init_width_or_weight, UserData = user_data, ColumnNewIdx = column_idx, ColumnOldIdx = -1, ColumnOldData = ImGuiTableColumn(), @@ -1694,9 +2019,9 @@ function ImGui.TableReconcileColumns(table_) end end - -- Apply in the final pass. Because it is possible that src_columns == table->Columns we went through a temporary copy. + -- Apply in the final pass. Because it is possible that src_columns == table.Columns we went through a temporary copy. for _, reconcile_data in reconcile_requests:iter() do - TableColumnCopy(table_.Columns[reconcile_data.ColumnNewIdx], reconcile_data.ColumnOldData) + TableColumnCopy(table_.Columns[reconcile_data.ColumnNewIdx], reconcile_data.ColumnOldData) -- When old column was not found clear anyway with default-constructed data (which will set IsJustCreated=true) TableSetupColumnApply(table_, reconcile_data.ColumnNewIdx, reconcile_data.ID, reconcile_data.NameOffset, reconcile_data.Flags, reconcile_data.InitWidthOrWeight, reconcile_data.UserData) end ImGui.TableFixDisplayOrder(table_) @@ -1721,10 +2046,25 @@ function ImGui.TableSetupScrollFreeze(columns, rows) table_.IsUnfrozenRows = (table_.FreezeRowsCount == 0) -- Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it. end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Simple accessors ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetColumnCount() +-- - TableGetColumnName() +-- - TableGetColumnName() [Internal] +-- - TableSetColumnEnabled() +-- - TableGetColumnFlags() +-- - TableGetCellBgRect() [Internal] +-- - TableGetColumnResizeID() [Internal] +-- - TableGetHoveredColumn() [Internal] +-- - TableGetHoveredRow() [Internal] +-- - TableSetBgColor() +------------------------------------------------------------------------------- +-- [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences, +-- they would meddle many times with the underlying ImDrawCmd. +-- Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let +-- the subsequent single call to SetCurrentChannel() does it things once. function ImGui.SetWindowClipRectBeforeSetChannel(window, clip_rect) local clip_rect_vec4 = clip_rect:ToVec4() ImRect_Copy(window.ClipRect, clip_rect) @@ -1765,6 +2105,11 @@ function ImGui.TableGetColumnName(a, b) end -- Change user accessible enabled/disabled state of a column (often perceived as "showing/hiding" from users point of view) +-- Note that end-user can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags.ContextMenuInBody) +-- - Require table to have the ImGuiTableFlags.Hideable flag because we are manipulating user accessible state. +-- - Request will be applied during next layout, which happens on the first call to TableNextRow() after BeginTable(). +-- - For the getter you can test (TableGetColumnFlags() & ImGuiTableColumnFlags.IsEnabled) ~= 0. +-- - Alternative: the ImGuiTableColumnFlags.Disabled is an overriding/master disable flag which will also hide the column from context menu. function ImGui.TableSetColumnEnabled(column_n, enabled) local g = GImGui local table_ = g.CurrentTable @@ -1796,10 +2141,19 @@ function ImGui.TableGetColumnFlags(column_n) end -- Return the cell rectangle based on currently known height. +-- - Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations. +-- The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it, or in TableEndRow() when we locked that height. +-- - Important: if ImGuiTableFlags.PadOuterX is set but ImGuiTableFlags.PadInnerX is not set, the outer-most left and right +-- columns report a small offset so their CellBgRect can extend up to the outer border. +-- FIXME: But the rendering code in TableEndRow() nullifies that with clamping required for scrolling. function ImGui.TableGetCellBgRect(table_, column_n) local column = table_.Columns[column_n] local x1 = column.MinX local x2 = column.MaxX + --if column.PrevEnabledColumn == -1 then + -- x1 = x1 - table.OuterPaddingX + --if column.NextEnabledColumn == -1 then + -- x2 = x2 + table.OuterPaddingX x1 = ImMax(x1, table_.WorkRect.Min.x) x2 = ImMin(x2, table_.WorkRect.Max.x) return ImRect(x1, table_.RowPosY1, x2, table_.RowPosY2) @@ -1824,6 +2178,8 @@ function ImGui.TableGetHoveredColumn() end -- Return -1 when table is not hovered. Return maxrow+1 if in table but below last submitted row. +-- *IMPORTANT* Unlike TableGetHoveredColumn(), this has a one frame latency in updating the value. +-- This difference with is the reason why this is not public yet. function ImGui.TableGetHoveredRow() local g = GImGui local table_ = g.CurrentTable @@ -1874,11 +2230,16 @@ function ImGui.TableSetBgColor(target, color, column_n) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Row changes ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetRowIndex() +-- - TableNextRow() +-- - TableBeginRow() [Internal] +-- - TableEndRow() [Internal] +------------------------------------------------------------------------------- --- [Public] Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows +-- [Public] Note: for row coloring we use .RowBgColorCounter which is the same value without counting header rows function ImGui.TableGetRowIndex() local g = GImGui local table_ = g.CurrentTable @@ -1946,7 +2307,7 @@ function ImGui.TableBeginRow(table_) window.DC.PrevLineTextBaseOffset = 0.0 window.DC.CursorPosPrevLine.x = window.DC.CursorPos.x window.DC.CursorPosPrevLine.y = window.DC.CursorPos.y + table_.RowCellPaddingY -- This allows users to call SameLine() to share LineSize between columns. - window.DC.PrevLineSize.x = 0.0; window.DC.PrevLineSize.y = 0.0 + window.DC.PrevLineSize.x = 0.0; window.DC.PrevLineSize.y = 0.0 -- This allows users to call SameLine() to share LineSize between columns, and to call it from first column too. window.DC.CurrLineSize.x = 0.0; window.DC.CurrLineSize.y = 0.0 window.DC.IsSameLine = false; window.DC.IsSetPos = false window.DC.CursorMaxPos.y = next_y1 @@ -1977,7 +2338,8 @@ function ImGui.TableEndRow(table_) ImGui.LogRenderedText(nil, "|") end - -- Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. + -- Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is + -- likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding. window.DC.CursorPos.y = table_.RowPosY2 -- Row background fill @@ -2045,6 +2407,7 @@ function ImGui.TableEndRow(table_) for cell_n = 0, table_.RowCellDataCurrent do local cell_data = table_.RowCellData[cell_n] -- As we render the BG here we need to clip things (for layout we would not) + -- FIXME: This cancels the OuterPadding addition done by TableGetCellBgRect(), need to keep it while rendering correctly while scrolling. local column = table_.Columns[cell_data.Column] local cell_bg_rect = ImGui.TableGetCellBgRect(table_, cell_data.Column) cell_bg_rect:ClipWith(table_.BgClipRect) @@ -2068,6 +2431,8 @@ function ImGui.TableEndRow(table_) end -- End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle) + -- - We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark + -- end of row and get the new cursor position. if unfreeze_rows_request then IM_ASSERT(table_.FreezeRowsRequest > 0) for column_n = 0, table_.ColumnsCount - 1 do @@ -2080,7 +2445,7 @@ function ImGui.TableEndRow(table_) IM_ASSERT(table_.IsUnfrozenRows == false) table_.IsUnfrozenRows = true - -- BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect + -- BgClipRect starts as table.InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect local min_y = ImMin(y0, table_.InnerClipRect.Max.y) table_.BgClipRect.Min.y = min_y; table_.Bg2ClipRectForDrawCmd.Min.y = min_y table_.BgClipRect.Max.y = table_.InnerClipRect.Max.y; table_.Bg2ClipRectForDrawCmd.Max.y = table_.InnerClipRect.Max.y @@ -2097,7 +2462,7 @@ function ImGui.TableEndRow(table_) column.ClipRect.Min.y = table_.Bg2ClipRectForDrawCmd.Min.y end - -- Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y + -- Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect.Min.y ImGui.SetWindowClipRectBeforeSetChannel(window, table_.Columns[0].ClipRect) table_.DrawSplitter:SetCurrentChannel(window.DrawList, table_.Columns[0].DrawChannelCurrent) end @@ -2109,9 +2474,15 @@ function ImGui.TableEndRow(table_) table_.IsInsideRow = false end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Columns changes ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetColumnIndex() +-- - TableSetColumnIndex() +-- - TableNextColumn() +-- - TableBeginCell() [Internal] +-- - TableEndCell() [Internal] +------------------------------------------------------------------------------- function ImGui.TableGetColumnIndex() local g = GImGui @@ -2171,6 +2542,7 @@ end -- [Internal] Called by TableSetColumnIndex()/TableNextColumn() -- This is called very frequently, so we need to be mindful of unnecessary overhead. +-- FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns. function ImGui.TableBeginCell(table_, column_n) local g = GImGui local column = table_.Columns[column_n] @@ -2180,7 +2552,7 @@ function ImGui.TableBeginCell(table_, column_n) -- Start position is roughly ~~ CellRect.Min + CellPadding + Indent local start_x = column.WorkMinX if band(column.Flags, ImGuiTableColumnFlags.IndentEnable) ~= 0 then - start_x = start_x + table_.RowIndentOffsetX -- ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row. + start_x = start_x + table_.RowIndentOffsetX -- ~~ += window.DC.Indent.x - table.HostIndentX, except we locked it for the row. end window.DC.CursorPos.x = start_x @@ -2207,6 +2579,7 @@ function ImGui.TableBeginCell(table_, column_n) if band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0 then -- FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed. table_.DrawSplitter:SetCurrentChannel(window.DrawList, TABLE_DRAW_CHANNEL_NOCLIP) + --IM_ASSERT(table.DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP) else -- FIXME-TABLE: Could avoid this if draw channel is dummy channel? ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect) @@ -2244,27 +2617,43 @@ function ImGui.TableEndCell(table_) column.ItemWidth = window.DC.ItemWidth -- Propagate text baseline for the entire row + -- FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one. table_.RowTextBaseline = ImMax(table_.RowTextBaseline, window.DC.PrevLineTextBaseOffset) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Columns width management ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetMaxColumnWidth() [Internal] +-- - TableGetColumnWidthAuto() [Internal] +-- - TableSetColumnWidth() +-- - TableSetColumnWidthAutoSingle() [Internal] +-- - TableSetColumnWidthAutoAll() [Internal] +-- - TableUpdateColumnsWeightFromWidth() [Internal] +------------------------------------------------------------------------------- +-- Note that actual columns widths are computed in TableUpdateLayout(). +------------------------------------------------------------------------------- --- Maximum column content width given current layout. Use column->MinX so this value differs on a per-column basis. +-- Maximum column content width given current layout. Use column.MinX so this value differs on a per-column basis. function ImGui.TableCalcMaxColumnWidth(table_, column_n) local column = table_.Columns[column_n] local max_width = FLT_MAX local min_column_distance = table_.MinColumnWidth + table_.CellPaddingX * 2.0 + table_.CellSpacingX1 + table_.CellSpacingX2 if band(table_.Flags, ImGuiTableFlags.ScrollX) ~= 0 then -- Frozen columns can't reach beyond visible width else scrolling will naturally break. + -- (we use DisplayOrder as within a set of multiple frozen column reordering is possible) if column.DisplayOrder < table_.FreezeColumnsRequest then max_width = (table_.InnerClipRect.Max.x - (table_.FreezeColumnsRequest - column.DisplayOrder) * min_column_distance) - column.MinX max_width = max_width - table_.OuterPaddingX - table_.CellPaddingX - table_.CellSpacingX2 end elseif band(table_.Flags, ImGuiTableFlags.NoKeepColumnsVisible) == 0 then - -- If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make sure they are all visible. + -- If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make + -- sure they are all visible. Because of this we also know that all of the columns will always fit in + -- table.WorkRect and therefore in table.InnerRect (because ScrollX is off) + -- FIXME-TABLE: This is solved incorrectly but also quite a difficult problem to fix as we also want ClipRect width to match. + -- See "table_width_distrib" and "table_width_keep_visible" tests max_width = table_.WorkRect.Max.x - (table_.ColumnsEnabledCount - column.IndexWithinEnabledSet - 1) * min_column_distance - column.MinX + --max_width = max_width - table.CellSpacingX1 max_width = max_width - table_.CellSpacingX2 max_width = max_width - table_.CellPaddingX * 2.0 max_width = max_width - table_.OuterPaddingX @@ -2272,7 +2661,7 @@ function ImGui.TableCalcMaxColumnWidth(table_, column_n) return max_width end --- Note this is meant to be stored in column->WidthAuto, please generally use the WidthAuto field +-- Note this is meant to be stored in column.WidthAuto, please generally use the WidthAuto field function ImGui.TableGetColumnWidthAuto(table_, column) local content_width_body = ImMax(column.ContentMaxXFrozen, column.ContentMaxXUnfrozen) - column.WorkMinX local content_width_headers = column.ContentMaxXHeadersIdeal - column.WorkMinX @@ -2301,6 +2690,7 @@ function ImGui.TableSetColumnWidth(column_n, width) local column_0_width = width -- Apply constraints early + -- Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded) IM_ASSERT(table_.MinColumnWidth > 0.0) local min_width = table_.MinColumnWidth local max_width = ImMax(min_width, column_0.WidthMax) -- Don't use TableCalcMaxColumnWidth() here as it would rely on MinX from last instance (#7933) @@ -2309,8 +2699,41 @@ function ImGui.TableSetColumnWidth(column_n, width) return end + --IMGUI_DEBUG_PRINT("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0.WidthGiven, column_0_width) local column_1 = (column_0.NextEnabledColumn ~= -1) and table_.Columns[column_0.NextEnabledColumn] or nil + -- In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns. + -- - All fixed: easy. + -- - All stretch: easy. + -- - One or more fixed + one stretch: easy. + -- - One or more fixed + more than one stretch: tricky. + -- Qt when manual resize is enabled only supports a single _trailing_ stretch column, we support more cases here. + + -- When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1. + -- FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user. + -- Scenarios: + -- - F1 F2 F3 resize from F1| or F2| --> ok: alter .WidthRequested of Fixed column. Subsequent columns will be offset. + -- - F1 F2 F3 resize from F3| --> ok: alter .WidthRequested of Fixed column. If active, ScrollX extent can be altered. + -- - F1 F2 W3 resize from F1| or F2| --> ok: alter .WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size. + -- - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 W2 W3 resize from W1| or W2| --> ok + -- - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1) + -- - W1 W2 F3 resize from W1| or W2| --> ok + -- - W1 F2 W3 resize from W1| or F2| --> ok + -- - F1 W2 F3 resize from W2| --> ok + -- - F1 W3 F2 resize from W3| --> ok + -- - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move. + -- - W1 F2 F3 resize from F2| --> ok + -- All resizes from a Wx columns are locking other columns. + + -- Possible improvements: + -- - W1 W2 W3 resize W1| --> to not be stuck, both W2 and W3 would stretch down. Seems possible to fix. Would be most beneficial to simplify resize of all-weighted columns. + -- - W3 F1 F2 resize W3| --> to not be stuck past F1|, both F1 and F2 would need to stretch down, which would be lossy or ambiguous. Seems hard to fix. + + -- [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout(). + -- If we have all Fixed columns OR resizing a Fixed column that doesn't come after a Stretch one, we can do an offsetting resize. -- This is the preferred resize path if band(column_0.Flags, ImGuiTableColumnFlags.WidthFixed) ~= 0 then @@ -2343,6 +2766,7 @@ function ImGui.TableSetColumnWidth(column_n, width) end -- Disable clipping then auto-fit, will take 2 frames +-- (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns) function ImGui.TableSetColumnWidthAutoSingle(table_, column_n) -- Single auto width uses auto-fit local column = table_.Columns[column_n] @@ -2389,11 +2813,24 @@ function ImGui.TableUpdateColumnsWeightFromWidth(table_) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Drawing ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TablePushBackgroundChannel() [Internal] +-- - TablePopBackgroundChannel() [Internal] +-- - TableSetupDrawChannels() [Internal] +-- - TableMergeDrawChannels() [Internal] +-- - TableGetColumnBorderCol() [Internal] +-- - TableDrawBorders() [Internal] +------------------------------------------------------------------------------- + + +-- FIXME: This could be abstracted and merged with PushColumnsBackground(), by creating a generic struct +-- with storage for backup cliprect + backup channel + storage for splitter pointer, new clip rect. +-- This would slightly simplify caller code. -- Bg2 is used by Selectable (and possibly other widgets) to render to the background. +-- Unlike our Bg0/1 channel which we uses for RowBg/CellBg/Borders and where we guarantee all shapes to be CPU-clipped, the Bg2 channel being widgets-facing will rely on regular ClipRect. function ImGui.TablePushBackgroundChannel() local g = GImGui local window = g.CurrentWindow @@ -2445,6 +2882,21 @@ function ImGui.TablePopColumnChannel() end -- Allocate draw channels. Called by TableUpdateLayout() +-- - We allocate them following storage order instead of display order so reordering columns won't needlessly +-- increase overall dormant memory cost. +-- - We isolate headers draw commands in their own channels instead of just altering clip rects. +-- This is in order to facilitate merging of draw commands. +-- - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels. +-- - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other +-- channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged. +-- - We allocate 1 or 2 background draw channels. This is because we know TablePushBackgroundChannel() is only used for +-- horizontal spanning. If we allowed vertical spanning we'd need one background draw channel per merge group (1-4). +-- Draw channel allocation (before merging): +-- - NoClip --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call) +-- - Clip --> 2+D+N channels +-- - FreezeRows --> 2+D+N*2 (unless scrolling value is zero) +-- - FreezeRows || FreezeColumns --> 3+D+N*2 (unless scrolling value is zero) +-- Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0. function ImGui.TableSetupDrawChannels(table_) local freeze_row_multiplier = (table_.FreezeRowsCount > 0) and 2 or 1 local channels_for_row = (band(table_.Flags, ImGuiTableFlags.NoClip) ~= 0) and 1 or table_.ColumnsEnabledCount @@ -2480,6 +2932,8 @@ function ImGui.TableSetupDrawChannels(table_) end -- Initial draw cmd starts with a BgClipRect that matches the one of its host, to facilitate merge draw commands by default. + -- All our cell highlight are manually clipped with BgClipRect. When unfreezing it will be made smaller to fit scrolling rect. + -- (This technically isn't part of setting up draw channels, but is reasonably related to be done here) ImRect_Copy(table_.BgClipRect, table_.InnerClipRect) ImRect_Copy(table_.Bg0ClipRectForDrawCmd, table_.OuterWindow.ClipRect) ImRect_Copy(table_.Bg2ClipRectForDrawCmd, table_.HostClipRect) @@ -2487,6 +2941,34 @@ function ImGui.TableSetupDrawChannels(table_) end -- This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable(). +-- For simplicity we call it TableMergeDrawChannels() but in fact it only reorder channels + overwrite ClipRect, +-- actual merging is done by table.DrawSplitter:Merge() which is called right after TableMergeDrawChannels(). +-- +-- Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve +-- this we merge their clip rect and make them contiguous in the channel list, so they can be merged +-- by the call to DrawSplitter:Merge() following to the call to this function. +-- We reorder draw commands by arranging them into a maximum of 4 distinct groups: +-- +-- 1 group: 2 groups: 2 groups: 4 groups: +-- [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze +-- [ .. ] or no scroll [ 2. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll +-- +-- Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled). +-- When the contents of a column didn't stray off its limit, we move its channels into the corresponding group +-- based on its position (within frozen rows/columns groups or not). +-- At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect. +-- This function assume that each column are pointing to a distinct draw channel, +-- otherwise merge_group.ChannelsCount will not match set bit count of merge_group.ChannelsMask. +-- +-- Column channels will not be merged into one of the 1-4 groups in the following cases: +-- - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value). +-- Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui.* bounds +-- matches, by e.g. calling SetCursorScreenPos(). +-- - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here.. +-- we could do better but it's going to be rare and probably not worth the hassle. +-- Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd. +-- +-- This function is particularly tricky to understand.. take a breath. -- (Lua: splitter channel n lives in splitter._Channels.Data[n + 1]; bit arrays are Lua sets) function ImGui.TableMergeDrawChannels(table_) local splitter = table_.DrawSplitter @@ -2525,6 +3007,7 @@ function ImGui.TableMergeDrawChannels(table_) end -- Find out the width of this merge group and check if it will fit in our column + -- (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it) if band(column.Flags, ImGuiTableColumnFlags.NoClip) == 0 then local content_max_x if not has_freeze_v then @@ -2554,6 +3037,7 @@ function ImGui.TableMergeDrawChannels(table_) end -- Invalidate current draw channel + -- (we don't clear DrawChannelFrozen/DrawChannelUnfrozen solely to facilitate debugging/later inspection of data) column.DrawChannelCurrent = -1 end end @@ -2569,6 +3053,7 @@ function ImGui.TableMergeDrawChannels(table_) remaining_mask[table_.Bg2DrawChannelUnfrozen] = nil IM_ASSERT(has_freeze_v == false or table_.Bg2DrawChannelUnfrozen ~= TABLE_DRAW_CHANNEL_BG2_FROZEN) local remaining_count = splitter._Count - (has_freeze_v and (LEADING_DRAW_CHANNELS + 1) or LEADING_DRAW_CHANNELS) + --local host_rect = (table.InnerWindow == table.OuterWindow) and table.InnerClipRect or table.HostClipRect local host_rect = table_.HostClipRect for merge_group_n = 0, 3 do local merge_channels_count = merge_groups[merge_group_n].ChannelsCount @@ -2578,6 +3063,11 @@ function ImGui.TableMergeDrawChannels(table_) -- Extend outer-most clip limits to match those of host, so draw calls can be merged even if -- outer-most columns have some outer padding offsetting them from their parent ClipRect. + -- The principal cases this is dealing with are: + -- - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge + -- - Columns can use padding and have left-most ClipRect.Min.x and right-most ClipRect.Max.x != from host ClipRect -> will extend and match host ClipRect -> will merge + -- FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit + -- within host clip rect, solely because of the half-padding difference between window.WorkRect and window.InnerClipRect. if band(merge_group_n, 1) == 0 or not has_freeze_h then merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x) end @@ -2590,6 +3080,9 @@ function ImGui.TableMergeDrawChannels(table_) if band(merge_group_n, 2) ~= 0 and band(table_.Flags, ImGuiTableFlags.NoHostExtendY) == 0 then merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y) end + --ImGui.GetForegroundDrawList():AddRect(merge_group.ClipRect.Min, merge_group.ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0, 0, 1.0) -- [DEBUG] + --ImGui.GetForegroundDrawList():AddLine(merge_group.ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200)) + --ImGui.GetForegroundDrawList():AddLine(merge_group.ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200)) remaining_count = remaining_count - merge_group.ChannelsCount for n in pairs(merge_group.ChannelsMask) do remaining_mask[n] = nil @@ -2706,7 +3199,13 @@ function ImGui.TableDrawBorders(table_) end -- Draw outer border + -- FIXME: could use AddRect or explicit VLine/HLine helper? if band(table_.Flags, ImGuiTableFlags.BordersOuter) ~= 0 then + -- Display outer border offset by 1 which is a simple way to display it without adding an extra draw call + -- (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their + -- parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part + -- of it in inner window, and the part that's over scrollbars in the outer window..) + -- Either solution currently won't allow us to use a larger border size: the border would clipped. local outer_border = table_.OuterRect local outer_col = table_.BorderColorStrong if band(table_.Flags, ImGuiTableFlags.BordersOuter) == ImGuiTableFlags.BordersOuter then @@ -2731,12 +3230,23 @@ function ImGui.TableDrawBorders(table_) inner_drawlist:PopClipRect() end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Sorting ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetSortSpecs() +-- - TableFixColumnSortDirection() [Internal] +-- - TableGetColumnNextSortDirection() [Internal] +-- - TableSetColumnSortDirection() [Internal] +-- - TableSortSpecsSanitize() [Internal] +-- - TableSortSpecsBuild() [Internal] +------------------------------------------------------------------------------- --- Return nil if no sort specs (most often when ImGuiTableFlags_Sortable is not set) --- When 'sort_specs.SpecsDirty == true' you should sort your data. Specs is a 1-based Lua array. +-- Return nil if no sort specs (most often when ImGuiTableFlags.Sortable is not set) +-- When 'sort_specs.SpecsDirty == true' you should sort your data. It will be true when sorting specs have +-- changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, +-- else you may wastefully sort your data every frame! +-- Lifetime: don't hold on this table over multiple frames or past any subsequent call to BeginTable()! +-- PORT: Specs is a 1-based Lua array. function ImGui.TableGetSortSpecs() local g = GImGui local table_ = g.CurrentTable @@ -2768,6 +3278,8 @@ function ImGui.TableFixColumnSortDirection(table_, column) end -- Calculate next sort direction that would be set after clicking the column +-- - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click. +-- - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op. function ImGui.TableGetColumnNextSortDirection(column) IM_ASSERT(column.SortDirectionsAvailCount > 0) if column.SortOrder == -1 then @@ -2851,6 +3363,7 @@ function ImGui.TableSortSpecsSanitize(table_) local fixed_mask = {} for sort_n = 0, sort_order_count - 1 do -- Fix: Rewrite sort order fields if needed so they have no gap or duplicate. + -- (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1) local column_with_smallest_sort_order = -1 for column_n = 0, table_.ColumnsCount - 1 do if not fixed_mask[column_n] and table_.Columns[column_n].SortOrder ~= -1 then @@ -2863,7 +3376,7 @@ function ImGui.TableSortSpecsSanitize(table_) fixed_mask[column_with_smallest_sort_order] = true table_.Columns[column_with_smallest_sort_order].SortOrder = sort_n - -- Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set. + -- Fix: Make sure only one column has a SortOrder if ImGuiTableFlags.MultiSortable is not set. if need_fix_single_sort_order then sort_order_count = 1 for column_n = 0, table_.ColumnsCount - 1 do @@ -2876,7 +3389,7 @@ function ImGui.TableSortSpecsSanitize(table_) end end - -- Fallback default sort order (if no column with the ImGuiTableColumnFlags_DefaultSort flag) + -- Fallback default sort order (if no column with the ImGuiTableColumnFlags.DefaultSort flag) if sort_order_count == 0 and band(table_.Flags, ImGuiTableFlags.SortTristate) == 0 then for column_n = 0, table_.ColumnsCount - 1 do local column = table_.Columns[column_n] @@ -2905,6 +3418,7 @@ function ImGui.TableSortSpecsBuild(table_) end -- Write output + -- May be able to move all SortSpecs data from table (48 bytes) to ImGuiTableTempData if we decide to write it back on every BeginTable() local sort_specs if table_.SortSpecsCount == 0 then sort_specs = nil @@ -2932,12 +3446,22 @@ function ImGui.TableSortSpecsBuild(table_) table_.SortSpecs.SpecsCount = table_.SortSpecsCount end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Headers ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableGetHeaderRowHeight() [Internal] +-- - TableGetHeaderAngledMaxLabelWidth() [Internal] +-- - TableHeadersRow() +-- - TableHeader() +-- - TableAngledHeadersRow() +-- - TableAngledHeadersRowEx() [Internal] +------------------------------------------------------------------------------- function ImGui.TableGetHeaderRowHeight() + -- Caring for a minor edge case: -- Calculate row height, for the unlikely case that some labels may be taller than others. + -- If we didn't do that, uneven header height would highlight but smaller one before the tallest wouldn't catch input for all height. + -- In your custom header row you may omit this all together and just call TableNextRow() without a height... local g = GImGui local table_ = g.CurrentTable local row_height = g.FontSize @@ -2966,6 +3490,12 @@ function ImGui.TableGetHeaderAngledMaxLabelWidth() end -- [Public] This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn(). +-- The intent is that advanced users willing to create customized headers would not need to use this helper +-- and can create their own! For example: TableHeader() may be preceded by Checkbox() or other custom widgets. +-- See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this. +-- This code is intentionally written to not make much use of internal functions, to give you better direction +-- if you need to write your own. +-- FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public. function ImGui.TableHeadersRow() local g = GImGui local table_ = g.CurrentTable @@ -3007,6 +3537,7 @@ end -- Emit a column header (text + optional sort order) -- We cpu-clip text here so that all columns headers can be merged into a same draw call. +-- Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader() function ImGui.TableHeader(label) local g = GImGui local window = g.CurrentWindow @@ -3029,6 +3560,7 @@ function ImGui.TableHeader(label) local label_pos = V2(window.DC.CursorPos) -- If we already got a row height, there's use that. + -- FIXME-TABLE: Padding problem if the correct outer-padding CellBgRect strays off our ClipRect? local cell_r = ImGui.TableGetCellBgRect(table_, column_n) local label_height = ImMax(label_size.y, table_.RowMinHeight - table_.RowCellPaddingY * 2.0) @@ -3062,11 +3594,15 @@ function ImGui.TableHeader(label) return end + --GetForegroundDrawList():AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)) -- [DEBUG] + --GetForegroundDrawList():AddRect(bb.Min, bb.Max, IM_COL32(255, 0, 0, 255)) -- [DEBUG] + -- Using AllowOverlap mode because we cover the whole cell, and we want user to be able to submit subsequent items. local highlight = (table_.HighlightColumnHeader == column_n) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, ImGuiButtonFlags.AllowOverlap) if held or hovered or highlight then local col = ImGui.GetColorU32(held and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header)) + --RenderFrame(bb.Min, bb.Max, col, false, 0.0) ImGui.TableSetBgColor(ImGuiTableBgTarget.CellBg, col, table_.CurrentColumn) else -- Submit single cell bg color in the case we didn't submit a full header row @@ -3081,7 +3617,14 @@ function ImGui.TableHeader(label) window.DC.CursorPos.y = window.DC.CursorPos.y - g.Style.ItemSpacing.y * 0.5 -- Drag and drop to re-order columns. + -- FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone. if held and band(table_.Flags, ImGuiTableFlags.Reorderable) ~= 0 and ImGui.IsMouseDragging(0) and not g.DragDropActive then + -- - While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x + -- - We need to handle reordering across hidden columns. + -- In the configuration below, moving C to the right of E will lead to: + -- ... C [D] E ---> ... [D] E C (Column name/index) + -- ... 2 3 4 ... 2 3 4 (Display order) + -- - The other constraints are enforced by TableQueueSetColumnDisplayOrder() which might early out. table_.InstanceInteracted = table_.InstanceCurrent if g.IO.MouseDelta.x < 0.0 and g.IO.MousePos.x < cell_r.Min.x then local prev_column = (column.PrevEnabledColumn ~= -1) and table_.Columns[column.PrevEnabledColumn] or nil @@ -3098,6 +3641,8 @@ function ImGui.TableHeader(label) end -- Sort order arrow + -- - Only clip label for a visible arrow. Auto-fit still accounts for a possible arrow, but when + -- manually sized smaller we don't clip the label for the sake of an arrow that isn't displayed. local ellipsis_max = ImMax(cell_r.Max.x - (sort_arrow and (w_arrow + w_sort_text) or 0.0), label_pos.x) if band(table_.Flags, ImGuiTableFlags.Sortable) ~= 0 and band(column.Flags, ImGuiTableColumnFlags.NoSort) == 0 then if column.SortOrder ~= -1 then @@ -3121,6 +3666,7 @@ function ImGui.TableHeader(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) ImGui.RenderTextEllipsis(window.DrawList, label_pos, ImVec2(ellipsis_max, bb.Max.y), ellipsis_max, label, label_end, label_size) local text_clipped = label_size.x > (ellipsis_max - label_pos.x) @@ -3135,6 +3681,7 @@ function ImGui.TableHeader(label) end -- Unlike TableHeadersRow() it is not expected that you can reimplement or customize this with custom widgets. +-- FIXME: No hit-testing/button on the angled header. function ImGui.TableAngledHeadersRow() local g = GImGui local table_ = g.CurrentTable @@ -3158,7 +3705,7 @@ function ImGui.TableAngledHeadersRow() if BitTest(table_.EnabledMaskByDisplayOrder, order_n) then local column_n = table_.DisplayOrderToIndex[order_n] local column = table_.Columns[column_n] - if band(column.Flags, ImGuiTableColumnFlags.AngledHeader) ~= 0 then -- Note: can't rely on ImGuiTableColumnFlags_IsVisible test here. + if band(column.Flags, ImGuiTableColumnFlags.AngledHeader) ~= 0 then -- Note: can't rely on ImGuiTableColumnFlags.IsVisible test here. temp_data.AngledHeadersRequests:push_back({ Index = column_n, TextColor = col_text, BgColor0 = col_header_bg, BgColor1 = (column_n == highlight_column_n) and ImGui.GetColorU32(ImGuiCol.Header) or 0 }) end end @@ -3204,6 +3751,7 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat local unit_right = ImVec2(cos_a, sin_a) -- Calculate our base metrics and set angled headers data _before_ the first call to TableNextRow() + -- FIXME-STYLE: Would it be better for user to submit 'max_label_width' or 'row_height' ? One can be derived from the other. local header_height = g.FontSize + g.Style.CellPadding.x * 2.0 local row_height = ImTrunc(ImAbs(ImRotate(ImVec2(max_label_width, flip_label and header_height or -header_height), cos_a, sin_a).y)) table_.AngledHeadersHeight = row_height @@ -3211,6 +3759,7 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat local header_angled_vector = unit_right * (row_height / -sin_a) -- vector from bottom-left to top-left, and from bottom-right to top-right -- Declare row, override and draw our own background + -- FIXME-TABLE: Generally broken when overlapping frozen columns limit. ImGui.TableNextRow(ImGuiTableRowFlags.Headers, row_height) ImGui.TableNextColumn() local row_r = ImRect(table_.WorkRect.Min.x, table_.BgClipRect.Min.y, table_.WorkRect.Max.x, table_.RowPosY2) @@ -3252,6 +3801,8 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat max_x = ImMax(max_x, bg_shape[3].x) -- Draw label + -- - First draw at an offset where RenderTextXXX() function won't meddle with applying current ClipRect, then transform to final offset. + -- - Handle multiple lines manually, as we want each lines to follow on the horizontal border, rather than see a whole block rotated. local label_name = ImGui.TableGetColumnName(table_, column_n) local label_name_end = ImGui.FindRenderedTextEnd(label_name) local line_off_step_x = (g.FontSize / -sin_a) @@ -3299,6 +3850,7 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat end pivot_out.x = pivot_out.x + (flip_label and (line_off_curr_x + line_off_step_x) or line_off_curr_x) ImGui.ShadeVertsTransformPos(draw_list, vtx_idx_begin, vtx_idx_end, pivot_in, label_cos_a, label_sin_a, pivot_out) -- Rotate and offset + --if g.IO.KeyShift then local fg_dl = GetForegroundDrawList(); vtx_idx_begin = fg_dl._VtxCurrentIdx; fg_dl:AddRect(clip_r.Min, clip_r.Max, IM_COL32(0, 255, 0, 255), 0.0, 0, 1.0); ShadeVertsTransformPos(fg_dl, vtx_idx_begin, fg_dl._VtxCurrentIdx, pivot_in, label_cos_a, label_sin_a, pivot_out) end p = label_name_eol + 1 end @@ -3315,9 +3867,13 @@ function ImGui.TableAngledHeadersRowEx(row_id, angle, max_label_width, data, dat table_.TempData.AngledHeadersExtraWidth = ImMax(0.0, max_x - table_.Columns[table_.RightMostEnabledColumn].MaxX) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Context Menu ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableOpenContextMenu() [Internal] +-- - TableBeginContextMenuPopup() [Internal] +-- - TableDrawDefaultContextMenu() [Internal] +------------------------------------------------------------------------------- -- Use -1 to open menu not specific to a given column. function ImGui.TableOpenContextMenu(column_n) @@ -3371,8 +3927,8 @@ local function MenuItemForColumnReorder(label, selected, enabled) end local has_been_moved = (g.ActiveId == id) and g.ActiveIdHasBeenEditedBefore -- But disable toggling once moved. - ImGui.BeginDisabled(not enabled) -- Don't use ImGuiSelectableFlags_Disabled so that Check mark is also affected. - local ret = ImGui.Selectable(label, false, selectable_flags, ImVec2(min_w, label_size.y)) and not has_been_moved + ImGui.BeginDisabled(not enabled) -- Don't use ImGuiSelectableFlags.Disabled so that Check mark is also affected. + local ret = ImGui.Selectable(label, false, selectable_flags, ImVec2(min_w, label_size.y)) and not has_been_moved -- Can't use IsMouseDragging(0) as button is released already. if band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 and selected then ImGui.RenderCheckMark(window.DrawList, text_pos + ImVec2(offsets.OffsetMark + stretch_w + g.FontSize * 0.40, g.FontSize * 0.134 * 0.5), ImGui.GetColorU32(ImGuiCol.Text), g.FontSize * 0.866) end @@ -3382,6 +3938,13 @@ local function MenuItemForColumnReorder(label, selected, enabled) end -- Output context menu into current window (generally a popup) +-- FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data? +-- Sections to display are pulled from 'flags_for_section_to_display', which is typically == table.Flags. +-- - ImGuiTableFlags.Resizable -> display Sizing menu items +-- - ImGuiTableFlags.Reorderable -> display "Reset Order" +---- ImGuiTableFlags.Sortable -> display sorting options (disabled) +-- - ImGuiTableFlags.Hideable -> display columns visibility menu items +-- It means if you have a custom context menus you can call this section and omit some sections, and add your own. function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) local g = GImGui local window = g.CurrentWindow @@ -3417,6 +3980,9 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) -- Reset Order/Visibility etc. if band(flags_for_section_to_display, bor(ImGuiTableFlags.Reorderable, ImGuiTableFlags.Hideable)) ~= 0 then if ImGui.BeginMenu(ImGui.LocalizeGetMsg(ImGuiLocKey.TableReset)) then + --if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.TableResetAll)) then -- FIXME: Hiding because altering Sort Order + requesting auto-fit simultaneously has a tendency to exhibit a sizing glitch. + -- table_.IsResetAllRequest = true + --end if band(flags_for_section_to_display, ImGuiTableFlags.Reorderable) ~= 0 then if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.TableResetOrder), nil, false, not table_.IsDefaultDisplayOrder) then -- PS: cannot be hidden because it would mess with drag reordering. table_.IsResetDisplayOrderRequest = true @@ -3431,6 +3997,22 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end end + -- Sorting + -- (modify TableOpenContextMenu() to add _Sortable flag if enabling this) + -- #if 0 + --if band(flags_for_section_to_display, ImGuiTableFlags.Sortable) ~= 0 and column ~= nil and band(column.Flags, ImGuiTableColumnFlags.NoSort) == 0 then + -- if want_separator then ImGui.Separator() end + -- want_separator = true + -- local append_to_sort_specs = g.IO.KeyShift + -- if ImGui.MenuItem("Sort in Ascending Order", nil, column.SortOrder ~= -1 and column.SortDirection == ImGuiSortDirection.Ascending, band(column.Flags, ImGuiTableColumnFlags.NoSortAscending) == 0) then + -- ImGui.TableSetColumnSortDirection(table_, column_n, ImGuiSortDirection.Ascending, append_to_sort_specs) + -- end + -- if ImGui.MenuItem("Sort in Descending Order", nil, column.SortOrder ~= -1 and column.SortDirection == ImGuiSortDirection.Descending, band(column.Flags, ImGuiTableColumnFlags.NoSortDescending) == 0) then + -- ImGui.TableSetColumnSortDirection(table_, column_n, ImGuiSortDirection.Descending, append_to_sort_specs) + -- end + --end + -- #endif + -- Hiding / Visibility if band(flags_for_section_to_display, ImGuiTableFlags.Hideable) ~= 0 then if want_separator then @@ -3438,7 +4020,8 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end want_separator = true - -- While reordering: we calculate min/max allowed range once here so we can avoid a O(N log N) in the loop. + -- While reordering: we calculate min/max allowed range once here so we can avoid a O(N log N) in the loop (because the query itself does a sweep scan). + -- This assume that reordering constraints output a single range, otherwise would need to either call TableGetMaxDisplayOrderAllowed() for each item below, or cache this once per frame into columns. local is_reordering = (g.ActiveId ~= 0 and g.ActiveIdWindow == g.CurrentWindow and table_.ReorderColumn ~= -1 and g.ActiveIdHasBeenEditedBefore) -- FIXME: This is a bit of a hack. local reorder_src_order = is_reordering and table_.Columns[table_.ReorderColumn].DisplayOrder or -1 local reorder_min_order = is_reordering and TableGetMaxDisplayOrderAllowed(table_, reorder_src_order, 0) or 0 @@ -3466,6 +4049,7 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end -- Drag to reorder + -- FIXME: It is currently not possible to reorder columns marked with ImGuiTableColumnFlags.NoHide. if ImGui.IsItemActive() and ImGui.IsMouseDragging(0) and g.ActiveIdSource == ImGuiInputSource.Mouse and band(table_.Flags, ImGuiTableFlags.Reorderable) ~= 0 then g.ActiveIdHasBeenEditedBefore = true -- Disable toggle in MenuItemForColumnReorder() + start dimming to display allowed reorder targets. table_.ReorderColumn = column_n @@ -3482,9 +4066,31 @@ function ImGui.TableDrawDefaultContextMenu(table_, flags_for_section_to_display) end end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Settings (.ini data) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- FIXME: The binding/finding/creating flow are too confusing. +------------------------------------------------------------------------------- +-- - TableSettingsInit() [Internal] +-- - TableSettingsCreate() [Internal] +-- - TableSettingsFindByID() [Internal] +-- - TableGetBoundSettings() [Internal] +-- - TableResetSettings() +-- - TableSaveSettings() [Internal] +-- - TableLoadSettings() [Internal] +-- - TableLoadSettingsForColumns() [Internal] +-- - TableSettingsHandler_ClearAll() [Internal] +-- - TableSettingsHandler_ApplyAll() [Internal] +-- - TableSettingsHandler_ReadOpen() [Internal] +-- - TableSettingsHandler_ReadLine() [Internal] +-- - TableSettingsHandler_WriteAll() [Internal] +-- - TableSettingsAddSettingsHandler() [Internal] +------------------------------------------------------------------------------- +-- [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings. +-- [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table. +-- [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty. +-- [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file. +------------------------------------------------------------------------------- -- Clear and initialize empty settings instance local function TableSettingsInit(settings, id, columns_count, columns_count_max) @@ -3516,6 +4122,7 @@ end -- Find existing settings function ImGui.TableSettingsFindByID(id) + -- FIXME-OPT: Might want to store a lookup map for this? local g = GImGui for _, settings in g.SettingsTables:iter() do if settings.ID == id then @@ -3530,7 +4137,7 @@ local function SettingsTablesOffsetFromPtr(settings) return g.SettingsTables:find_index(settings) or -1 end --- Get settings for a given table, NULL if none +-- Get settings for a given table, nil if none function ImGui.TableGetBoundSettings(table_) if table_.SettingsOffset == -1 then return nil @@ -3590,6 +4197,8 @@ function ImGui.TableSaveSettings(table_) end -- We skip saving some data in the .ini file when they are unnecessary to restore our state. + -- Note that fixed width where initial width was derived from auto-fit will always be saved as InitStretchWeightOrWidth will be 0.0f. + -- FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present. if width_or_weight ~= column.InitStretchWeightOrWidth then settings.SaveFlags = bor(settings.SaveFlags, ImGuiTableFlags.Resizable) end @@ -3734,7 +4343,8 @@ function ImGui.TableFixDisplayOrder(table_) for n = 0, table_.ColumnsCount - 1 do fdo_columns[n + 1] = n end - -- Sort by DisplayOrder and then Index. -1 (unsigned short 0xFFFF) always sorts after. + -- Sort by DisplayOrder and then Index + -- Assume ImGuiTableColumnIdx == signed short, to turn -1 into a large value so that it always sort after. local function key(idx) local o = table_.Columns[idx].DisplayOrder if o < 0 then o = o + 0x10000 end @@ -3776,6 +4386,9 @@ local function TableSettingsHandler_ApplyAll(ctx, handler) end local function TableSettingsHandler_ReadOpen(ctx, handler, name) + -- FIXME: As topology changes are allowed, strictly speaking a >= IMGUI_TABLE_MAX_COLUMNS tables stored in .ini file + -- that was emitted with a higher max count could still be meaningful in some unlikely cases. + -- We might want to use another MAX defined as (1<<(sizeof(ImGuiTableColumnIdx)*8-1))-1. local id, columns_count = string.match(name, "^0x(%x+),(%-?%d+)") if id == nil then return nil @@ -3831,6 +4444,8 @@ local function TableSettingsHandler_WriteAll(ctx, handler, buf) local g = ctx for _, settings in g.SettingsTables:iter() do if settings.ID ~= 0 then -- Skip ditched settings + -- TableSaveSettings() may clear some of those flags when we establish that the data can be stripped + -- (e.g. Order was unchanged) local save_size = band(settings.SaveFlags, ImGuiTableFlags.Resizable) ~= 0 local save_visible = band(settings.SaveFlags, ImGuiTableFlags.Hideable) ~= 0 local save_order = band(settings.SaveFlags, ImGuiTableFlags.Reorderable) ~= 0 @@ -3843,6 +4458,7 @@ local function TableSettingsHandler_WriteAll(ctx, handler, buf) end for column_n = 0, settings.ColumnsCount - 1 do local column = settings.Columns[column_n] + -- "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v" local save_column = save_size or save_visible or save_order or (save_sort and column.SortOrder ~= -1) if save_column then buf:appendf("Column %-2d", column_n) @@ -3875,12 +4491,17 @@ function ImGui.TableSettingsAddSettingsHandler() ImGui.AddSettingsHandler(ini_handler) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Tables: Garbage Collection ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - TableRemove() [Internal] +-- - TableGcCompactTransientBuffers() [Internal] +-- - TableGcCompactSettings() [Internal] +------------------------------------------------------------------------------- -- Remove Table data (currently only used by TestEngine) function ImGui.TableRemove(table_) + --IMGUI_DEBUG_PRINT("TableRemove() id=0x%08X\n", table_.ID) local g = GImGui local table_idx = g.Tables:GetIndex(table_) g.Tables:Remove(table_.ID, table_) @@ -3897,6 +4518,7 @@ function ImGui.TableGcCompactTransientBuffers(t) t.LastTimeActive = -1.0 return end + --IMGUI_DEBUG_PRINT("TableGcCompactTransientBuffers() id=0x%08X\n", t.ID) local g = GImGui local table_ = t IM_ASSERT(table_.MemoryCompacted == false) @@ -3911,7 +4533,7 @@ function ImGui.TableGcCompactTransientBuffers(t) g.TablesLastTimeActive.Data[g.Tables:GetIndex(table_) + 1] = -1.0 end --- Compact and remove unused or resize settings data +-- Compact and remove unused or resize settings data (only TestEngine mark unused, but resizing table down can lead to compaction) function ImGui.TableGcCompactSettings() local g = GImGui local has_dead = false @@ -3929,10 +4551,28 @@ function ImGui.TableGcCompactSettings() ForEachTable(g, function(t) t.SettingsOffset = -1 end) end ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Columns, BeginColumns, EndColumns, etc. -- (This is a legacy API, prefer using BeginTable/EndTable!) ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- FIXME: sizing is lossy when columns width is very small (default width may turn negative etc.) +------------------------------------------------------------------------------- +-- - GetColumnIndex() +-- - GetColumnsCount() +-- - GetColumnOffset() +-- - GetColumnWidth() +-- - SetColumnOffset() +-- - SetColumnWidth() +-- - PushColumnClipRect() [Internal] +-- - PushColumnsBackground() [Internal] +-- - PopColumnsBackground() [Internal] +-- - FindOrCreateColumns() [Internal] +-- - GetColumnsID() [Internal] +-- - BeginColumns() +-- - NextColumn() +-- - EndColumns() +-- - Columns() +------------------------------------------------------------------------------- -- (Lua: columns.Columns is an ImVector, column n lives in .Data[n + 1]) function ImGui.GetColumnIndex() @@ -3956,7 +4596,8 @@ end local COLUMNS_HIT_RECT_HALF_THICKNESS = 4.0 local function GetDraggedColumnOffset(columns, column_index) - -- Active (dragged) column always follow mouse. + -- Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + -- window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. local g = GImGui local window = g.CurrentWindow IM_ASSERT(column_index > 0) -- We are not supposed to drag column 0. @@ -4110,6 +4751,7 @@ function ImGui.GetColumnsID(str_id, columns_count) local window = ImGui.GetCurrentWindow() -- Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + -- In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. ImGui.PushID(0x11223347 + (str_id and 0 or columns_count)) local id = window:GetID(str_id or "columns") ImGui.PopID() @@ -4142,6 +4784,7 @@ function ImGui.BeginColumns(str_id, columns_count, flags) ImRect_Copy(window.ParentWorkRect, window.WorkRect) -- Set state for first column + -- We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect local column_padding = g.Style.ItemSpacing.x local half_clip_extend_x = ImTrunc(ImMax(window.WindowPadding.x * 0.5, window.WindowBorderSize)) local max_1 = window.WorkRect.Max.x + column_padding - ImMax(column_padding - window.WindowPadding.x, 0.0) @@ -4215,6 +4858,7 @@ function ImGui.NextColumn() ImGui.PopItemWidth() -- Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect() + -- (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them), local column = columns.Columns.Data[columns.Current + 1] ImGui.SetWindowClipRectBeforeSetChannel(window, column.ClipRect) columns.Splitter:SetCurrentChannel(window.DrawList, columns.Current + 1) @@ -4223,6 +4867,7 @@ function ImGui.NextColumn() columns.LineMaxY = ImMax(columns.LineMaxY, window.DC.CursorPos.y) if columns.Current > 0 then -- Columns 1+ ignore IndentX (by canceling it out) + -- FIXME-COLUMNS: Unnecessary, could be locked? window.DC.ColumnsOffset.x = ImGui.GetColumnOffset(columns.Current) - window.DC.Indent.x + column_padding else -- New row/line: column 0 honor IndentX. @@ -4235,6 +4880,7 @@ function ImGui.NextColumn() window.DC.CurrLineSize.x = 0.0; window.DC.CurrLineSize.y = 0.0 window.DC.CurrLineTextBaseOffset = 0.0 + -- FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup. local offset_0 = ImGui.GetColumnOffset(columns.Current) local offset_1 = ImGui.GetColumnOffset(columns.Current + 1) local width = offset_1 - offset_0 @@ -4262,6 +4908,7 @@ function ImGui.EndColumns() end -- Draw columns borders and handle resize + -- The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy local is_being_resized = false if band(flags, ImGuiOldColumnFlags.NoBorder) == 0 and not window.SkipItems then -- We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. @@ -4327,6 +4974,7 @@ function ImGui.Columns(columns_count, id, borders) IM_ASSERT(columns_count >= 1) local flags = borders and 0 or ImGuiOldColumnFlags.NoBorder + --flags = bor(flags, ImGuiOldColumnFlags.NoPreserveWidths) -- NB: Legacy behavior local columns = window.DC.CurrentColumns if columns ~= nil and columns.Count == columns_count and columns.Flags == flags then return diff --git a/imgui_widgets.lua b/imgui_widgets.lua index fbe83e6..3737e8f 100644 --- a/imgui_widgets.lua +++ b/imgui_widgets.lua @@ -1,5 +1,28 @@ --- Dear ImGui WIP --- (Widgets Code) +-- (widgets code) + +-- +-- Index of this file: +-- +-- [SECTION] Widgets: Text, etc. +-- [SECTION] Widgets: Value helpers +-- [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.) +-- [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.) +-- [SECTION] Widgets: ComboBox +-- [SECTION] Data Type and Data Formatting Helpers +-- [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +-- [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +-- [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +-- [SECTION] Widgets: InputText, InputTextMultiline +-- [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +-- [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +-- [SECTION] Widgets: Selectable +-- [SECTION] Widgets: ListBox +-- [SECTION] Widgets: PlotLines, PlotHistogram +-- [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc. +-- [SECTION] Widgets: BeginTabBar, EndTabBar, etc. +-- [SECTION] Widgets: BeginTabItem, EndTabItem, etc. +-- --- @type ImGuiContext? local GImGui @@ -11,8 +34,13 @@ function ImGui._SetCurrentContext_Widgets(ctx) GImGui = ctx end -local DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70 -- Time for drag-hold to activate items accepting the ImGuiButtonFlags.PressedOnDragDropHold button behavior -local DRAG_MOUSE_THRESHOLD_FACTOR = 0.50 -- Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags +------------------------------------------------------------------------------- +-- Data +------------------------------------------------------------------------------- + +-- Widgets +local DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70 -- Time for drag-hold to activate items accepting the ImGuiButtonFlags.PressedOnDragDropHold button behavior. +local DRAG_MOUSE_THRESHOLD_FACTOR = 0.50 -- Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags. local IM_S8_MIN = -128 local IM_S8_MAX = 127 @@ -22,14 +50,25 @@ local IM_S16_MIN = -32768 local IM_S16_MAX = 32767 local IM_U16_MIN = 0 local IM_U16_MAX = 0xFFFF -local IM_S32_MIN = INT_MIN -local IM_S32_MAX = INT_MAX +local IM_S32_MIN = INT_MIN -- (-2147483647 - 1), (0x80000000); +local IM_S32_MAX = INT_MAX -- (2147483647), (0x7FFFFFFF) local IM_U32_MIN = 0 -local IM_U32_MAX = UINT_MAX +local IM_U32_MAX = UINT_MAX -- (0xFFFFFFFF) ----------------------------------------------------------------- --- [SECTION] TEXT ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Text, etc. +------------------------------------------------------------------------------- +-- - TextEx() [Internal] +-- - TextUnformatted() +-- - Text() +-- - TextV() +-- - TextColored() +-- - TextDisabled() +-- - TextWrapped() +-- - TextAligned() +-- - LabelText() +-- - BulletText() +------------------------------------------------------------------------------- --- @param text string --- @param text_end? int @@ -44,11 +83,13 @@ function ImGui.TextEx(text, text_end, flags) return end + -- Accept null ranges if not text or text == "" then text = "" text_end = 1 end + -- Calculate length if text_end == nil then text_end = #text + 1 end @@ -57,6 +98,7 @@ function ImGui.TextEx(text, text_end, flags) local wrap_pos_x = window.DC.TextWrapPos local wrap_enabled = (wrap_pos_x >= 0.0) if (text_end - 1 <= 2000) or wrap_enabled then + -- Common case local wrap_width = wrap_enabled and ImGui.CalcWrapWidthForPos(window.DC.CursorPos, wrap_pos_x) or 0.0 local text_size = ImGui.CalcTextSize(text, text_end, false, wrap_width) @@ -66,12 +108,18 @@ function ImGui.TextEx(text, text_end, flags) return end + -- Render (we don't hide text after ## in this end-user function) ImGui.RenderTextWrapped(bb.Min, text, text_end, wrap_width) else + -- Long text! + -- Perform manual coarse clipping to optimize for long multi-line text + -- - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. + -- - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. local line = 1 local line_height = ImGui.GetTextLineHeight() local text_size = ImVec2(0, 0) + -- Lines to skip (can't skip when logging text) local pos = ImVec2(text_pos.x, text_pos.y) if not g.LogEnabled then local lines_skippable = ImFloor((window.ClipRect.Min.y - text_pos.y) / line_height) @@ -93,6 +141,7 @@ function ImGui.TextEx(text, text_end, flags) end end + -- Lines to render if line < text_end then local line_rect = ImRect(pos, pos + ImVec2(FLT_MAX, line_height)) while line < text_end do @@ -114,6 +163,7 @@ function ImGui.TextEx(text, text_end, flags) pos.y = pos.y + line_height end + -- Count remaining lines local lines_skipped = 0 while line < text_end do local line_end = ImMemchr(text, "\n", line) @@ -189,7 +239,7 @@ end --- @param ... any function ImGui.TextWrapped(fmt, ...) local g = GImGui - local need_backup = (g.CurrentWindow.DC.TextWrapPos < 0.0) + local need_backup = (g.CurrentWindow.DC.TextWrapPos < 0.0) -- Keep existing wrap position if one is already set if need_backup then ImGui.PushTextWrapPos(0.0) end @@ -200,8 +250,8 @@ function ImGui.TextWrapped(fmt, ...) end -- 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) +-- size_x < 0.0f (e.g. -FLT_MIN): shortcut for GetContentRegionAvail().x +-- FIXME-WIP: Works but API is likely to be reworked. This is designed for 1 item on the line. (#7024, #9455) --- @param align_x float --- @param size_x float --- @param fmt string @@ -231,7 +281,7 @@ function ImGui.TextAligned(align_x, size_x, fmt, ...) ImVec2_Copy(backup_max_pos, window.DC.CursorMaxPos) ImGui.ItemSize(size) ImGui.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 + window.DC.CursorMaxPos.x = backup_max_pos.x -- Cancel out extending content to 'size' to use 'text_size' allowing auto-resize to function with align_x > 0.0f if size_x < text_size.x and ImGui.IsItemHovered(bit32.bor(ImGuiHoveredFlags.NoNavOverride, ImGuiHoveredFlags.AllowWhenDisabled, ImGuiHoveredFlags.ForTooltip)) then ImGui.SetTooltip("%.*s", text_end - 1, text) @@ -274,6 +324,7 @@ function ImGui.LabelText(label, fmt, ...) end end +-- Text with a little bullet aligned to the typical tree node. --- @param fmt string --- @param ... any function ImGui.BulletText(fmt, ...) @@ -312,6 +363,13 @@ ImGui.TextAlignedV = ImGui.TextAligned ImGui.LabelTextV = ImGui.LabelText ImGui.BulletTextV = ImGui.BulletText +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Value helpers +-- Those is not very useful, legacy API. +------------------------------------------------------------------------------- +-- - Value() +------------------------------------------------------------------------------- + -- Value(prefix, b) / Value(prefix, int) / Value(prefix, float, float_format) -- Lua can't tell int from float: integers without float_format print as %d, otherwise %.3f function ImGui.Value(prefix, v, float_format) @@ -326,10 +384,94 @@ function ImGui.Value(prefix, v, float_format) end end ----------------------------------------------------------------- --- [SECTION] MAIN: BUTTONS, SCROLLBARS, ... ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Main +------------------------------------------------------------------------------- +-- - ButtonBehavior() [Internal] +-- - Button() +-- - SmallButton() +-- - InvisibleButton() +-- - ArrowButton() +-- - CloseButton() [Internal] +-- - CollapseButton() [Internal] +-- - GetWindowScrollbarID() [Internal] +-- - GetWindowScrollbarRect() [Internal] +-- - Scrollbar() [Internal] +-- - ScrollbarEx() [Internal] +-- - Image() +-- - ImageButton() +-- - Checkbox() +-- - CheckboxFlagsT() [Internal] +-- - CheckboxFlags() +-- - RadioButton() +-- - ProgressBar() +-- - Bullet() +-- - Hyperlink() +------------------------------------------------------------------------------- +-- The ButtonBehavior() function is key to many interactions and used by many/most widgets. +-- Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags), +-- this code is a little complex. +-- By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags.PressedOnClickRelease button behavior. +-- See the series of events below and the corresponding state reported by dear imgui: +------------------------------------------------------------------------------- +-- with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+0 (mouse is outside bb) - - - - - - +-- Frame N+1 (mouse moves inside bb) - true - - - - +-- Frame N+2 (mouse button is down) - true true true - true +-- Frame N+3 (mouse button is down) - true true - - - +-- Frame N+4 (mouse moves outside bb) - - true - - - +-- Frame N+5 (mouse moves inside bb) - true true - - - +-- Frame N+6 (mouse button is released) true true - - true - +-- Frame N+7 (mouse button is released) - true - - - - +-- Frame N+8 (mouse moves outside bb) - - - - - - +------------------------------------------------------------------------------- +-- with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+2 (mouse button is down) true true true true - true +-- Frame N+3 (mouse button is down) - true true - - - +-- Frame N+6 (mouse button is released) - true - - true - +-- Frame N+7 (mouse button is released) - true - - - - +------------------------------------------------------------------------------- +-- with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+2 (mouse button is down) - true - - - true +-- Frame N+3 (mouse button is down) - true - - - - +-- Frame N+6 (mouse button is released) true true - - - - +-- Frame N+7 (mouse button is released) - true - - - - +------------------------------------------------------------------------------- +-- with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked() +-- Frame N+0 (mouse button is down) - true - - - true +-- Frame N+1 (mouse button is down) - true - - - - +-- Frame N+2 (mouse button is released) - true - - - - +-- Frame N+3 (mouse button is released) - true - - - - +-- Frame N+4 (mouse button is down) true true true true - true +-- Frame N+5 (mouse button is down) - true true - - - +-- Frame N+6 (mouse button is released) - true - - true - +-- Frame N+7 (mouse button is released) - true - - - - +------------------------------------------------------------------------------- +-- Note that some combinations are supported, +-- - 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 ImGuiItemFlags.ButtonRepeat is set: +-- Repeat+ Repeat+ Repeat+ Repeat+ +-- PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick +------------------------------------------------------------------------------- +-- Frame N+0 (mouse button is down) - true - true +-- ... - - - - +-- Frame N + RepeatDelay true true - true +-- ... - - - - +-- Frame N + RepeatDelay + RepeatRate*N true true - true +------------------------------------------------------------------------------- + +-- - FIXME: For refactor we could output flags, incl mouse hovered vs nav keyboard vs nav triggered etc. +-- 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 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() +-- Returns (pressed, hovered, held). --- @param bb ImRect --- @param id ImGuiID --- @param flags? ImGuiButtonFlags @@ -341,6 +483,8 @@ function ImGui.ButtonBehavior(bb, id, flags) local window = g.CurrentWindow + -- 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. local item_flags = (g.LastItemData.ID == id) and g.LastItemData.ItemFlags or g.CurrentItemFlags if bit32.band(flags, ImGuiButtonFlags.AllowOverlap) ~= 0 then item_flags = bit32.bor(item_flags, ImGuiItemFlags.AllowOverlap) @@ -367,6 +511,9 @@ function ImGui.ButtonBehavior(bb, id, flags) local pressed = false local hovered = ImGui.ItemHoverable(bb, id, item_flags) + + -- 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 then if (bit32.band(flags, ImGuiButtonFlags.PressedOnDragDropHold) ~= 0) and (bit32.band(g.DragDropSourceFlags, ImGuiDragDropFlags.SourceNoHoldToOpenOthers) == 0) and ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem) then hovered = true @@ -388,10 +535,14 @@ function ImGui.ButtonBehavior(bb, id, flags) g.HoveredWindow = backup_hovered_window end + -- Mouse handling local test_owner_id = (bit32.band(flags, ImGuiButtonFlags.NoTestKeyOwner) ~= 0) and ImGuiKeyOwner_Any or id if hovered then - IM_ASSERT(id ~= 0) + IM_ASSERT(id ~= 0) -- Lazily check inside rare path. + -- Poll mouse buttons + -- - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId. + -- - Technically we only need some values in one code path, but since this is gated by hovered test this is fine. local mouse_button_clicked = -1 local mouse_button_released = -1 for button = 0, 2 do @@ -401,6 +552,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end end + -- Process initial action local mods_ok = (bit32.band(flags, ImGuiButtonFlags.NoKeyModsAllowed) == 0) or (not g.IO.KeyCtrl and not g.IO.KeyShift and not g.IO.KeyAlt) if mods_ok then if mouse_button_clicked ~= -1 and g.ActiveId ~= id then @@ -418,7 +570,7 @@ function ImGui.ButtonBehavior(bb, id, flags) ImGui.SetFocusID(id, window) ImGui.FocusWindow(window) elseif bit32.band(flags, ImGuiButtonFlags.NoFocus) == 0 then - ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) + ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) -- Still need to focus and bring to front, but try to avoid losing NavId when navigating a child end end @@ -428,7 +580,7 @@ function ImGui.ButtonBehavior(bb, id, flags) if bit32.band(flags, ImGuiButtonFlags.NoHoldingActiveId) ~= 0 then ImGui.ClearActiveID() else - ImGui.SetActiveID(id, window) + ImGui.SetActiveID(id, window) -- Hold on ID end g.ActiveIdMouseButton = mouse_button_clicked @@ -437,12 +589,12 @@ function ImGui.ButtonBehavior(bb, id, flags) ImGui.SetFocusID(id, window) ImGui.FocusWindow(window) elseif bit32.band(flags, ImGuiButtonFlags.NoFocus) == 0 then - ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) + ImGui.FocusWindow(window, ImGuiFocusRequestFlags.RestoreFocusedChild) -- Still need to focus and bring to front, but try to avoid losing NavId when navigating a child end end if bit32.band(flags, ImGuiButtonFlags.PressedOnRelease) ~= 0 then - -- FIXME: Traditionally ImGuiButtonFlags.PressedOnRelease never took ActiveId. Adding it in 2026-03-20 since ImGuiButtonFlags_NoHoldingActiveId can always be added. + -- FIXME: Traditionally ImGuiButtonFlags.PressedOnRelease never took ActiveId. Adding it in 2026-03-20 since ImGuiButtonFlags.NoHoldingActiveId can always be added. -- We don't yet perform an explicit ClearActiveID() to reduce scope of change, but this possibility could be investigated. if bit32.band(flags, ImGuiButtonFlags.NoHoldingActiveId) == 0 then ImGui.SetActiveID(id, window) -- Hold on ID @@ -453,14 +605,14 @@ function ImGui.ButtonBehavior(bb, id, flags) if bit32.band(flags, ImGuiButtonFlags.PressedOnRelease) ~= 0 then if mouse_button_released ~= -1 then - local has_repeated_at_least_once = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay + local has_repeated_at_least_once = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay -- Repeat mode trumps on release behavior if not has_repeated_at_least_once then pressed = true end if bit32.band(flags, ImGuiButtonFlags.NoNavFocus) == 0 then - ImGui.SetFocusID(id, window) -- FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why. + ImGui.SetFocusID(id, window) -- FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why. end ImGui.ClearActiveID() @@ -482,7 +634,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end -- Keyboard/Gamepad navigation handling - -- We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse + -- We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse. if bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0 then if g.NavId == id and g.NavCursorVisible and g.NavHighlightItemUnderNav then if bit32.band(flags, ImGuiButtonFlags.NoHoveredOnFocus) == 0 then @@ -515,6 +667,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end end + -- Process while held local held = false if g.ActiveId == id then if g.ActiveIdSource == ImGuiInputSource.Mouse then @@ -536,7 +689,7 @@ function ImGui.ButtonBehavior(bb, id, flags) -- Report as pressed when releasing the mouse (this is the most common path) local is_double_click_release = (bit32.band(flags, ImGuiButtonFlags.PressedOnDoubleClick) ~= 0) and g.IO.MouseReleased[mouse_button] and g.IO.MouseClickedLastCount[mouse_button] == 2 - local is_repeating_already = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay + local is_repeating_already = (bit32.band(item_flags, ImGuiItemFlags.ButtonRepeat) ~= 0) and g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay -- Repeat mode trumps local is_button_avail_or_owned = ImGui.TestKeyOwner(ImGui.MouseButtonToKey(mouse_button), test_owner_id) @@ -554,7 +707,7 @@ function ImGui.ButtonBehavior(bb, id, flags) elseif g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad then -- When activated using Nav, we hold on the ActiveID until activation button is released if g.NavActivateDownId == id then - held = true -- hovered == true not true as we are already likely hovered on direct activation. + held = true -- hovered == true not true as we are already likely hovered on direct activation. else ImGui.ClearActiveID() end @@ -565,6 +718,7 @@ function ImGui.ButtonBehavior(bb, id, flags) end end + -- Activation highlight (this may be a remote activation) if g.NavHighlightActivatedId == id and (bit32.band(item_flags, ImGuiItemFlags.Disabled) == 0) then hovered = true end @@ -594,7 +748,7 @@ function ImGui.ButtonEx(label, size_arg, flags) local pos = ImVec2() -- Don't modify the cursor! ImVec2_Copy(pos, window.DC.CursorPos) - if bit32.band(flags, ImGuiButtonFlags.AlignTextBaseLine) ~= 0 and style.FramePadding.y < window.DC.CurrLineTextBaseOffset then + if bit32.band(flags, ImGuiButtonFlags.AlignTextBaseLine) ~= 0 and style.FramePadding.y < window.DC.CurrLineTextBaseOffset then -- Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y = pos.y + window.DC.CurrLineTextBaseOffset - style.FramePadding.y end local size = ImGui.CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0, label_size.y + style.FramePadding.y * 2.0) @@ -607,6 +761,7 @@ function ImGui.ButtonEx(label, size_arg, flags) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id, flags) + -- Render local col if held and hovered then col = ImGui.GetColorU32(ImGuiCol.ButtonActive) @@ -638,6 +793,7 @@ function ImGui.Button(label, size_arg) return ImGui.ButtonEx(label, size_arg, ImGuiButtonFlags.None) end +-- Small buttons fits within text without additional vertical spacing. --- @param label string --- @return bool function ImGui.SmallButton(label) @@ -649,6 +805,8 @@ function ImGui.SmallButton(label) return pressed end +-- Tip: use ImGui.PushID()/PopID() to push indices or pointers in the ID stack. +-- Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) --- @param str_id string --- @param size_arg ImVec2 --- @param flags? ImGuiButtonFlags @@ -720,6 +878,7 @@ function ImGui.ArrowButton(str_id, dir) return ImGui.ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags.None) end +-- Button to close a window --- @param id ImGuiID --- @param pos ImVec2 --- @return bool @@ -728,6 +887,8 @@ function ImGui.CloseButton(id, pos) local window = g.CurrentWindow + -- Tweak 1: Shrink hit-testing area if button covers an abnormally large proportion of the visible region. That's in order to facilitate moving the window away. (#3825) + -- This may better be applied as a general hit-rect reduction mechanism for all widgets to ensure the area to move window is always accessible? local bb = ImRect(pos, pos + ImVec2(g.FontSize, g.FontSize)) local bb_interact = ImRect() ImRect_Copy(bb_interact, bb) @@ -737,6 +898,8 @@ function ImGui.CloseButton(id, pos) bb_interact:Expand(ImTrunc(bb_interact:GetSize() * -0.25)) end + -- Tweak 2: We intentionally allow interaction when clipped so that a mechanical Alt,Right,Activate sequence can always close a window. + -- (this isn't the common behavior of buttons, but it doesn't affect the user because navigation tends to keep items visible in scrolling layer). local is_clipped = not ImGui.ItemAdd(bb_interact, id) local pressed, hovered, held = ImGui.ButtonBehavior(bb, id) @@ -744,6 +907,7 @@ function ImGui.CloseButton(id, pos) return pressed end + -- Render local bg_col if held then bg_col = ImGui.GetColorU32(ImGuiCol.ButtonActive) @@ -777,6 +941,7 @@ function ImGui.CollapseButton(id, pos) local pressed, hovered = ImGui.ButtonBehavior(bb, id) + -- Render if hovered then window.DrawList:AddRectFilled(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.ButtonHovered)) end @@ -801,6 +966,7 @@ function ImGui.GetWindowScrollbarID(window, axis) end end +-- Return scrollbar rectangle, must only be called for corresponding axis if window.ScrollbarX/Y is set. --- @param window ImGuiWindow --- @param axis ImGuiAxis --- @return ImRect @@ -841,6 +1007,12 @@ function ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb, threshold, axis) end end +-- Vertical/Horizontal scrollbar +-- The entire piece of code below is rather confusing because: +-- - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) +-- - 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.. --- @param bb_frame ImRect --- @param id ImGuiID --- @param axis ImGuiAxis @@ -863,6 +1035,7 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ return false, p_scroll_v end + -- 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) local alpha = 1.0 if axis == ImGuiAxis.Y and bb_frame_height < bb_frame_width then alpha = ImSaturate(bb_frame_height / ImMax(bb_frame_width * 2.0, 1.0)) @@ -892,7 +1065,9 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ return false, p_scroll_v end - IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0) + -- Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount) + -- But we maintain a minimum size in pixel to allow for the user to still aim inside. + IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0) -- Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. local win_size_v = ImMax(ImMax(size_contents_v, size_visible_v), 1) local grab_h_minsize = ImMin(bb:GetSize()[axis], style.GrabMinSize) local grab_h_pixels = ImTrunc(ImClamp(scrollbar_size_v * (size_visible_v / win_size_v), grab_h_minsize, scrollbar_size_v)) @@ -903,15 +1078,18 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ ImRect_Copy(bb_hit, bb_frame) ImGui.ExtendHitBoxWhenNearViewportEdge(window, bb_hit, g.Style.WindowBorderSize, ImGuiAxis.X + ImGuiAxis.Y - axis) -- swap axis here + -- Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). ImGui.ItemAdd(bb_frame, id, nil, ImGuiItemFlags.NoNav) local pressed, hovered, held = ImGui.ButtonBehavior(bb_hit, id, ImGuiButtonFlags.NoNavFocus) local scroll_max = ImMax(1, size_contents_v - size_visible_v) local scroll_ratio = ImSaturate(p_scroll_v / scroll_max) - local grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v + local grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v -- Grab position in normalized space if held and allow_interaction and grab_h_norm < 1.0 then local scrollbar_pos_v = bb.Min[axis] local mouse_pos_v = g.IO.MousePos[axis] + + -- Click position in scrollbar normalized space (0.0f->1.0f) local clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v) local held_dir @@ -923,6 +1101,7 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ held_dir = 0 end if g.ActiveIdIsJustActivated then + -- On initial click when held_dir == 0 (clicked over grab): calculate the distance between mouse and the center of the grab local scroll_to_clicked_location = (g.IO.ConfigScrollbarScrollByPage == false) or g.IO.KeyShift or held_dir == 0 if scroll_to_clicked_location then @@ -938,10 +1117,14 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ end end + -- Apply scroll (p_scroll_v will generally point on one member of window.Scroll) + -- It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position if g.ScrollbarSeekMode == 0 then + -- Absolute seeking scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5) / (1.0 - grab_h_norm)) p_scroll_v = scroll_v_norm * scroll_max else + -- Page by page if ImGui.IsMouseClickedEx(ImGuiMouseButton.Left, ImGuiInputFlags.Repeat) and held_dir == g.ScrollbarSeekMode then local page_dir if g.ScrollbarSeekMode > 0.0 then @@ -953,10 +1136,16 @@ function ImGui.ScrollbarEx(bb_frame, id, axis, p_scroll_v, size_visible_v, size_ end end + -- Update values for rendering scroll_ratio = ImSaturate(p_scroll_v / scroll_max) grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v + + -- Update distance to grab now that we have seek'ed and saturated + --if (seek_absolute) + -- g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f; end + -- Render local bg_col = ImGui.GetColorU32(ImGuiCol.ScrollbarBg) local grab_col if held then @@ -998,7 +1187,8 @@ function ImGui.Scrollbar(axis) window.Scroll[axis] = scroll end --- - `uv0` and `uv1` are texture coordinates +-- - 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. --- @param tex_ref ImTextureRef --- @param image_size ImVec2 --- @param uv0? ImVec2 @@ -1090,7 +1280,7 @@ function ImGui.ImageButtonEx(id, tex_ref, image_size, uv0, uv1, bg_col, tint_col return pressed end --- - ImageButton() adds style.FramePadding*2.0 to provided size. This is in order to facilitate fitting an image in a button. +-- - 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? --- @param str_id string --- @param tex_ref ImTextureRef @@ -1141,12 +1331,13 @@ function ImGui.Checkbox(label, v) local is_visible = ImGui.ItemAdd(total_bb, id) local is_multi_select = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0) if not is_visible then - if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(total_bb) then -- Extra layer of "no logic clip" for box-select support + if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(total_bb) then -- Extra layer of "no logic clip" for box-select support -- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)) return false, v end end + -- Range-Selection/Multi-selection support (header) local checked = v if is_multi_select then -- TODO: MultiSelectItemHeader() @@ -1154,6 +1345,7 @@ function ImGui.Checkbox(label, v) local pressed, hovered, held = ImGui.ButtonBehavior(total_bb, id) + -- Range-Selection/Multi-selection support (footer) if is_multi_select then -- TODO: MultiSelectItemFooter() elseif pressed then @@ -1162,7 +1354,7 @@ function ImGui.Checkbox(label, v) if v ~= checked then v = checked - pressed = true + pressed = true -- return value ImGui.MarkItemEdited(id) end @@ -1333,8 +1525,8 @@ function ImGui.ProgressBar(fraction, size_arg, overlay) return end - -- Fraction < 0.0 will display an indeterminate progress bar animation - -- The value must be animated along with time, so e.g. passing '-1.0 * ImGui.GetTime()' as fraction works + -- Fraction < 0.0f will display an indeterminate progress bar animation + -- The value must be animated along with time, so e.g. passing '-1.0f * ImGui.GetTime()' as fraction works. local is_indeterminate = (fraction < 0.0) if not is_indeterminate then fraction = ImSaturate(fraction) @@ -1398,6 +1590,10 @@ function ImGui.Bullet() ImGui.SameLine(0, style.FramePadding.x * 2.0) end +-- This is provided as a convenience for being an often requested feature. +-- FIXME-STYLE: we delayed adding as there is a larger plan to revamp the styling system. +-- Because of this we currently don't provide many styling options for this widget +-- (e.g. hovered/active colors are automatically inferred from a single color). --- @param label string function ImGui.TextLink(label) local window = ImGui.GetCurrentWindow() @@ -1442,7 +1638,7 @@ function ImGui.TextLink(label) end local line_y = bb.Max.y + ImFloor(g.FontBaked.Descent * g.FontBakedScale * 0.20) - window.DrawList:AddLineH(bb.Min.x, bb.Max.x, line_y, ImGui.GetColorU32(line_colf), 1.0 * ImTrunc(g.Style._MainScale)) -- FIXME-DPI + window.DrawList:AddLineH(bb.Min.x, bb.Max.x, line_y, ImGui.GetColorU32(line_colf), 1.0 * ImTrunc(g.Style._MainScale)) -- FIXME-TEXT: Underline mode -- FIXME-DPI ImGui.PushStyleColor(ImGuiCol.Text, ImGui.GetColorU32(text_colf)) ImGui.RenderText(bb.Min, label, 1, label_end, false) @@ -1464,7 +1660,7 @@ function ImGui.TextLinkOpenURL(label, url) g.PlatformIO.Platform_OpenInShellFn(g, url) end - ImGui.SetItemTooltip(ImGui.LocalizeGetMsg(ImGuiLocKey.OpenLink_s), url) + ImGui.SetItemTooltip(ImGui.LocalizeGetMsg(ImGuiLocKey.OpenLink_s), url) -- It is more reassuring for user to _always_ display URL when it is the same as the label. if ImGui.BeginPopupContextItem() then if ImGui.MenuItem(ImGui.LocalizeGetMsg(ImGuiLocKey.CopyLink)) then @@ -1476,9 +1672,16 @@ function ImGui.TextLinkOpenURL(label, url) return pressed end ----------------------------------------------------------------- --- [SECTION] Low-level Layout helpers ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Low-level Layout helpers +------------------------------------------------------------------------------- +-- - Spacing() +-- - Dummy() +-- - NewLine() +-- - AlignTextToFramePadding() +-- - SeparatorEx() [Internal] +-- - Separator() +------------------------------------------------------------------------------- function ImGui.Spacing() local window = ImGui.GetCurrentWindow() @@ -1511,8 +1714,7 @@ function ImGui.NewLine() window.DC.LayoutType = ImGuiLayoutType.Vertical window.DC.IsSameLine = false - if window.DC.CurrLineSize.y > 0.0 then - -- In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + if window.DC.CurrLineSize.y > 0.0 then -- In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. ImGui.ItemSize(ImVec2(0, 0)) else ImGui.ItemSize(ImVec2(0.0, g.FontSize)) @@ -1532,6 +1734,9 @@ function ImGui.AlignTextToFramePadding() window.DC.CurrLineTextBaseOffset = ImMax(window.DC.CurrLineTextBaseOffset, g.Style.FramePadding.y) end +-- Horizontal/vertical separating line +-- FIXME: Surprisingly, this seemingly trivial widget is a victim of many different legacy/tricky layout issues. +-- Note how thickness == 1.0f is handled specifically as not moving CursorPos by 'thickness', but other values are. --- @param flags ImGuiSeparatorFlags --- @param thickness float function ImGui.SeparatorEx(flags, thickness) @@ -1571,13 +1776,18 @@ function ImGui.SeparatorEx(flags, thickness) -- We currently don't need to provide the same feature for tables because tables naturally have border features. local columns = (bit32.band(flags, ImGuiSeparatorFlags.SpanAllColumns) ~= 0) and window.DC.CurrentColumns or nil if columns then - x1 = window.Pos.x + window.DC.Indent.x -- Used to be Pos.x before 2023/10/03 + x1 = window.Pos.x + window.DC.Indent.x -- Used to be Pos.x before 2023/10/03 x2 = window.Pos.x + window.Size.x ImGui.PushColumnsBackground() end -- We don't provide our width to the layout so that it doesn't get feed back into AutoFit -- FIXME: This prevents ->CursorMaxPos based bounding box evaluation from working (e.g. TableEndCell) + + -- Between 1.71 and 1.92.7, we maintained a hack where a 1.0f thin Separator() would not impact layout. + -- This was mostly chosen to allow backward compatibility with user's code assuming zero-height when calculating height for layout (e.g. bottom alignment of a status bar). + -- In order to handle scaling we need to scale separator thickness and it would not makes sense to have a disparity depending on height. + ----float thickness_for_layout = (thickness == 1.0f) ? 0.0f : thickness; // FIXME: See 1.70/1.71 Separator() change: makes legacy 1-px separator not affect layout yet. Should change. local bb = ImRect(ImVec2(x1, window.DC.CursorPos.y), ImVec2(x2, window.DC.CursorPos.y + thickness)) ImGui.ItemSize(ImVec2(0.0, thickness)) @@ -1636,7 +1846,7 @@ function ImGui.SeparatorTextEx(id, label, label_end, extra_w) local min_size = ImVec2(label_size.x + extra_w + padding.x * 2.0, ImMax(label_size.y + padding.y * 2.0, separator_thickness)) local bb = ImRect(pos, ImVec2(window.WorkRect.Max.x, pos.y + min_size.y)) - local text_baseline_y = ImTrunc((bb:GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.999) -- ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f)) + local text_baseline_y = ImTrunc((bb:GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.999) --ImMax(padding.y, ImTrunc((style.SeparatorTextSize - label_size.y) * 0.5f)) ImGui.ItemSize(min_size, text_baseline_y) if not ImGui.ItemAdd(bb, id) then @@ -1648,7 +1858,7 @@ function ImGui.SeparatorTextEx(id, label, label_end, extra_w) local seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5 + 0.999) local label_avail_w = ImMax(0.0, sep2_x2 - sep1_x1 - padding.x * 2.0) - local label_pos = ImVec2(pos.x + padding.x + ImMax(0.0, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y) -- FIXME-ALIGN + local label_pos = ImVec2(pos.x + padding.x + ImMax(0.0, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y) -- FIXME-ALIGN -- This allows using SameLine() to position something in the 'extra_w' window.DC.CursorPosPrevLine.x = label_pos.x + label_size.x @@ -1690,12 +1900,26 @@ function ImGui.SeparatorText(label) return end + -- The SeparatorText() vs SeparatorTextEx() distinction is designed to be considerate that we may want: + -- - allow separator-text to be draggable items (would require a stable ID + a noticeable highlight) + -- - this high-level entry point to allow formatting? (which in turns may require ID separate from formatted string) + -- - because of this we probably can't turn 'string label' into 'string fmt, ...' + -- Otherwise, we can decide that users wanting to drag this would layout a dedicated drag-item, + -- and then we can turn this into a format function. ImGui.SeparatorTextEx(0, label, ImGui.FindRenderedTextEnd(label), 0.0) end ----------------------------------------------------------------- --- [SECTION] COMBO BOX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: ComboBox +------------------------------------------------------------------------------- +-- - CalcMaxPopupHeightFromItemCount() [Internal] +-- - BeginCombo() +-- - BeginComboPopup() [Internal] +-- - EndCombo() +-- - BeginComboPreview() [Internal] +-- - EndComboPreview() [Internal] +-- - Combo() +------------------------------------------------------------------------------- --- @param items_count float --- @return float @@ -1717,7 +1941,7 @@ function ImGui.BeginCombo(label, preview_value, flags) local window = ImGui.GetCurrentWindow() local backup_next_window_data_flags = g.NextWindowData.HasFlags - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values if window.SkipItems then return false end @@ -1764,6 +1988,7 @@ function ImGui.BeginCombo(label, preview_value, flags) return false end + -- Open on click local pressed, hovered, held = ImGui.ButtonBehavior(bb, id) local popup_id = ImHashStr("##ComboPopup", nil, id) local popup_open = ImGui.IsPopupOpen(popup_id, ImGuiPopupFlags.None) @@ -1832,6 +2057,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) return false end + -- Set popup size local w = bb:GetWidth() if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) ~= 0 then g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w) @@ -1839,7 +2065,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) if bit32.band(flags, ImGuiComboFlags.HeightMask_) == 0 then flags = bit32.bor(flags, ImGuiComboFlags.HeightRegular) end - IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiComboFlags.HeightMask_))) + IM_ASSERT(ImIsPowerOfTwo(bit32.band(flags, ImGuiComboFlags.HeightMask_))) -- Only one local popup_max_height_in_items = -1 if bit32.band(flags, ImGuiComboFlags.HeightRegular) ~= 0 then popup_max_height_in_items = 8 @@ -1850,7 +2076,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) end local constraint_min = ImVec2(0.0, 0.0) local constraint_max = ImVec2(FLT_MAX, FLT_MAX) - if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.x <= 0.0 then + if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.x <= 0.0 then -- Don't apply constraints if user specified a size constraint_min.x = w end if bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSize) == 0 or g.NextWindowData.SizeVal.y <= 0.0 then @@ -1860,7 +2086,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) end -- This is essentially a specialized version of BeginPopupEx() - local name = ImFormatString("##Combo_%02d", g.BeginComboDepth) + local name = ImFormatString("##Combo_%02d", g.BeginComboDepth) -- Recycle windows based on depth -- Set position given a custom constraint (peak into expected window size so we can position it) -- FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function? @@ -1870,7 +2096,7 @@ function ImGui.BeginComboPopup(popup_id, bb, flags) if popup_window.WasActive then -- Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us. local size_expected = ImGui.CalcWindowNextAutoFitSize(popup_window) - popup_window.AutoPosLastDirection = (bit32.band(flags, ImGuiComboFlags.PopupAlignLeft) ~= 0) and ImGuiDir.Left or ImGuiDir.Down + popup_window.AutoPosLastDirection = (bit32.band(flags, ImGuiComboFlags.PopupAlignLeft) ~= 0) and ImGuiDir.Left or ImGuiDir.Down -- Left = "Below, Toward Left", Down = "Below, Toward Right (default)" local r_outer = ImGui.GetPopupAllowedExtentRect(popup_window) local pos pos, popup_window.AutoPosLastDirection = ImGui.FindBestWindowPosForPopupEx(bb:GetBL(), size_expected, popup_window.AutoPosLastDirection, r_outer, bb, ImGuiPopupPositionPolicy.ComboBox) @@ -1910,8 +2136,11 @@ function ImGui.EndCombo() ImGui.EndPopup() end --- Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements --- (Experimental, see GitHub issues: #1658, #4168) +-- Submit preview contents for BeginCombo()/EndCombo(), to display contents that's more than just a text label. +-- - [BETA] See GitHub issues: #1658, #4168. +-- - Call directly after the BeginCombo/EndCombo block (requires ImGuiComboFlags.CustomPreview). +-- - The preview is designed to only host non-interactive elements. +-- - Not compatible with ImGuiComboFlags.WidthFitPreview. function ImGui.BeginComboPreview() local g = GImGui local window = g.CurrentWindow @@ -1949,6 +2178,7 @@ function ImGui.EndComboPreview() local window = g.CurrentWindow local preview_data = g.ComboPreviewData + -- FIXME: Using CursorMaxPos approximation instead of correct AABB which we will store in ImDrawCmd in the future local draw_list = window.DrawList if window.DC.CursorMaxPos.x < preview_data.PreviewRect.Max.x and window.DC.CursorMaxPos.y < preview_data.PreviewRect.Max.y then if draw_list.CmdBuffer.Size > 1 then -- Unlikely case that the PushClipRect() didn't create a command @@ -1961,7 +2191,7 @@ function ImGui.EndComboPreview() ImGui.PopClipRect() ImVec2_Copy(window.DC.CursorPos, preview_data.BackupCursorPos) - ImVec2_Copy(window.DC.CursorMaxPos, ImMax(window.DC.CursorMaxPos, preview_data.BackupCursorMaxPos)) + ImVec2_Copy(window.DC.CursorMaxPos, ImMax(window.DC.CursorMaxPos, preview_data.BackupCursorMaxPos)) -- No need to do the same with IdealMaxPos ImVec2_Copy(window.DC.CursorPosPrevLine, preview_data.BackupCursorPosPrevLine) window.DC.PrevLineTextBaseOffset = preview_data.BackupPrevLineTextBaseOffset window.DC.LayoutType = preview_data.BackupLayout @@ -2024,6 +2254,7 @@ function ImGui.Combo(label, current_item, a, b, c, d) local getter, user_data, items_count, popup_max_height_in_items = Items_ResolveArgs(a, b, c, d) if popup_max_height_in_items == nil then popup_max_height_in_items = -1 end + -- Call the getter to obtain the preview string which is a parameter to BeginCombo() local preview_value = nil if bit32.band(bit32.bor(g.NextItemData.ItemFlagsSet, g.CurrentItemFlags), ImGuiItemFlags.MixedValue) ~= 0 then preview_value = "" @@ -2031,6 +2262,7 @@ function ImGui.Combo(label, current_item, a, b, c, d) preview_value = getter(user_data, current_item) end + -- 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 and bit32.band(g.NextWindowData.HasFlags, ImGuiNextWindowDataFlags.HasSizeConstraint) == 0 then ImGui.SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))) end @@ -2039,6 +2271,7 @@ function ImGui.Combo(label, current_item, a, b, c, d) return current_item, false end + -- Display items local value_changed = false local clipper = ImGuiListClipper() clipper:Begin(items_count) @@ -2071,9 +2304,18 @@ function ImGui.Combo(label, current_item, a, b, c, d) return current_item, value_changed end ----------------------------------------------------------------- --- [SECTION] DATA TYPE & DATA FORMATTING [Internal] ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Data Type and Data Formatting Helpers [Internal] +------------------------------------------------------------------------------- +-- - DataTypeGetInfo() +-- - DataTypeFormatString() +-- - DataTypeApplyOp() +-- - DataTypeApplyFromText() +-- - DataTypeCompare() +-- - DataTypeClamp() +-- - GetMinimumStepAtDecimalPrecision +-- - RoundScalarWithFormat<>() +------------------------------------------------------------------------------- local function float(val) return val end local function double(val) return val end @@ -2094,16 +2336,16 @@ local function ImGuiDataTypeInfo(size, name, print_fmt, scan_fmt) end local GDataTypeInfo = { - ImGuiDataTypeInfo(1, "S8", "%d", "%d"), + ImGuiDataTypeInfo(1, "S8", "%d", "%d"), -- ImGuiDataType.S8 ImGuiDataTypeInfo(1, "U8", "%u", "%u"), - ImGuiDataTypeInfo(2, "S16", "%d", "%d"), + ImGuiDataTypeInfo(2, "S16", "%d", "%d"), -- ImGuiDataType.S16 ImGuiDataTypeInfo(2, "U16", "%u", "%u"), - ImGuiDataTypeInfo(4, "S32", "%d", "%d"), + ImGuiDataTypeInfo(4, "S32", "%d", "%d"), -- ImGuiDataType.S32 ImGuiDataTypeInfo(4, "U32", "%u", "%u"), - ImGuiDataTypeInfo(4, "float", "%.3f", "%f"), - ImGuiDataTypeInfo(8, "double", "%f", "%lf"), - ImGuiDataTypeInfo(1, "bool", "%d", "%d"), - ImGuiDataTypeInfo(0, "string", "%s", "%s") + ImGuiDataTypeInfo(4, "float", "%.3f", "%f"), -- ImGuiDataType.Float + ImGuiDataTypeInfo(8, "double", "%f", "%lf"), -- ImGuiDataType.Double + ImGuiDataTypeInfo(1, "bool", "%d", "%d"), -- ImGuiDataType.Bool + ImGuiDataTypeInfo(0, "string", "%s", "%s") -- ImGuiDataType.String } --- @param data_type ImGuiDataType @@ -2203,12 +2445,15 @@ end local ImParseFormatSanitizeForScanning +-- User can input math operators (e.g. +100) to edit a numerical values. +-- NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess.. --- @param buf char[] --- @param data_type ImGuiDataType --- @param data number --- @param format string --- @param data_when_empty? number function ImGui.DataTypeApplyFromText(buf, data_type, data, format, data_when_empty) + -- Copy the value so we can compare at the end of the function if it changed at all. local type_info = ImGui.DataTypeGetInfo(data_type) local data_backup = data @@ -2224,16 +2469,19 @@ function ImGui.DataTypeApplyFromText(buf, data_type, data, format, data_when_emp return data, false end + -- Sanitize format + -- - For float/double we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in, so force them into %f and %lf local format_sanitized, format_sanitized_size = {}, 32 if (data_type == ImGuiDataType.Float or data_type == ImGuiDataType.Double) then format = type_info.ScanFmt else format = ImParseFormatSanitizeForScanning(format, format_sanitized, format_sanitized_size) if format[1] == 0 then - format = type_info.ScanFmt + format = type_info.ScanFmt -- Format doesn't want us to show the number currently, but we still need to parse the resulting input end end + -- Small types need a 32-bit buffer to receive the result from scanf() local v32 = 0 local res = {} if ImStd.sscanf(buf, 1, format, res) < 1 then @@ -2294,6 +2542,7 @@ end --- @param v_max? T --- @return T, boolean local function DataTypeClampT(v, v_min, v_max) + -- Clamp, both sides are optional, return true if modified if v_min and v < v_min then return v_min, true end if v_max and v > v_max then return v_max, true end return v, false @@ -2358,16 +2607,37 @@ function ImGui.RoundScalarWithFormatT(format, data_type, v) -- TODO: Sanitize format + -- Format value with our rounding, and read back local str = ImFormatString(format, v) v = ImAtof(str) or v return v end ----------------------------------------------------------------- --- [SECTION] INPUTXXX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. +------------------------------------------------------------------------------- +-- - ImParseFormatFindStart() [Internal] +-- - ImParseFormatFindEnd() [Internal] +-- - ImParseFormatTrimDecorations() [Internal] +-- - ImParseFormatSanitizeForScanning() [Internal] +-- - ImParseFormatPrecision() [Internal] +-- - TempInputText() [Internal] +-- - TempInputScalar() [Internal] +-- - InputScalar() +-- - InputScalarN() +-- - InputFloat() +-- - InputFloat2() +-- - InputFloat3() +-- - InputFloat4() +-- - InputInt() +-- - InputInt2() +-- - InputInt3() +-- - InputInt4() +-- - InputDouble() +------------------------------------------------------------------------------- +-- We don't use strchr() because our strings are usually very short and often start with '%' --- @param fmt string function ImParseFormatFindStart(fmt) local len = #fmt @@ -2388,7 +2658,7 @@ end --- @param fmt string --- @param pos int local function ImParseFormatFindEnd(fmt, pos) - -- Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format + -- Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format. if string.byte(fmt, pos) ~= 37 then -- '%' return pos end @@ -2408,6 +2678,10 @@ local function ImParseFormatFindEnd(fmt, pos) return len + 1 end +-- Extract the format out of a format string with leading or trailing decorations +-- fmt = "blah blah" -> return "" +-- fmt = "%.3f" -> return "%.3f" +-- fmt = "hello %.3f" -> return "%.3f" -- TODO: temporary patch. does not look good --- @param fmt string local function ImParseFormatTrimDecorations(fmt) @@ -2423,13 +2697,14 @@ local function ImParseFormatTrimDecorations(fmt) return string.sub(fmt, fmt_start, fmt_end) end +-- - For scanning we need to remove all width and precision fields and flags "%+3.7f" -> "%f". BUT don't strip types like "%I64d" which includes digits. ! "%07I64d" -> "%I64d" --- @param fmt_in string --- @param fmt_out char[] --- @param fmt_out_size size_t function ImParseFormatSanitizeForScanning(fmt_in, fmt_out, fmt_out_size) local fmt_end = ImParseFormatFindEnd(fmt_in, 1) -- IM_UNUSED(fmt_out_size) - IM_ASSERT(fmt_end < fmt_out_size) + IM_ASSERT(fmt_end < fmt_out_size) -- Format is too long, let us know if this happens to you! local has_type = false local fmt_in_begin = 1 local fmt_out_begin = 1 @@ -2442,15 +2717,15 @@ function ImParseFormatSanitizeForScanning(fmt_in, fmt_out, fmt_out_size) break end - has_type = has_type or ((c >= 97 and c <= 122) or (c >= 65 and c <= 90)) - if c ~= 39 and c ~= 36 and c ~= 95 then + has_type = has_type or ((c >= 97 and c <= 122) or (c >= 65 and c <= 90)) -- Stop skipping digits + if c ~= 39 and c ~= 36 and c ~= 95 then -- Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '. fmt_out[fmt_out_begin] = c fmt_out_begin = fmt_out_begin + 1 end until true end - -- fmt_out[fmt_out_begin] = 0 + -- fmt_out[fmt_out_begin] = 0 -- Zero-terminate return string.char(unpack(fmt_out)) -- FIXME: not ideal end @@ -2477,6 +2752,8 @@ local function ImAtoi(str, pos) return negative and -v or v, pos end +-- Parse display precision back from the display format string +-- FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed. --- @param fmt string --- @param default_precision int local function ImParseFormatPrecision(fmt, default_precision) @@ -2509,6 +2786,9 @@ local function ImParseFormatPrecision(fmt, default_precision) return (precision == INT_MAX) and default_precision or precision end +-- Create text input in place of another active widget (e.g. used when doing a Ctrl+Click on drag/slider widgets) +-- - This must be submitted right after the item it is overlaying. +-- FIXME: Facilitate using this in variety of other situations. --- @param bb ImRect --- @param id ImGuiID --- @param label string @@ -2520,6 +2800,8 @@ end function ImGui.TempInputText(bb, id, label, buf, buf_size, flags, callback, user_data) if flags == nil then flags = 0 end + -- On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id. + -- We clear ActiveID on the first frame to allow the InputText() taking it back. local g = GImGui local window = g.CurrentWindow @@ -2532,10 +2814,11 @@ function ImGui.TempInputText(bb, id, label, buf, buf_size, flags, callback, user local backup_pos = ImVec2() ImVec2_Copy(backup_pos, window.DC.CursorPos) ImVec2_Copy(window.DC.CursorPos, bb.Min) - g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowDuplicateId) + g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.AllowDuplicateId) -- Using ImGuiInputTextFlags.MergedItem above will skip ItemAdd() so we poke here. local value_changed = ImGui.InputTextEx(label, nil, buf, buf_size, bb:GetSize(), bit32.bor(flags, ImGuiInputTextFlags.TempInput, ImGuiInputTextFlags.AutoSelectAll), callback, user_data) - ImGui.KeepAliveID(id) + ImGui.KeepAliveID(id) -- Not done because of ImGuiInputTextFlags.TempInput if (not is_active and not is_deactivated) then + -- First frame we started displaying the InputText widget, we expect it to take the active id. IM_ASSERT(g.ActiveId == id) g.TempInputId = g.ActiveId end @@ -2547,6 +2830,9 @@ function ImGui.TempInputText(bb, id, label, buf, buf_size, flags, callback, user return value_changed end +-- Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags.AlwaysClamp flag is set! +-- This is intended: this way we allow Ctrl+Click manual input to set a value out of bounds, for maximum flexibility. +-- However this may not be ideal for all uses, as some user code may break on out of bound values. --- @param bb ImRect --- @param id ImGuiID --- @param label string @@ -2556,6 +2842,8 @@ end --- @param clamp_min? number --- @param clamp_max? number function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min, clamp_max) + -- FIXME: May need to clarify display behavior if format doesn't contain %. + -- "%d" -> "%d" / "There are %d items" -> "%d" / "items" -> "%d" (fallback). Also see #6405 local g = GImGui local type_info = ImGui.DataTypeGetInfo(data_type) local data_buf, data_buf_size = {}, 32 @@ -2567,14 +2855,16 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min ImStd.ImStrTrimBlanks(data_buf) local flags = bit32.bor(ImGuiInputTextFlags.AutoSelectAll, ImGuiInputTextFlags.LocalizeDecimalPoint) - g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited) + g.LastItemData.ItemFlags = bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.NoMarkEdited) -- Because TempInputText() uses ImGuiInputTextFlags.MergedItem it doesn't submit a new item, so we poke LastItemData. g.LastItemData.ItemFlags = (bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0) and bit32.bor(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputText) or bit32.band(g.LastItemData.ItemFlags, bit32.bnot(ImGuiItemFlags.LiveEditOnInputText)) if not ImGui.TempInputText(bb, id, label, data_buf, data_buf_size, flags) then return data, false end + -- Backup old value local data_backup = data + -- Apply new value (or operations) then clamp data = ImGui.DataTypeApplyFromText(data_buf, data_type, data, format, nil) if clamp_min or clamp_max then if clamp_min and clamp_max and ImGui.DataTypeCompare(data_type, clamp_min, clamp_max) > 0 then @@ -2583,6 +2873,7 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min data = ImGui.DataTypeClamp(data_type, data, clamp_min, clamp_max) end + -- Only mark as edited if new value is different g.LastItemData.ItemFlags = bit32.band(g.LastItemData.ItemFlags, bit32.bnot(ImGuiItemFlags.NoMarkEdited)) local value_changed = data_backup ~= data if value_changed then @@ -2592,6 +2883,8 @@ function ImGui.TempInputScalar(bb, id, label, data_type, data, format, clamp_min return data, value_changed end +-- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For an Input widget, step and step_fast are optional. +-- Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @param label string --- @param data_type ImGuiDataType --- @param data number @@ -2609,6 +2902,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag local g = GImGui local style = g.Style + -- IM_ASSERT((flags & ImGuiInputTextFlags.EnterReturnsTrue) == 0) -- Not supported by InputScalar(). Please open an issue if you this would be useful to you. Otherwise use IsItemDeactivatedAfterEdit()! if format == nil then format = ImGui.DataTypeGetInfo(data_type).PrintFmt @@ -2623,6 +2917,8 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag ImGui.DataTypeFormatString(buf, buf_size, data_type, data, format) end + -- Disable the MarkItemEdited() call in InputText but keep ImGuiItemStatusFlags.Edited. + -- We call MarkItemEdited() ourselves by comparing the actual data rather than the string. g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoMarkEdited) flags = bit32.bor(flags, ImGuiInputTextFlags.AutoSelectAll, ImGuiInputTextFlags.LocalizeDecimalPoint) @@ -2630,18 +2926,21 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag local button_size = has_step_buttons and ImGui.GetFrameHeight() or 0.0 local ret if has_step_buttons then - ImGui.BeginGroup() + -- With Step Buttons + ImGui.BeginGroup() -- The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() ImGui.PushID(label) ImGui.SetNextItemWidth(ImMax(1.0, ImGui.CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)) - ret = ImGui.InputText("", buf, buf_size, flags) + ret = ImGui.InputText("", buf, buf_size, flags) -- PushID(label) + "" gives us the expected ID from outside point of view -- IMGUI_TEST_ENGINE_ITEM_INFO() else + -- Without Step Buttons ret = ImGui.InputText(label, buf, buf_size, flags) end + -- Apply local value_changed = false if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0 then - local input_edited = bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal) ~= 0 + local input_edited = bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.EditedInternal) ~= 0 -- We would be using 'ret' if ImGuiInputTextFlags.EnterReturnsTrue was not involved. if input_edited then data, value_changed = ImGui.DataTypeApplyFromText(buf, data_type, data, format, bit32.band(flags, ImGuiInputTextFlags.ParseEmptyRefVal) ~= 0 and data_default or nil) end @@ -2654,6 +2953,7 @@ function ImGui.InputScalar(label, data_type, data, step, step_fast, format, flag end end + -- Step buttons if has_step_buttons then local backup_frame_padding = ImVec2() ImVec2_Copy(backup_frame_padding, style.FramePadding) @@ -2786,6 +3086,7 @@ function ImGui.InputInt(label, v, step, step_fast, flags) if step_fast == nil then step_fast = 100 end if flags == nil then flags = 0 end + -- Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. local format = (bit32.band(flags, ImGuiInputTextFlags.CharsHexadecimal) ~= 0) and "%08X" or "%d" return ImGui.InputScalar(label, ImGuiDataType.S32, v, (step > 0) and step or nil, (step_fast > 0) and step_fast or nil, format, flags) end @@ -2818,9 +3119,24 @@ function ImGui.InputDouble(label, v, step, step_fast, format, flags) return ImGui.InputScalar(label, ImGuiDataType.Double, v, (step > 0.0 and step or nil), (step_fast > 0.0 and step_fast or nil), format, flags) end ----------------------------------------------------------------- --- [SECTION] DRAGXXX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. +------------------------------------------------------------------------------- +-- - DragBehaviorT<>() [Internal] +-- - DragBehavior() [Internal] +-- - DragScalar() +-- - DragScalarN() +-- - DragFloat() +-- - DragFloat2() +-- - DragFloat3() +-- - DragFloat4() +-- - DragFloatRange2() +-- - DragInt() +-- - DragInt2() +-- - DragInt3() +-- - DragInt4() +-- - DragIntRange2() +------------------------------------------------------------------------------- -- This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) --- @generic T : number @@ -2884,7 +3200,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m end adjust_delta = adjust_delta * v_speed - -- For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter + -- For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter. if axis == ImGuiAxis.Y then adjust_delta = -adjust_delta end @@ -2939,7 +3255,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m v_cur = ImGui.RoundScalarWithFormatT(format, data_type, v_cur) end - -- Preserve remainder after rounding has been applied. This also allow slow tweaking of values + -- Preserve remainder after rounding has been applied. This also allow slow tweaking of values. g.DragCurrentAccumDirty = false if is_logarithmic then -- Convert to parametric space, apply delta, convert back @@ -2949,7 +3265,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m g.DragCurrentAccum = g.DragCurrentAccum - ((SIGNEDTYPE)(v_cur) - (SIGNEDTYPE)(v)) end - -- This does nothing + -- Lose zero sign for float/double if v_cur == (TYPE)(-0) then v_cur = (TYPE)(0) end @@ -2964,7 +3280,7 @@ function ImGui.DragBehaviorT(TYPE, SIGNEDTYPE, data_type, v, v_speed, v_min, v_m v_cur = (TYPE)(v_cur - (TYPE)((TYPE)(v_max - v_min) - (is_floating_point and 0 or 1))) end else - -- Clamp values + handle overflow/wrap-around for integer types + -- Clamp values + handle overflow/wrap-around for integer types. if v_cur < v_min or (v_cur > v and adjust_delta < 0.0 and not is_floating_point) then v_cur = (TYPE)(v_min) end @@ -2992,8 +3308,10 @@ end --- @param flags ImGuiSliderFlags @native function ImGui.DragBehavior(id, data_type, v, v_speed, min, max, format, flags) + -- Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. IM_ASSERT((flags == 1 or bit32.band(flags, ImGuiSliderFlags.InvalidMask_) == 0), "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.") + -- Things we can do easily outside the DragBehaviorT<> template, saves code generation. local g = GImGui if g.ActiveId == id then if g.ActiveIdSource == ImGuiInputSource.Mouse and not g.IO.MouseDown[0] then @@ -3031,6 +3349,7 @@ function ImGui.DragBehavior(id, data_type, v, v_speed, min, max, format, flags) return v, false end +-- Only clamp Ctrl+Click input when ImGuiSliderFlags.ClampOnInput is set (generally via ImGuiSliderFlags.AlwaysClamp) --- @param flags ImGuiSliderFlags --- @param data_type ImGuiDataType --- @param min number @@ -3039,7 +3358,7 @@ local function TempInputIsClampEnabled(flags, data_type, min, max) if bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 and (min ~= nil or max ~= nil) then local clamp_range_dir = 0 if min ~= nil and max ~= nil then - clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) + clamp_range_dir = ImGui.DataTypeCompare(data_type, min, max) -- -1 when min < max, == 0 when min == max end if min == nil or max == nil or clamp_range_dir < 0 then return true @@ -3074,6 +3393,8 @@ function FormatCached(format, v) return r end +-- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a Drag widget, min and max are optional. +-- Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. @native function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, flags) if v_speed == nil then v_speed = 1.0 end @@ -3108,6 +3429,7 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla local hovered = ImGui.ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags) local temp_input_is_active = temp_input_allowed and ImGui.TempInputIsActive(id) if not temp_input_is_active then + -- Tabbing or Ctrl+Click on Drag turns it into an InputText local clicked = hovered and ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, id) local double_clicked = (hovered and g.IO.MouseClickedCount[0] == 2 and ImGui.TestKeyOwner(ImGuiKey.MouseLeft, id)) local make_active = (clicked or double_clicked or g.NavActivateId == id) @@ -3167,7 +3489,7 @@ function ImGui.DragScalar(label, data_type, data, v_speed, min, max, format, fla -- TODO: ImGui.DataTypeFormatString() should be used here instead of ImFormatString() - -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value + -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value. ImGui.RenderTextClipped(frame_bb.Min, frame_bb.Max, FormatCached(format, data), nil, nil, DRAG_TEXT_ALIGN) if label_size.x > 0.0 then @@ -3194,6 +3516,7 @@ function ImGui.DragFloat(label, v, v_speed, v_min, v_max, format, flags) return ImGui.DragScalar(label, ImGuiDataType.Float, v, v_speed, v_min, v_max, format, flags) end +-- NB: v_speed is float to allow adjusting the drag speed with more precision --- @param label string --- @param v int --- @param v_speed? float @@ -3270,7 +3593,7 @@ ImGui.DragInt2 = DragIntN(2) ImGui.DragInt3 = DragIntN(3) ImGui.DragInt4 = DragIntN(4) --- NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this. +-- NB: You likely want to specify the ImGuiSliderFlags.AlwaysClamp when using this. --- @return float v_current_min --- @return float v_current_max --- @return bool value_changed @@ -3318,9 +3641,28 @@ function ImGui.DragIntRange2(label, v_current_min, v_current_max, v_speed, v_min return DragRange2(ImGuiDataType.S32, label, v_current_min, v_current_max, v_speed or 1.0, v_min or 0, v_max or 0, format or "%d", format_max, flags or 0) end ----------------------------------------------------------------- --- [SECTION] SLIDERXXX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. +------------------------------------------------------------------------------- +-- - ScaleRatioFromValueT<> [Internal] +-- - ScaleValueFromRatioT<> [Internal] +-- - SliderBehaviorT<>() [Internal] +-- - SliderBehavior() [Internal] +-- - SliderScalar() +-- - SliderScalarN() +-- - SliderFloat() +-- - SliderFloat2() +-- - SliderFloat3() +-- - SliderFloat4() +-- - SliderAngle() +-- - SliderInt() +-- - SliderInt2() +-- - SliderInt3() +-- - SliderInt4() +-- - VSliderScalar() +-- - VSliderFloat() +-- - VSliderInt() +------------------------------------------------------------------------------- -- Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT) --- @param data_type ImGuiDataType @@ -3466,7 +3808,11 @@ function ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, t, v_min, v_max local is_floating_point = (data_type == ImGuiDataType.Float) or (data_type == ImGuiDataType.Double) if is_floating_point then result = ImLerp(v_min, v_max, t) - elseif t < 1.0 then + elseif t < 1.0 then -- t is already < 1.0 here + -- - For integer values we want the clicking position to match the grab box so we round above + -- This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. + -- - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64 + -- range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits. local v_new_off_f = (SIGNEDTYPE)((v_max - v_min)) * t result = (TYPE)((SIGNEDTYPE)(v_min) + (SIGNEDTYPE)(v_new_off_f + 0)) -- LUA: + 0 instead of + ((v_min > v_max) and -0.5 or 0.5) end @@ -3475,6 +3821,7 @@ function ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, t, v_min, v_max return result end +-- FIXME: Try to move more of the code into shared SliderBehavior() --- @generic T : number --- @param TYPE fun(val: number): T --- @param SIGNEDTYPE fun(val: number): T @@ -3496,27 +3843,30 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ local axis = (bit32.band(flags, ImGuiSliderFlags.Vertical) ~= 0) and ImGuiAxis.Y or ImGuiAxis.X local is_logarithmic = bit32.band(flags, ImGuiSliderFlags.Logarithmic) ~= 0 local is_floating_point = (data_type == ImGuiDataType.Float) or (data_type == ImGuiDataType.Double) - local v_range_f = (v_min < v_max) and (v_max - v_min) or (v_min - v_max) + local v_range_f = (v_min < v_max) and (v_max - v_min) or (v_min - v_max) -- We don't need high precision for what we do with it. - local grab_padding = 2.0 + -- Calculate bounds + local grab_padding = 2.0 -- FIXME: Should be part of style. local slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0 local grab_sz = style.GrabMinSize - if not is_floating_point and v_range_f >= 0.0 then - grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize) + if not is_floating_point and v_range_f >= 0.0 then -- v_range_f < 0 may happen on integer overflows + grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize) -- For integer sliders: if possible have the grab size represent 1 unit end grab_sz = ImMin(grab_sz, slider_sz) local slider_usable_sz = slider_sz - grab_sz local slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5 local slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5 - local logarithmic_zero_epsilon = 0.0 - local zero_deadzone_halfsize = 0.0 + local logarithmic_zero_epsilon = 0.0 -- Only valid when is_logarithmic is true + local zero_deadzone_halfsize = 0.0 -- Only valid when is_logarithmic is true if is_logarithmic then + -- When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound. local decimal_precision = is_floating_point and ImParseFormatPrecision(format, 3) or 1 logarithmic_zero_epsilon = ImPow(0.1, decimal_precision) zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5) / ImMax(slider_usable_sz, 1.0) end + -- Process interacting with the slider local value_changed = false if g.ActiveId == id then local set_new_value = false @@ -3532,7 +3882,7 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ grab_t = 1.0 - grab_t end local grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t) - local clicked_around_grab = (mouse_abs_pos >= grab_pos - grab_sz * 0.5 - 1.0) and (mouse_abs_pos <= grab_pos + grab_sz * 0.5 + 1.0) + local clicked_around_grab = (mouse_abs_pos >= grab_pos - grab_sz * 0.5 - 1.0) and (mouse_abs_pos <= grab_pos + grab_sz * 0.5 + 1.0) -- No harm being extra generous here. g.SliderGrabClickOffset = (clicked_around_grab and is_floating_point) and (mouse_abs_pos - grab_pos) or 0.0 end if slider_usable_sz > 0.0 then @@ -3545,7 +3895,7 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ end elseif g.ActiveIdSource == ImGuiInputSource.Keyboard or g.ActiveIdSource == ImGuiInputSource.Gamepad then if g.ActiveIdIsJustActivated then - g.SliderCurrentAccum = 0.0 + g.SliderCurrentAccum = 0.0 -- Reset any stored nav delta upon activation g.SliderCurrentAccumDirty = false end @@ -3555,13 +3905,13 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ local tweak_fast = ImGui.IsKeyDown((g.NavInputSource == ImGuiInputSource.Gamepad) and ImGuiKey.NavGamepadTweakFast or ImGuiKey.NavKeyboardTweakFast) local decimal_precision = is_floating_point and ImParseFormatPrecision(format, 3) or 0 if decimal_precision > 0 then - input_delta = input_delta / 100.0 + input_delta = input_delta / 100.0 -- Keyboard/Gamepad tweak speeds in % of slider bounds if tweak_slow then input_delta = input_delta / 10.0 end else if (v_range_f >= -100.0 and v_range_f <= 100.0 and v_range_f ~= 0.0) or tweak_slow then - input_delta = ((input_delta < 0.0) and -1.0 or 1.0) / v_range_f + input_delta = ((input_delta < 0.0) and -1.0 or 1.0) / v_range_f -- Keyboard/Gamepad tweak speeds in integer steps else input_delta = input_delta / 100.0 end @@ -3580,14 +3930,15 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ elseif g.SliderCurrentAccumDirty then clicked_t = ImGui.ScaleRatioFromValueT(data_type, v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) - if (clicked_t >= 1.0 and delta > 0.0) or (clicked_t <= 0.0 and delta < 0.0) then + if (clicked_t >= 1.0 and delta > 0.0) or (clicked_t <= 0.0 and delta < 0.0) then -- This is to avoid applying the saturation when already past the limits set_new_value = false - g.SliderCurrentAccum = 0.0 + g.SliderCurrentAccum = 0.0 -- If pushing up against the limits, don't continue to accumulate else set_new_value = true local old_clicked_t = clicked_t clicked_t = ImSaturate(clicked_t + delta) + -- Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator local v_new = ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) if is_floating_point and bit32.band(flags, ImGuiSliderFlags.NoRoundToFormat) == 0 then v_new = ImGui.RoundScalarWithFormatT(format, data_type, v_new) @@ -3614,10 +3965,12 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ if set_new_value then local v_new = ImGui.ScaleValueFromRatioT(TYPE, SIGNEDTYPE, data_type, clicked_t, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) + -- Round to user desired precision based on format string if is_floating_point and bit32.band(flags, ImGuiSliderFlags.NoRoundToFormat) == 0 then v_new = ImGui.RoundScalarWithFormatT(format, data_type, v_new) end + -- Apply result if v ~= v_new then v = v_new value_changed = true @@ -3628,6 +3981,7 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ if slider_sz < 1.0 then ImRect_Copy(out_grab_bb, ImRect(bb.Min, bb.Min)) else + -- Output grab position so it can be displayed by the caller local grab_t = ImGui.ScaleRatioFromValueT(data_type, v, v_min, v_max, logarithmic_zero_epsilon, zero_deadzone_halfsize) if axis == ImGuiAxis.Y then grab_t = 1.0 - grab_t @@ -3643,6 +3997,9 @@ function ImGui.SliderBehaviorT(TYPE, SIGNEDTYPE, bb, id, data_type, v, v_min, v_ return v, value_changed end +-- For 32-bit and larger types, slider bounds are limited to half the natural type range. +-- So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. +-- It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. --- @generic T : number --- @param bb ImRect --- @param id ImGuiID @@ -3656,8 +4013,9 @@ end --- @return T v --- @return bool value_changed function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out_grab_bb) + -- Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert. IM_ASSERT((flags == 1 or bit32.band(flags, ImGuiSliderFlags.InvalidMask_) == 0), "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.") - IM_ASSERT(bit32.band(flags, ImGuiSliderFlags.WrapAround) == 0) + IM_ASSERT(bit32.band(flags, ImGuiSliderFlags.WrapAround) == 0) -- Not supported by SliderXXX(), only by DragXXX() if data_type == ImGuiDataType.S8 then local v32 = (ImS32)((ImS8)(v)); local r @@ -3697,6 +4055,8 @@ function ImGui.SliderBehavior(bb, id, data_type, v, min, max, format, flags, out return v, false end +-- Note: data is passed by value and the new value is returned: Returns (data, value_changed). For a slider, min and max are required. +-- Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly. --- @generic T : number --- @param label string --- @param data_type ImGuiDataType @@ -3732,6 +4092,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) return data, false end + -- Default format string when passing NULL if format == nil then format = ImGui.DataTypeGetInfo(data_type).PrintFmt end @@ -3739,6 +4100,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) local hovered = ImGui.ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags) local temp_input_is_active = temp_input_allowed and ImGui.TempInputIsActive(id) if not temp_input_is_active then + -- Tabbing or Ctrl+Click on Slider turns it into an input box local clicked = hovered and ImGui.IsMouseClickedEx(0, ImGuiInputFlags.None, id) local make_active = clicked or g.NavActivateId == id if make_active and clicked then @@ -3750,6 +4112,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) end end + -- Store initial value (not used by main lib but available as a convenience but some mods e.g. to revert) if make_active then g.ActiveIdValueOnActivation = data end @@ -3763,10 +4126,12 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) end if temp_input_is_active then - local clamp_enabled = bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 + -- Only clamp Ctrl+Click input when ImGuiSliderFlags.ClampOnInput is set (generally via ImGuiSliderFlags.AlwaysClamp) + local clamp_enabled = bit32.band(flags, ImGuiSliderFlags.ClampOnInput) ~= 0 -- Don't use TempInputIsClampEnabled() return ImGui.TempInputScalar(frame_bb, id, label, data_type, data, format, clamp_enabled and min or nil, clamp_enabled and max or nil) end + -- Draw frame local frame_col = ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.FrameBgActive or (hovered and ImGuiCol.FrameBgHovered or ImGuiCol.FrameBg)) ImGui.RenderNavCursor(frame_bb, id) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, false, style.FrameRounding) @@ -3775,6 +4140,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) end ImGui.RenderFrameBorder(frame_bb.Min, frame_bb.Max, g.Style.FrameRounding) + -- Slider behavior local grab_bb = ImRect() local value_changed data, value_changed = ImGui.SliderBehavior(frame_bb, id, data_type, data, min, max, format, flags, grab_bb) @@ -3782,12 +4148,14 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) ImGui.MarkItemEdited(id) end + -- Render grab if grab_bb.Max.x > grab_bb.Min.x then window.DrawList:AddRectFilled(grab_bb.Min, grab_bb.Max, ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.SliderGrabActive or ImGuiCol.SliderGrab), style.GrabRounding) end -- TODO: ImGui.DataTypeFormatString() should be used here instead of ImFormatString() + -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value. -- if g.LogEnabled then -- ImGui.LogSetNextTextDecoration("{", "}") -- end @@ -3801,6 +4169,7 @@ function ImGui.SliderScalar(label, data_type, data, min, max, format, flags) return data, value_changed end +-- Add multiple sliders on 1 line for compact edition of multiple components --- @param label string --- @param data_type ImGuiDataType --- @param v table @@ -3969,6 +4338,7 @@ function ImGui.VSliderScalar(label, size, data_type, data, min, max, format, fla return data, false end + -- Default format string when passing NULL if format == nil then format = ImGui.DataTypeGetInfo(data_type).PrintFmt end @@ -3985,10 +4355,12 @@ function ImGui.VSliderScalar(label, size, data_type, data, min, max, format, fla g.ActiveIdUsingNavDirMask = bit32.bor(g.ActiveIdUsingNavDirMask, bit32.lshift(1, ImGuiDir.Up), bit32.lshift(1, ImGuiDir.Down)) end + -- Draw frame local frame_col = ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.FrameBgActive or (hovered and ImGuiCol.FrameBgHovered or ImGuiCol.FrameBg)) ImGui.RenderNavCursor(frame_bb, id) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding) + -- Slider behavior local grab_bb = ImRect() local value_changed data, value_changed = ImGui.SliderBehavior(frame_bb, id, data_type, data, min, max, format, bit32.bor(flags or 0, ImGuiSliderFlags.Vertical), grab_bb) @@ -3996,10 +4368,13 @@ function ImGui.VSliderScalar(label, size, data_type, data, min, max, format, fla ImGui.MarkItemEdited(id) end + -- Render grab if grab_bb.Max.y > grab_bb.Min.y then window.DrawList:AddRectFilled(grab_bb.Min, grab_bb.Max, ImGui.GetColorU32((g.ActiveId == id) and ImGuiCol.SliderGrabActive or ImGuiCol.SliderGrab), style.GrabRounding) end + -- Display value using user-provided display format so user can add prefix/suffix/decorations to the value. + -- For the vertical slider we allow centered text to overlap the frame padding -- local value_buf, value_buf_size = {}, 64 -- TODO: ImGui.DataTypeFormatString() ImGui.RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, ImFormatString(format, data), nil, nil, ImVec2(0.5, 0.0)) @@ -4037,9 +4412,16 @@ function ImGui.VSliderInt(label, size, v, v_min, v_max, format, flags) return ImGui.VSliderScalar(label, size, ImGuiDataType.S32, v, v_min, v_max, format, flags) end ----------------------------------------------------------------- --- [SECTION] INPUT TEXT ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint +------------------------------------------------------------------------------- +-- - imstb_textedit.h include +-- - InputText() +-- - InputTextWithHint() +-- - InputTextMultiline() +-- - InputTextEx() [Internal] +-- - DebugNodeInputTextState() [Internal] +------------------------------------------------------------------------------- --- @param label string --- @param buf char[] @@ -4050,7 +4432,7 @@ end function ImGui.InputText(label, buf, buf_size, flags, callback, user_data) if flags == nil then flags = 0 end - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) -- call InputTextMultiline() return ImGui.InputTextEx(label, nil, buf, buf_size, ImVec2(0, 0), flags, callback, user_data) end @@ -4098,6 +4480,11 @@ local function InputTextCalcTextSize(ctx, text, text_begin, text_end_display, te return ImFontCalcTextSizeEx(g.Font, g.FontSize, FLT_MAX, obj.WrapWidth, text, text_begin, text_end_display, text_end, out_offset, flags) end +-- 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) +-- With our UTF-8 use of stb_textedit: +-- - STB_TEXTEDIT_GETCHAR is nothing more than a a "GETBYTE". It's only used to compare to ascii or to copy blocks of text so we are fine. +-- - One exception is the STB_TEXTEDIT_IS_SPACE feature which would expect a full char in order to handle full-width space such as 0x3000 (see ImCharIsBlankW). +-- - ...but we don't use that feature. --- @param obj ImGuiInputTextState --- @return int function ImStb.TEXTEDIT_STRINGLEN(obj) return obj.TextLen end @@ -4168,7 +4555,7 @@ end --- @param obj ImGuiInputTextState --- @param idx int function ImStb.is_word_boundary_from_right(obj, idx) - -- When ImGuiInputTextFlags.Password is set, we don't want actions such as Ctrl+Arrow to leak the fact that underlying data are blanks or separators + -- When ImGuiInputTextFlags.Password is set, we don't want actions such as Ctrl+Arrow to leak the fact that underlying data are blanks or separators. if bit32.band(obj.Flags, ImGuiInputTextFlags.Password) ~= 0 or idx <= 1 then return false end @@ -4245,7 +4632,7 @@ function ImStb.TEXTEDIT_MOVEWORDRIGHT(obj, idx) end end --- Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping +-- Reimplementation of stb_textedit_move_line_start()/stb_textedit_move_line_end() which supports word-wrapping. --- @param obj ImGuiInputTextState --- @param state STB_TexteditState --- @param cursor int @@ -4322,6 +4709,7 @@ end --- @param pos int --- @param n int function ImStb.TEXTEDIT_DELETECHARS(obj, pos, n) + -- Offset remaining text (+ copy zero terminator) IM_ASSERT(obj.TextSrc == obj.TextA.Data) ImStd.memmove(obj.TextA.Data, pos, obj.TextA.Data, pos + n, obj.TextLen - n - pos + 2) obj.EditedBefore = true @@ -4339,10 +4727,10 @@ function ImStb.TEXTEDIT_INSERTCHARS(obj, pos, new_text, new_text_pos, new_text_l local text_len = obj.TextLen IM_ASSERT(pos <= text_len + 1) - -- We support partial insertion (with a mod in stb_textedit) + -- We support partial insertion (with a mod in stb_textedit.h) local avail = obj.BufCapacity - 1 - obj.TextLen if not is_resizable and new_text_len > avail then - new_text_len = math.floor(ImStd.ImTextFindValidUtf8CodepointEnd(new_text, new_text_pos, new_text_len + 1, avail) - new_text_pos) -- Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion + new_text_len = math.floor(ImStd.ImTextFindValidUtf8CodepointEnd(new_text, new_text_pos, new_text_len + 1, avail) - new_text_pos) -- Truncate to closest UTF-8 codepoint. Alternative: return 0 to cancel insertion. end if new_text_len == 0 then return 0 @@ -4371,6 +4759,8 @@ end stbte = IM_INCLUDE"imstb_textedit.lua" +-- stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling +-- the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?) --- @param str ImGuiInputTextState --- @param state STB_TexteditState --- @param text IMSTB_TEXTEDIT_CHARTYPE[] @@ -4429,8 +4819,8 @@ function MT.ImGuiInputTextState:OnCharPressed(c) self:CursorAnimReset() end --- After a user-input the cursor stays on for a while without blinking -function MT.ImGuiInputTextState:CursorAnimReset() self.CursorAnim = -0.30 end +-- Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header. +function MT.ImGuiInputTextState:CursorAnimReset() self.CursorAnim = -0.30 end -- After a user-input the cursor stays on for a while without blinking function MT.ImGuiInputTextState:CursorClamp() self.Stb.cursor = ImMin(self.Stb.cursor, self.TextLen + 1) @@ -4475,6 +4865,7 @@ function ImGui.PopPasswordFont() IM_ASSERT(backup.IndexAdvanceX.Size == 0 and backup.IndexLookup.Size == 0) end +-- Return false to discard a character. Returns (char, ok). --- @param ctx ImGuiContext --- @param state ImGuiInputTextState --- @param char unsigned_int @@ -4615,7 +5006,7 @@ 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 +-- 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. --- @param state ImGuiInputTextState --- @param old_buf ImStringBuffer --- @param old_length int @@ -4658,6 +5049,10 @@ local function InputTextReconcileUndoState(state, old_buf, old_length, new_buf, end end +-- As InputText() retain textual data and we currently provide a path for user to not retain it (via local variables) +-- we need some form of hook to reapply data back to user buffer on deactivation frame. (#4714) +-- It would be more desirable that we discourage users from taking advantage of the "user not retaining data" trick, +-- but that more likely be attractive when we do have _NoLiveEdit flag available. --- @param id ImGuiID function ImGui.InputTextDeactivateHook(id) local g = GImGui @@ -4673,7 +5068,7 @@ function ImGui.InputTextDeactivateHook(id) g.InputTextDeactivatedState.ID = state.ID g.InputTextDeactivatedState.ElapseFrame = g.FrameCount + 1 if bit32.band(state.Flags, ImGuiInputTextFlags.ReadOnly) ~= 0 then - g.InputTextDeactivatedState.TextA:resize(0) -- In theory this data won't be used, but clear to be neat + g.InputTextDeactivatedState.TextA:resize(0) -- In theory this data won't be used, but clear to be neat. else IM_ASSERT(state.TextA.Data ~= nil) -- IM_ASSERT(state.TextA[state.TextLen + 1] == 0) @@ -4682,6 +5077,8 @@ function ImGui.InputTextDeactivateHook(id) end end +-- 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) --- @param flags ImGuiInputTextFlags --- @param line_index ImGuiTextIndex --- @param buf char[] @@ -4810,6 +5207,8 @@ local function InputTextLineIndexGetPosOffset(g, state, line_index, buf, buf_end end -- Edit a string of text +-- - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!". +-- - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect. --- @param label string --- @param hint? char[] --- @param buf char[] @@ -4840,9 +5239,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback IM_ASSERT(buf ~= nil and buf_size >= 0) IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.CallbackHistory) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Can't use both together (they both use up/down keys) IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.CallbackCompletion) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0)) -- Can't use both together (they both use tab key) - IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Multiline does not not work with left-trimming - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Password) == 0) -- WordWrap does not work with Password mode - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0) -- WordWrap does not work in single-line mode + IM_ASSERT(not (bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0)) -- Multiline does not work with left-trimming + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Password) == 0) -- WordWrap does not work with Password mode. + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.WordWrap) == 0 or bit32.band(flags, ImGuiInputTextFlags.Multiline) ~= 0) -- WordWrap does not work in single-line mode. local g = GImGui --[[@as ImGuiContext]] local io = g.IO @@ -4879,18 +5278,18 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback ImGuiLastItemData_Copy(item_data_backup, g.LastItemData) ImVec2_Copy(window.DC.CursorPos, backup_pos) - -- Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping + -- Prevent NavActivation from explicit Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping. if g.NavActivateId == id and (bit32.band(g.NavActivateFlags, ImGuiActivateFlags.FromTabbing) ~= 0) and (bit32.band(g.NavActivateFlags, ImGuiActivateFlags.FromFocusApi) == 0) and (bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0) then g.NavActivateId = 0 end - -- Prevent NavActivate reactivating in BeginChild() when we are already active + -- Prevent NavActivate reactivating in BeginChild() when we are already active. local backup_activate_id = g.NavActivateId if g.ActiveId == id then -- Prevent reactivation g.NavActivateId = 0 end - -- We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug + -- We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug. ImGui.PushStyleColor(ImGuiCol.ChildBg, style.Colors[ImGuiCol.FrameBg]) ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.FrameRounding) ImGui.PushStyleVar(ImGuiStyleVar.ChildBorderSize, style.FrameBorderSize) @@ -4905,7 +5304,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback return false end draw_window = g.CurrentWindow -- Child window - draw_window.DC.NavLayersActiveMaskNext = bit32.bor(draw_window.DC.NavLayersActiveMaskNext, bit32.lshift(1, draw_window.DC.NavLayerCurrent)) -- This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it + draw_window.DC.NavLayersActiveMaskNext = bit32.bor(draw_window.DC.NavLayersActiveMaskNext, bit32.lshift(1, draw_window.DC.NavLayerCurrent)) -- This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it. ImVec2_Copy(draw_window.DC.CursorPos, draw_window.DC.CursorPos + style.FramePadding) inner_size.x = inner_size.x - draw_window.ScrollbarSizes.x @@ -4914,6 +5313,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback g.LastItemData.ItemFlags = item_data_backup.ItemFlags g.LastItemData.StatusFlags = item_data_backup.StatusFlags else + -- Support for internal ImGuiInputTextFlags.MergedItem flag, which could be redesigned as an ItemFlags if needed (with test performed in ItemAdd) ImGui.ItemSize(total_bb, style.FramePadding.y) if bit32.band(flags, ImGuiInputTextFlags.TempInput) == 0 then @@ -4932,7 +5332,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback hovered = false end - -- We are only allowed to access the state if we are already the active widget + -- We are only allowed to access the state if we are already the active widget. local state = ImGui.GetInputTextState(id) if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.ReadOnly) ~= 0 then @@ -4967,8 +5367,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local scroll_y = is_multiline and draw_window.Scroll.y or FLT_MAX local init_reload_from_user_buf = (state ~= nil and state.WantReloadUserBuf) - local init_changed_specs_multiline = (state ~= nil and (state.Stb.single_line ~= (not is_multiline))) - local init_changed_specs_readonly = (state ~= nil and (bit32.band(bit32.bxor(state.Flags, flags), ImGuiInputTextFlags.ReadOnly) ~= 0)) -- state ~= nil means it's our state + local init_changed_specs_multiline = (state ~= nil and (state.Stb.single_line ~= (not is_multiline))) -- state ~= nil means its our state. + local init_changed_specs_readonly = (state ~= nil and (bit32.band(bit32.bxor(state.Flags, flags), ImGuiInputTextFlags.ReadOnly) ~= 0)) -- state ~= nil means its our state. local init_make_active = (input_requested_by_user or input_requested_by_nav or input_requested_by_reactivate or user_scroll_finish) if init_reload_from_user_buf then local new_len = ImStd.ImStrlen(buf) @@ -4976,14 +5376,14 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.WantReloadUserBuf = false --- @cast state ImGuiInputTextState InputTextReconcileUndoState(state, state.TextA.Data, state.TextLen, buf, new_len) - state.TextA:resize(buf_size + 1) + 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 ImStd.memmove(state.TextA.Data, 1, buf, 1, state.TextLen + 1) state.Stb.select_start = state.ReloadSelectionStart state.Stb.cursor = state.ReloadSelectionEnd state.Stb.select_end = state.ReloadSelectionEnd -- will be clamped to bounds below elseif (init_make_active and g.ActiveId ~= id) or init_changed_specs_multiline or init_changed_specs_readonly then - -- Access state even if we don't own it yet + -- Access state even if we don't own it yet. state = g.InputTextState state:CursorAnimReset() @@ -4997,7 +5397,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local buf_len = ImStd.ImStrlen(buf) IM_ASSERT(((buf_len + 1 <= buf_size) or (buf_len == 0 and buf_size == 0)), "Is your input buffer properly zero-terminated?") if not user_scroll_finish then - state.TextToRevertTo:resize(buf_len + 1) + 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. ImStd.memmove(state.TextToRevertTo.Data, 1, buf, 1, buf_len + 1) end @@ -5013,7 +5413,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.TextLen = buf_len state.EditedBefore = false if not is_readonly then - state.TextA:resize(buf_size + 1) + state.TextA:resize(buf_size + 1) -- we use +1 to make sure that .Data is always pointing to at least an empty string. ImStd.memmove(state.TextA.Data, 1, buf, 1, state.TextLen + 1) end @@ -5024,7 +5424,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end -- 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 + -- Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. if not recycle_state then stbte.initialize_state(state.Stb, not is_multiline) end @@ -5058,8 +5458,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end if g.ActiveId == id then - -- 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 combination into individual shortcuts + -- 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 combination into individual shortcuts. local always_owned_keys = { ImGuiKey.LeftArrow, ImGuiKey.RightArrow, ImGuiKey.Delete, ImGuiKey.Backspace, ImGuiKey.Home, ImGuiKey.End } for _, key in ipairs(always_owned_keys) do ImGui.SetKeyOwner(key, id) @@ -5118,7 +5518,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local value_changed = false local validated = false - -- Select the buffer to render + -- Select the buffer to render. local buf_display_from_state = (render_cursor or render_selection or g.ActiveId == id) and not is_readonly and state ~= nil local is_displaying_hint = (hint ~= nil and (buf_display_from_state and state.TextA.Data or buf)[1] == 0) @@ -5147,7 +5547,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback 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 + -- Down the line we should have a cleaner library-wide concept of Selected vs Active. g.ActiveIdAllowOverlap = not io.MouseDown[0] -- Edit in progress @@ -5178,7 +5578,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback else -- Triple-click: Select line local is_eol = ImStb.TEXTEDIT_GETCHAR(state, state.Stb.cursor) == 10 - state.WrapWidth = 0.0 -- Temporarily disable wrapping so we use real line start + state.WrapWidth = 0.0 -- Temporarily disable wrapping so we use real line start. state:OnKeyPressed(STB_TEXTEDIT_K_LINESTART) state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_LINEEND, STB_TEXTEDIT_K_SHIFT)) state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_RIGHT, STB_TEXTEDIT_K_SHIFT)) @@ -5208,6 +5608,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.SelectedAllMouseLock = false end + -- We expect backends to emit a Tab key but some also emit a Tab character which we ignore (#2467, #1336) + -- (For Tab and Enter: Win32/SFML/Allegro are sending both keys and chars, GLFW and SDL are only sending keys. For Space they all send all threes) if bit32.band(flags, ImGuiInputTextFlags.AllowTabInput) ~= 0 and not is_readonly then if ImGui.Shortcut(ImGuiKey.Tab, ImGuiInputFlags.Repeat, id) then local c = 9 -- Insert TAB @@ -5219,9 +5621,12 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end -- FIXME: Implement Shift+Tab + -- if ImGui.Shortcut(bit32.bor(ImGuiKey.Tab, ImGuiMod_Shift), ImGuiInputFlags.Repeat, id) then + -- end end - -- Process regular text input + -- Process regular text input (before we check for Return because using some IME will effectively send a Return?) + -- We ignore Ctrl inputs, but need to allow Alt+Ctrl as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. local ignore_char_inputs = io.KeyCtrl and not io.KeyAlt if io.InputQueueCharacters.Size > 0 then if not ignore_char_inputs and not is_readonly and not input_requested_by_nav then @@ -5229,7 +5634,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback repeat -- Insert character if they pass filtering local c = io.InputQueueCharacters[n] - if c == 9 then -- Skip Tab, see above + if c == 9 then -- Skip Tab, see above. break end @@ -5258,9 +5663,11 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.Stb.row_count_per_page = row_count_per_page local k_mask = (io.KeyShift and STB_TEXTEDIT_K_SHIFT or 0) - local is_wordmove_key_down = is_osx and io.KeyAlt or io.KeyCtrl - local is_startend_key_down = is_osx and io.KeyCtrl and not io.KeySuper and not io.KeyAlt + local is_wordmove_key_down = is_osx and io.KeyAlt or io.KeyCtrl -- OS X style: Text editing cursor movement using Alt instead of Ctrl + local is_startend_key_down = is_osx and io.KeyCtrl and not io.KeySuper and not 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: former would be handled by InputText) + -- Otherwise we could simply assume that we own the keys as we are active. local f_repeat = ImGuiInputFlags.Repeat local is_cut = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.X), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Shift, ImGuiKey.Delete), f_repeat, id)) and not is_readonly and not is_password and (not is_multiline or state:HasSelection()) local is_copy = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.C), 0, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Insert), 0, id)) and not is_password and (not is_multiline or state:HasSelection()) @@ -5269,6 +5676,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local is_redo = (ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Y), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiMod_Shift, ImGuiKey.Z), f_repeat, id)) and not is_readonly and is_undoable local is_select_all = ImGui.Shortcut(bit32.bor(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. local nav_gamepad_active = (bit32.band(io.ConfigFlags, ImGuiConfigFlags.NavEnableGamepad) ~= 0) and (bit32.band(io.BackendFlags, ImGuiBackendFlags.HasGamepad) ~= 0) local is_enter = ImGui.Shortcut(ImGuiKey.Enter, f_repeat, id) or ImGui.Shortcut(ImGuiKey.KeypadEnter, f_repeat, id) local is_ctrl_enter = ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.Enter), f_repeat, id) or ImGui.Shortcut(bit32.bor(ImGuiMod_Ctrl, ImGuiKey.KeypadEnter), f_repeat, id) @@ -5276,6 +5684,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback local is_gamepad_validate = nav_gamepad_active and ImGui.IsKeyPressed(ImGuiKey.NavGamepadActivate, false) local is_cancel = ImGui.Shortcut(ImGuiKey.Escape, f_repeat, id) or (nav_gamepad_active and ImGui.Shortcut(ImGuiKey.NavGamepadCancel, f_repeat, id)) + -- FIXME: Should use more Shortcut() and reduce IsKeyPressed()+SetKeyOwner(), but requires modifiers combination to be taken account of. + -- FIXME-OSX: Missing support for Alt(option)+Right/Left = go to end of line, or next line if already in end of line. if ImGui.IsKeyPressed(ImGuiKey.LeftArrow) then state:OnKeyPressed(bit32.bor(is_startend_key_down and STB_TEXTEDIT_K_LINESTART or (is_wordmove_key_down and STB_TEXTEDIT_K_WORDLEFT or STB_TEXTEDIT_K_LEFT), k_mask)) elseif ImGui.IsKeyPressed(ImGuiKey.RightArrow) then @@ -5304,6 +5714,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state:OnKeyPressed(io.KeyCtrl and bit32.bor(STB_TEXTEDIT_K_TEXTEND, k_mask) or bit32.bor(STB_TEXTEDIT_K_LINEEND, k_mask)) elseif ImGui.IsKeyPressed(ImGuiKey.Delete) and not is_readonly and not is_cut then if not state:HasSelection() then + -- OSX doesn't seem to have Super+Delete to delete until end-of-line, so we don't emulate that (as opposed to Super+Backspace) if is_wordmove_key_down then state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_WORDRIGHT, STB_TEXTEDIT_K_SHIFT)) end @@ -5319,17 +5730,20 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end state:OnKeyPressed(bit32.bor(STB_TEXTEDIT_K_BACKSPACE, k_mask)) elseif is_enter or is_ctrl_enter or is_shift_enter or is_gamepad_validate then + -- Determine if we turn Enter into a \n character local ctrl_enter_for_new_line = bit32.band(flags, ImGuiInputTextFlags.CtrlEnterForNewLine) ~= 0 local is_new_line = is_multiline and not is_gamepad_validate and (is_shift_enter or (is_enter and not ctrl_enter_for_new_line) or (is_ctrl_enter and ctrl_enter_for_new_line)) if not is_new_line then validated = true clear_active_id = true if io.ConfigInputTextEnterKeepActive and not is_multiline and not is_ctrl_enter and not is_shift_enter then - state:SelectAll() - g.InputTextReactivateId = id + -- Queue reactivation, so that e.g. IsItemDeactivatedAfterEdit() will work. (#9001) + state:SelectAll() -- No need to scroll + g.InputTextReactivateId = id -- Mark for reactivation on next frame end elseif not is_readonly then - local c = 10 -- Insert new line + -- Insert new line + local c = 10 local ret2 c, ret2 = InputTextFilterCharacter(g, state, c, callback, callback_user_data) if ret2 then @@ -5358,7 +5772,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state:SelectAll() state.CursorFollow = true elseif is_cut or is_copy then + -- Cut, Copy if g.PlatformIO.Platform_SetClipboardTextFn ~= nil then + -- SetClipboardText() only takes null terminated strings + state.TextSrc may point to read-only user buffer, so we need to make a copy. local ib = state:HasSelection() and ImMin(state.Stb.select_start, state.Stb.select_end) or 1 local ie = state:HasSelection() and ImMax(state.Stb.select_start, state.Stb.select_end) or state.TextLen + 1 g.TempBuffer:reserve(ie - ib + 1) @@ -5376,6 +5792,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback elseif is_paste then local clipboard = ImGui.GetClipboardText() if clipboard then + -- Filter pasted buffer local clipboard_len = #clipboard local clipboard_end = clipboard_len + 1 local clipboard_filtered = ImVector() @@ -5402,7 +5819,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback until true end - if clipboard_filtered.Size > 0 then + if clipboard_filtered.Size > 0 then -- If everything was filtered, ignore the pasting operation clipboard_filtered:push_back(0) stbte.paste(state, state.Stb, clipboard_filtered.Data, clipboard_filtered.Size - 1) state.CursorFollow = true @@ -5410,6 +5827,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end + -- Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame. render_selection = render_selection or (state:HasSelection() and (RENDER_SELECTION_WHEN_INACTIVE or render_cursor)) end @@ -5422,6 +5840,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback if revert_edit and not is_readonly then if bit32.band(flags, ImGuiInputTextFlags.EscapeClearsAll) ~= 0 then + -- Clear input IM_ASSERT(state.TextA.Data[1] ~= 0) apply_new_text = {0} apply_new_text_length = 0 @@ -5432,14 +5851,19 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback 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 ImStb.stb_textedit_replace(state, state.Stb, state.TextToRevertTo.Data, state.TextToRevertTo.Size - 1) end end + -- User callback if bit32.band(flags, bit32.bor(ImGuiInputTextFlags.CallbackCompletion, ImGuiInputTextFlags.CallbackHistory, ImGuiInputTextFlags.CallbackEdit, ImGuiInputTextFlags.CallbackAlways)) ~= 0 then IM_ASSERT(callback ~= nil) + -- The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. + local event_flag = 0 local event_key = ImGuiKey.None if bit32.band(flags, ImGuiInputTextFlags.CallbackCompletion) ~= 0 and ImGui.Shortcut(ImGuiKey.Tab, 0, id) then @@ -5466,6 +5890,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback callback_data.EventActivated = (g.ActiveId == state.ID and g.ActiveIdIsJustActivated) callback_data.UserData = callback_user_data + -- FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925 local callback_buf = is_readonly and buf or state.TextA.Data IM_ASSERT(callback_buf == state.TextSrc) state.CallbackTextBackup:resize(state.TextLen + 1) @@ -5480,10 +5905,12 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback callback_data.SelectionStart = state.Stb.select_start callback_data.SelectionEnd = state.Stb.select_end + -- Call user code callback(callback_data) - callback_buf = is_readonly and buf or state.TextA.Data - IM_ASSERT(callback_data.Buf == callback_buf) + -- Read back what user may have modified + callback_buf = is_readonly and buf or 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.BufCapacity) IM_ASSERT(callback_data.Flags == flags) if callback_data.BufDirty or callback_data.CursorPos ~= state.Stb.cursor then @@ -5493,15 +5920,18 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.Stb.select_start = ImClamp(callback_data.SelectionStart, 0, callback_data.BufTextLen) state.Stb.select_end = ImClamp(callback_data.SelectionEnd, 0, callback_data.BufTextLen) if callback_data.BufDirty then - IM_ASSERT(callback_data.BufTextLen == ImStd.ImStrlen(callback_data.Buf)) + -- Callback may update buffer and thus set buf_dirty even in read-only mode. + IM_ASSERT(callback_data.BufTextLen == ImStd.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 + state.TextLen = callback_data.BufTextLen -- Assume correct length and valid UTF-8 from user, saves us an extra strlen() state.EditedBefore = true; state.EditedThisFrame = true state:CursorAnimReset() end end end + -- Write back result string if modified. + -- FIXME-OPT: Could mark dirty state from the stb_textedit callbacks if not is_readonly then if bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.LiveEditOnInputScalar) ~= 0 then -- Apply when modified @@ -5519,6 +5949,8 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end + -- Handle reapplying final data on deactivation (see InputTextDeactivateHook() for details) + -- This is used when e.g. losing focus or tabbing out into another InputText() which may already be using the temp buffer. if g.InputTextDeactivatedState.ID == id then -- The state only exists after an Edit. IsItemDeactivatedAfterEdit() is not valid in every code path (see "widgets_inputtext_status_noliveedit" test). if ((g.ActiveId ~= id and ImGui.IsItemDeactivated()) or (g.ActiveId == id and bit32.band(flags, ImGuiInputTextFlags.TempInput) ~= 0)) then @@ -5532,6 +5964,12 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback g.InputTextDeactivatedState.ID = 0 end + -- Write back result to user buffer. This can currently only happen when (g.ActiveId == id) or when just deactivated. + -- - As soon as the InputText() is active, our stored in-widget value gets priority over any underlying modification of the user buffer. + -- - Make sure we always reapply the live buffer back to the input/user buffer before clearing ActiveId, even thought strictly speaking + -- it was not modified on this frame. This allows the user to use InputText() without maintaining any user-side storage. + -- (PS: if you use this property together with ImGuiInputTextFlags.CallbackResize, you are at the risk of recreating a temporary + -- allocated/string object every frame. Which in the grand scheme of scheme is nothing, but isn't dear imgui vibe). if apply_new_text ~= nil then IM_ASSERT(apply_new_text_length >= 0) if is_resizable then @@ -5553,7 +5991,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1) IM_ASSERT(apply_new_text_length <= buf_size) end + -- IMGUI_DEBUG_PRINT("InputText(\"%s\"): apply_new_text length %d\n", label, apply_new_text_length); + -- If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size. ImStd.ImStrncpy(buf, 1, apply_new_text, 1, ImMin(apply_new_text_length + 1, buf_size)) end @@ -5605,7 +6045,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback if render_cursor or render_selection or g.ActiveId == id then buf_display_end = state.TextLen + 1 elseif is_multiline and not is_wordwrap then - buf_display_end = nil -- Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path + buf_display_end = nil -- Inactive multi-line: end of buffer will be output by InputTextLineIndexBuild() special strchr() path. else buf_display_end = ImStd.ImStrlen(buf_display) + 1 end @@ -5617,10 +6057,13 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize) end + -- Build line index for easy data access (makes code below simpler and faster) local line_index = g.InputTextLineIndex line_index.Offsets:resize(0) local line_count = 1 if is_multiline then + -- If scrolling is expected to change build full index. + -- FIXME-OPT: Could append to index when new value of line_visible_n1 becomes bigger, see second call to CalcClipRectVisibleItemsY() below. local will_scroll_y = state and ((state.CursorFollow and render_cursor) or (state.CursorCenterY and (render_cursor or render_selection))) --- @cast buf_display_end int local out_buf_end @@ -5632,19 +6075,32 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback line_index.EndOffset = buf_display_end - 1 line_visible_n1 = ImMin(line_visible_n1, line_count + 1) + -- Store text height (we don't need width) local text_size_y = line_count * g.FontSize + -- ImGui.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 --- @cast buf_display_end int local cursor_offset = (render_cursor and state) and InputTextLineIndexGetPosOffset(g, state, line_index, buf_display, buf_display_end, state.Stb.cursor) or ImVec2(0.0, 0.0) local draw_scroll = ImVec2() + -- Render text. We currently only render selection when the widget is active or while scrolling. local text_col = ImGui.GetColorU32(is_displaying_hint and ImGuiCol.TextDisabled or ImGuiCol.Text) if render_cursor or render_selection then + -- 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) + -- - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) + -- - 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. IM_ASSERT(state ~= nil) state.LineCount = line_count + -- Scroll local new_scroll_y = scroll_y if render_cursor and state.CursorFollow then + -- Horizontal scroll in chunks of quarter width if bit32.band(flags, ImGuiInputTextFlags.NoHorizontalScroll) == 0 then local scroll_increment_x = inner_size.x * 0.25 local visible_width = inner_size.x - style.FramePadding.x @@ -5657,7 +6113,9 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback state.Scroll.x = 0.0 end + -- Vertical scroll if is_multiline then + -- Test if cursor is vertically visible if cursor_offset.y - g.FontSize < scroll_y then new_scroll_y = ImMax(0.0, cursor_offset.y - g.FontSize) elseif cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0) >= scroll_y then @@ -5676,18 +6134,19 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback if new_scroll_y ~= scroll_y then local scroll_max_y = ImMax((text_size_y + style.FramePadding.y * 2.0) - inner_size.y, 0.0) scroll_y = ImClamp(new_scroll_y, 0.0, scroll_max_y) - draw_pos.y = draw_pos.y + (draw_window.Scroll.y - scroll_y) + draw_pos.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 line_visible_n0, line_visible_n1 = ImGui.CalcClipRectVisibleItemsY(clip_rect, draw_pos, g.FontSize) line_visible_n1 = ImMin(line_visible_n1, line_count) end + -- Draw selection draw_scroll.x = state.Scroll.x if render_selection then - local bg_color = ImGui.GetColorU32(ImGuiCol.TextSelectedBg, render_cursor and 1.0 or 0.6) - local bg_offy_up = is_multiline and 0.0 or -1.0 + local bg_color = ImGui.GetColorU32(ImGuiCol.TextSelectedBg, render_cursor and 1.0 or 0.6) -- FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. + local bg_offy_up = is_multiline and 0.0 or -1.0 -- FIXME-DPI: those offsets should be part of the style? they don't play so well with multi-line selection. local bg_offy_dn = is_multiline and 0.0 or 2.0 - local bg_eol_width = IM_TRUNC(g.FontBaked:GetCharAdvance(32) * 0.50) + local bg_eol_width = IM_TRUNC(g.FontBaked:GetCharAdvance(32) * 0.50) -- So we can see selected empty lines local text_selected_begin = ImMin(state.Stb.select_start, state.Stb.select_end) local text_selected_end = ImMax(state.Stb.select_start, state.Stb.select_end) @@ -5707,7 +6166,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback rect_width = rect_width + ImGui.CalcTextSizeEx(buf_display, line_selected_begin, line_selected_end).x end if text_selected_begin <= p_eol and text_selected_end > p_eol and not p_eol_is_wrap then - rect_width = rect_width + bg_eol_width + rect_width = rect_width + bg_eol_width -- So we can see selected empty lines end if rect_width == 0.0 then break @@ -5727,10 +6186,13 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback end end + -- Find render position for right alignment (single-line only) if g.ActiveId ~= id and bit32.band(flags, ImGuiInputTextFlags.ElideLeft) ~= 0 and not render_cursor and not render_selection then draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - ImGui.CalcTextSize(buf_display, nil).x - style.FramePadding.x) end + -- draw_scroll.x = state.Scroll.x -- Preserve scroll when inactive? + -- Render text if (is_multiline or (buf_display_end - 1) < buf_display_max_length) and bit32.band(text_col, IM_COL32_A_MASK) ~= 0 and line_visible_n0 < line_visible_n1 then g.Font:RenderText(draw_window.DrawList, g.FontSize, draw_pos - draw_scroll + ImVec2(0.0, (line_visible_n0 - 1) * g.FontSize), @@ -5741,6 +6203,7 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback wrap_width, bit32.bor(ImDrawTextFlags.WrapKeepBlanks, ImDrawTextFlags.CpuFineClip)) end + -- Render blinking cursor if render_cursor then state.CursorAnim = state.CursorAnim + io.DeltaTime local cursor_is_visible = (not g.IO.ConfigInputTextCursorBlink) or (state.CursorAnim <= 0.0) or (ImFmod(state.CursorAnim, 1.20) <= 0.80) @@ -5752,8 +6215,11 @@ function ImGui.InputTextEx(label, hint, buf, buf_size, size_arg, flags, callback draw_window.DrawList:AddLineV(cursor_screen_rect.Min.x, cursor_screen_rect.Min.y, cursor_screen_rect.Max.y, ImGui.GetColorU32(ImGuiCol.InputTextCursor), style.InputTextCursorSize) end + -- 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 not is_readonly and g.ActiveId == id then - local ime_data = g.PlatformImeData + local ime_data = g.PlatformImeData -- (this is a public struct, passed to io.Platform_SetImeDataFn() handler) ime_data.WantVisible = true ime_data.WantTextInput = true ImVec2_Copy(ime_data.InputPos, ImVec2(cursor_screen_pos.x - 1.0, cursor_screen_pos.y - g.FontSize)) @@ -5812,13 +6278,23 @@ end function ImGui.InputTextWithHint(label, hint, buf, buf_size, flags, callback, user_data) if flags == nil then flags = 0 end - IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) + IM_ASSERT(bit32.band(flags, ImGuiInputTextFlags.Multiline) == 0) -- call InputTextMultiline() or InputTextEx() manually if you need multi-line + hint. return ImGui.InputTextEx(label, hint, buf, buf_size, ImVec2(0, 0), flags, callback, user_data) end ----------------------------------------------------------------- --- [SECTION] COLOR EDIT / PICKER ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. +------------------------------------------------------------------------------- +-- - ColorEdit3() +-- - ColorEdit4() +-- - ColorPicker3() +-- - RenderColorRectWithAlphaCheckerboard() [Internal] +-- - ColorPicker4() +-- - ColorButton() +-- - ColorTooltip() [Internal] +-- - ColorEditOptionsPopup() [Internal] +-- - ColorPickerOptionsPopup() [Internal] +------------------------------------------------------------------------------- --- @param col float[] --- @param H float @@ -5833,6 +6309,8 @@ local function ColorEditRestoreH(col, H) return H end +-- ColorEdit supports RGB and HSV inputs. In case of RGB input resulting color may have undefined hue and/or saturation. +-- Since widget displays both RGB and HSV values we must preserve hue and saturation to prevent these values resetting. --- @param col float[] --- @param H float --- @param S float @@ -5874,6 +6352,9 @@ local fmt_table_float = { { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } -- Long display for HSVA } +-- 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. --- @param label string --- @param col float[] --- @param flags ImGuiColorEditFlags @@ -5975,6 +6456,7 @@ function ImGui.ColorEdit4(label, col, flags) window.DC.CursorPos.x = pos.x + inputs_offset_x if bit32.band(flags, bit32.bor(ImGuiColorEditFlags.DisplayRGB, ImGuiColorEditFlags.DisplayHSV)) ~= 0 and bit32.band(flags, ImGuiColorEditFlags.NoInputs) == 0 then + -- RGB/HSV 0..255 Sliders local w_items = w_inputs - style.ItemInnerSpacing.x * (components - 1) local w_per_component = IM_TRUNC(w_items / components) local draw_color_marker = bit32.band(flags, bit32.bor(ImGuiColorEditFlags.DisplayHSV, ImGuiColorEditFlags.NoColorMarkers)) == 0 @@ -6002,7 +6484,7 @@ function ImGui.ColorEdit4(label, col, flags) ImGui.SetNextItemColorMarker(GDefaultRgbaColorMarkers[n]) end - -- FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0 + -- FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0. if bit32.band(flags, ImGuiColorEditFlags.Float) ~= 0 then local changed f[n], changed = ImGui.DragFloat(ids[n], f[n], 1.0 / 255.0, 0.0, hdr and 0.0 or 1.0, fmt_table_float[fmt_idx][n], drag_flags) @@ -6040,15 +6522,15 @@ function ImGui.ColorEdit4(label, col, flags) p = p + 1 end i[1], i[2], i[3] = 0, 0, 0 - i[4] = 0xFF + i[4] = 0xFF -- alpha default to 255 is not parsed by scanf (e.g. inputting #FFFFFF omitting alpha) local r if alpha then - r = ImStd.sscanf(buf, p, "%02X%02X%02X%02X", i) + r = ImStd.sscanf(buf, p, "%02X%02X%02X%02X", i) -- Treat at unsigned (%X is unsigned) else r = ImStd.sscanf(buf, p, "%02X%02X%02X", i) end - -- IM_UNUSED(r) + -- IM_UNUSED(r) -- Fixes C6031: Return value ignored: 'sscanf'. end if bit32.band(flags, ImGuiColorEditFlags.NoOptions) == 0 then @@ -6092,7 +6574,7 @@ function ImGui.ColorEdit4(label, col, flags) if label ~= "" and label_display_end > 1 and bit32.band(flags, ImGuiColorEditFlags.NoLabel) == 0 then -- Position not necessarily next to last submitted button (e.g. if style.ColorButtonPosition == ImGuiDir_Left), - -- but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this + -- but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this. ImGui.SameLine(0.0, style.ItemInnerSpacing.x) window.DC.CursorPos.x = pos.x + ((bit32.band(flags, ImGuiColorEditFlags.NoInputs) ~= 0) and w_button or (w_full + style.ItemInnerSpacing.x)) ImGui.TextEx(label, label_display_end) @@ -6133,7 +6615,7 @@ function ImGui.ColorEdit4(label, col, flags) -- Drag and Drop Target -- TODO: - -- When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4() + -- When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4(). if picker_active_window and g.ActiveId ~= 0 and g.ActiveIdWindow == picker_active_window then g.LastItemData.ID = g.ActiveId end @@ -6168,6 +6650,7 @@ function ImGui.ColorPicker3(label, col, flags) return true end +-- This allowed passing 0 to set default, whereas NewFrame() will assert if one of missing. Abide to old logic. function ImGui.SetColorEditOptions(flags) local g = GImGui local def = ImGuiColorEditFlags.DefaultOptions_ @@ -6197,6 +6680,9 @@ do --[[ColorPicker4]] local backup_initial_col = {0, 0, 0, 0} +-- Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags.NoAlpha flag is set. +-- FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) +-- FIXME: this is trying to be aware of style.Alpha but not fully correct. Also, the color wheel will have overlapping glitches with (style.Alpha < 1.0) --- @param label string --- @param col float[] --- @param flags ImGuiColorEditFlags @@ -6262,8 +6748,8 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) local picker_pos = ImVec2() ImVec2_Copy(picker_pos, window.DC.CursorPos) local square_sz = ImGui.GetFrameHeight() - local bars_width = square_sz -- Arbitrary smallish width of Hue/Alpha picking bars - local sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar and 2 or 1) * (bars_width + style.ItemInnerSpacing.x)) -- Saturation/Value picking box + local bars_width = square_sz -- Arbitrary smallish width of Hue/Alpha picking bars + local sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar and 2 or 1) * (bars_width + style.ItemInnerSpacing.x)) -- Saturation/Value picking box local bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x local bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x local bars_triangles_half_sz = IM_TRUNC(bars_width * 0.20) @@ -6279,9 +6765,9 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) local triangle_rotate = bit32.band(flags, ImGuiColorEditFlags.PickerNoRotate) == 0 local triangle_r = wheel_r_inner - math.floor(sv_picker_size * 0.027) local triangle_pa, triangle_pb, triangle_pc - if triangle_rotate then triangle_pa = ImVec2( triangle_r, 0.0) else triangle_pa = ImVec2( triangle_r * 0.866, triangle_r * 0.5) end -- Hue point - if triangle_rotate then triangle_pb = ImVec2(triangle_r * -0.5, triangle_r * -0.866) else triangle_pb = ImVec2( 0.0, -triangle_r) end -- Black point - if triangle_rotate then triangle_pc = ImVec2(triangle_r * -0.5, triangle_r * 0.866) else triangle_pc = ImVec2(triangle_r * -0.866, triangle_r * 0.5) end -- White point + if triangle_rotate then triangle_pa = ImVec2( triangle_r, 0.0) else triangle_pa = ImVec2( triangle_r * 0.866, triangle_r * 0.5) end -- Hue point. + if triangle_rotate then triangle_pb = ImVec2(triangle_r * -0.5, triangle_r * -0.866) else triangle_pb = ImVec2( 0.0, -triangle_r) end -- Black point. + if triangle_rotate then triangle_pc = ImVec2(triangle_r * -0.5, triangle_r * 0.866) else triangle_pc = ImVec2(triangle_r * -0.866, triangle_r * 0.5) end -- White point. local H = col[1]; local S = col[2]; local V = col[3] local R = col[1]; local G = col[2]; local B = col[3] @@ -6341,7 +6827,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) if ImGui.IsItemActive() and not is_readonly then S = ImSaturate((io.MousePos.x - picker_pos.x) / ImMax(sv_picker_size - 1, 0.0001)) V = 1.0 - ImSaturate((io.MousePos.y - picker_pos.y) / ImMax(sv_picker_size - 1, 0.0001)) - H = ColorEditRestoreH(col, H) -- Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square. + H = ColorEditRestoreH(col, H) -- Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square. value_changed = true value_changed_sv = true end @@ -6369,7 +6855,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) value_changed = true end end - ImGui.PopItemFlag() + ImGui.PopItemFlag() -- ImGuiItemFlags.NoNav if bit32.band(flags, ImGuiColorEditFlags.NoSidePreview) == 0 then ImGui.SameLine(0, style.ItemInnerSpacing.x) @@ -6559,8 +7045,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) draw_list:AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black) ImGui.RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0) - -- Sneakily prevent the circle to stick out too much - sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2) + sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2) -- Sneakily prevent the circle to stick out too much sv_cursor_pos.y = ImClamp(IM_ROUND(picker_pos.y + ImSaturate(1 - V) * sv_picker_size), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2) -- Render Hue Bar @@ -6575,7 +7060,7 @@ function ImGui.ColorPicker4(label, col, flags, ref_col) -- Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range) local sv_cursor_rad = value_changed_sv and (wheel_thickness * 0.55) or (wheel_thickness * 0.40) - local sv_cursor_segments = draw_list:_CalcCircleAutoSegmentCount(sv_cursor_rad) -- Lock segment count so the +1 one matches others. + local sv_cursor_segments = draw_list:_CalcCircleAutoSegmentCount(sv_cursor_rad) -- Lock segment count so the +1 one matches others. draw_list:AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, sv_cursor_segments) draw_list:AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, sv_cursor_segments) draw_list:AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, sv_cursor_segments) @@ -6620,6 +7105,10 @@ end end +-- A little color square. Return true when clicked. +-- FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. +-- 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. +-- Note that 'col' may be encoded in HSV if ImGuiColorEditFlags.InputHSV is set. --- @param desc_id string --- @param col ImVec4 --- @param flags? ImGuiColorEditFlags @@ -6674,6 +7163,7 @@ function ImGui.ColorButton(desc_id, col, flags, size_arg) end window.DrawList:AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), ImGui.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 local col_source = (bit32.band(flags, ImGuiColorEditFlags.AlphaOpaque) ~= 0) and col_rgb_without_alpha or col_rgb if col_source.w < 1.0 and bit32.band(flags, ImGuiColorEditFlags.AlphaNoBg) == 0 then ImGui.RenderColorRectWithAlphaCheckerboard(window.DrawList, bb_inner.Min, bb_inner.Max, ImGui.GetColorU32(col_source), grid_step, ImVec2(off, off), rounding) @@ -6686,7 +7176,7 @@ function ImGui.ColorButton(desc_id, col, flags, size_arg) if g.Style.FrameBorderSize > 0.0 then ImGui.RenderFrameBorder(bb.Min, bb.Max, rounding) else - window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), rounding) + window.DrawList:AddRect(bb.Min, bb.Max, ImGui.GetColorU32(ImGuiCol.FrameBg), rounding) -- Color buttons are often in need of some sort of border end end @@ -6712,6 +7202,7 @@ function ImGui.ColorButton(desc_id, col, flags, size_arg) return pressed end +-- Note: only access 3 floats if ImGuiColorEditFlags.NoAlpha flag is set. --- @param text? string --- @param col ImVec4 --- @param flags ImGuiColorEditFlags @@ -6849,6 +7340,7 @@ function ImGui.ColorPickerOptionsPopup(ref_col, flags) local picker_size = ImVec2(g.FontSize * 8, ImMax(g.FontSize * 8 - (ImGui.GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0)) -- FIXME: Picker size copied from main picker function ImGui.PushItemWidth(picker_size.x) for picker_type = 0, 1 do + -- Draw small/thumbnail version of each picker type (over an invisible button for selection) if picker_type > 0 then ImGui.Separator() end @@ -6861,8 +7353,7 @@ function ImGui.ColorPickerOptionsPopup(ref_col, flags) picker_flags = bit32.bor(picker_flags, ImGuiColorEditFlags.PickerHueWheel) end local backup_pos = ImGui.GetCursorScreenPos() - -- By default, Selectable() is closing popup - if ImGui.Selectable("##selectable", false, 0, picker_size) then + if ImGui.Selectable("##selectable", false, 0, picker_size) then -- By default, Selectable() is closing popup g.IO.ConfigColorEditFlags = bit32.bor(bit32.band(g.IO.ConfigColorEditFlags, bit32.bnot(ImGuiColorEditFlags.PickerMask_)), bit32.band(picker_flags, ImGuiColorEditFlags.PickerMask_)) end ImGui.SetCursorScreenPos(backup_pos) @@ -6885,9 +7376,21 @@ function ImGui.ColorPickerOptionsPopup(ref_col, flags) ImGui.EndPopup() end ----------------------------------------------------------------- --- [SECTION] TREES ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: TreeNode, CollapsingHeader, etc. +------------------------------------------------------------------------------- +-- - TreeNode() +-- - TreeNodeV() +-- - TreeNodeEx() +-- - TreeNodeExV() +-- - TreeNodeStoreStackData() [Internal] +-- - TreeNodeBehavior() [Internal] +-- - TreePush() +-- - TreePop() +-- - GetTreeNodeToLabelSpacing() +-- - SetNextItemOpen() +-- - CollapsingHeader() +------------------------------------------------------------------------------- -- va_list variants: identical in Lua (varargs) ImGui.TextColoredV = function(...) return ImGui.TextColored(...) end @@ -6951,6 +7454,8 @@ function ImGui.TreeNodeExV(str_id, flags, fmt, ...) return ImGui.TreeNodeBehavior(id, flags, label, #label + 1) end +-- The reason those two functions are not yet in public API is because I would like to design a more feature-full and generic API for this. +-- They are otherwise function (cc: #3823, #9251, #7553, #6754, #5423, #2958, #2079, #1947, #1131, #722) --- @param storage_id ImGuiID function ImGui.TreeNodeGetOpen(storage_id) local g = GImGui @@ -6969,10 +7474,12 @@ end --- @param storage_id ImGuiID --- @param flags ImGuiTreeNodeFlags function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) + -- Leaf node always open a new tree/id scope. If you never use it, add ImGuiTreeNodeFlags.NoTreePushOnOpen. if bit32.band(flags, ImGuiTreeNodeFlags.Leaf) ~= 0 then return true end + -- We only write to the tree storage if the user clicks, or explicitly use the SetNextItemOpen function local g = GImGui local window = g.CurrentWindow local storage = window.DC.StateStorage @@ -6983,6 +7490,7 @@ function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) is_open = g.NextItemData.OpenVal ImGui.TreeNodeSetOpen(storage_id, is_open) else + -- We treat ImGuiCond.Once and ImGuiCond.FirstUseEver the same because tree node state are not saved persistently. local stored_value = storage[storage_id] if stored_value == nil then is_open = g.NextItemData.OpenVal @@ -6995,6 +7503,8 @@ function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) is_open = (storage[storage_id] == nil) and (bit32.band(flags, ImGuiTreeNodeFlags.DefaultOpen) ~= 0) or storage[storage_id] end + -- When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). + -- NB- If we are above max depth we still allow manually opened nodes to be logged. if g.LogEnabled and bit32.band(flags, ImGuiTreeNodeFlags.NoAutoOpenOnLog) == 0 and (window.DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand then is_open = true end @@ -7002,6 +7512,8 @@ function ImGui.TreeNodeUpdateNextOpen(storage_id, flags) return is_open end +-- Store ImGuiTreeNodeStackData for just submitted node. +-- Currently only supports 32 level deep. Easy to increase to e.g. 64. --- @param flags ImGuiTreeNodeFlags --- @param x1 float local function TreeNodeStoreStackData(flags, x1) @@ -7015,6 +7527,7 @@ local function TreeNodeStoreStackData(flags, x1) tree_node_data.ItemFlags = g.LastItemData.ItemFlags ImRect_Copy(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. local draw_lines = bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.DrawLinesFull, ImGuiTreeNodeFlags.DrawLinesToNodes)) ~= 0 tree_node_data.DrawLinesX1 = draw_lines and (x1 + g.FontSize * 0.5 + g.Style.FramePadding.x) or FLT_MAX tree_node_data.DrawLinesTableColumn = (draw_lines and g.CurrentTable) and g.CurrentTable.CurrentColumn or -1 @@ -7039,6 +7552,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local g = GImGui local style = g.Style + -- When not framed, we vertically increase height up to typical framed widget height local display_frame = bit32.band(flags, ImGuiTreeNodeFlags.Framed) ~= 0 local use_frame_padding = display_frame or (bit32.band(flags, ImGuiTreeNodeFlags.FramePadding) ~= 0) local padding @@ -7053,9 +7567,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end local label_size = ImGui.CalcTextSize(label, label_end, false) - local text_offset_x = g.FontSize + (display_frame and (padding.x * 3) or (padding.x * 2)) - local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset - local text_width = g.FontSize + label_size.x + padding.x * 2 + local text_offset_x = g.FontSize + (display_frame and (padding.x * 3) or (padding.x * 2)) -- Collapsing arrow width + Spacing + local text_offset_y = use_frame_padding and ImMax(style.FramePadding.y, window.DC.CurrLineTextBaseOffset) or window.DC.CurrLineTextBaseOffset -- Latch before ItemSize changes it + local text_width = g.FontSize + label_size.x + padding.x * 2 -- Include collapsing arrow local frame_height = label_size.y + padding.y * 2 local span_all_columns = bit32.band(flags, ImGuiTreeNodeFlags.SpanAllColumns) ~= 0 and (g.CurrentTable ~= nil) @@ -7066,7 +7580,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) frame_bb.Max.x = span_all_columns and window.ParentWorkRect.Max.x or (bit32.band(flags, ImGuiTreeNodeFlags.SpanLabelWidth) ~= 0 and window.DC.CursorPos.x + text_width + padding.x or window.WorkRect.Max.x) frame_bb.Max.y = window.DC.CursorPos.y + (text_offset_y - padding.y) + frame_height if display_frame then - local outer_extend = IM_TRUNC(window.WindowPadding.x * 0.5) + local outer_extend = IM_TRUNC(window.WindowPadding.x * 0.5) -- Framed header expand a little outside of current limits frame_bb.Min.x = frame_bb.Min.x - outer_extend frame_bb.Max.x = frame_bb.Max.x + outer_extend end @@ -7074,17 +7588,20 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local text_pos = ImVec2(window.DC.CursorPos.x + text_offset_x, window.DC.CursorPos.y + text_offset_y) ImGui.ItemSize(ImVec2(text_width, frame_height), padding.y) + -- For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing local interact_bb = ImRect() ImRect_Copy(interact_bb, frame_bb) if bit32.band(flags, bit32.bor(ImGuiTreeNodeFlags.Framed, ImGuiTreeNodeFlags.SpanAvailWidth, ImGuiTreeNodeFlags.SpanFullWidth, ImGuiTreeNodeFlags.SpanLabelWidth, ImGuiTreeNodeFlags.SpanAllColumns)) == 0 then interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0 and (style.ItemSpacing.x * 2.0) or 0.0) end + -- Compute open and multi-select states before ItemAdd() as it clear NextItem data. local storage_id = (bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasStorageID) ~= 0) and g.NextItemData.StorageId or id local is_open = ImGui.TreeNodeUpdateNextOpen(storage_id, flags) local is_visible if span_all_columns or span_all_columns_label then + -- Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable.. local backup_clip_rect_min_x = window.ClipRect.Min.x local backup_clip_rect_max_x = window.ClipRect.Max.x window.ClipRect.Min.x = window.ParentWorkRect.Min.x @@ -7098,6 +7615,10 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HasDisplayRect) ImRect_Copy(g.LastItemData.DisplayRect, frame_bb) + -- 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.NavLeftJumpsToParent by default or move it to ImGuiStyle. local store_tree_node_stack_data = false if bit32.band(flags, ImGuiTreeNodeFlags.DrawLinesMask_) == 0 then flags = bit32.bor(flags, g.Style.TreeLinesFlags) @@ -7116,13 +7637,13 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) if not is_visible then if bit32.band(flags, ImGuiTreeNodeFlags.DrawLinesToNodes) ~= 0 and bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.lshift(1, (window.DC.TreeDepth - 1))) ~= 0 then local parent_data = g.TreeNodeStack.Data[g.TreeNodeStack.Size] - parent_data.DrawLinesToNodesY2 = ImMax(parent_data.DrawLinesToNodesY2, window.DC.CursorPos.y) + 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 then - window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(bit32.lshift(1, (window.DC.TreeDepth - 1)))) + window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(bit32.lshift(1, (window.DC.TreeDepth - 1)))) -- Done end end if is_open and store_tree_node_stack_data then - TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) -- Call before TreePushOverrideID() end if is_open and bit32.band(flags, ImGuiTreeNodeFlags.NoTreePushOnOpen) == 0 then ImGui.TreePushOverrideID(id) @@ -7145,15 +7666,27 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnDragDropHold) end + -- We allow clicking on the arrow section with keyboard modifiers held, in order to easily + -- allow browsing a tree while preserving selection with code implementing multi-selection patterns. + -- When clicking on the rest of the tree node we always disallow keyboard modifiers. local arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x local arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0) + style.TouchExtraPadding.x local is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 and g.IO.MousePos.x < arrow_hit_x2) local is_multi_select = bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0 - if is_multi_select then + if is_multi_select then -- We absolutely need to distinguish open vs select so _OpenOnArrow comes by default flags = bit32.bor(flags, (bit32.band(flags, ImGuiTreeNodeFlags.OpenOnMask_) == 0) and bit32.bor(ImGuiTreeNodeFlags.OpenOnArrow, ImGuiTreeNodeFlags.OpenOnDoubleClick) or ImGuiTreeNodeFlags.OpenOnArrow) end + -- Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags. + -- Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support. + -- - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0) + -- - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0) + -- - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1) + -- - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1) + -- - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0) + -- It is rather standard that arrow click react on Down rather than Up. + -- We set ImGuiButtonFlags.PressedOnClickRelease on OpenOnDoubleClick because we want the item to be active on the initial MouseDown in order for drag and drop to work. if is_mouse_x_over_arrow then button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClick) elseif bit32.band(flags, ImGuiTreeNodeFlags.OpenOnDoubleClick) ~= 0 then @@ -7168,7 +7701,9 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local selected = bit32.band(flags, ImGuiTreeNodeFlags.Selected) ~= 0 local was_selected = selected + -- Multi-selection support (header) if is_multi_select then + -- Handle multi-select + alter button flags for it selected, button_flags = ImGui.MultiSelectItemHeader(id, selected, button_flags) if is_mouse_x_over_arrow then button_flags = bit32.band(bit32.bor(button_flags, ImGuiButtonFlags.PressedOnClick), bit32.bnot(ImGuiButtonFlags.PressedOnClickRelease)) @@ -7184,20 +7719,20 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) if not is_leaf then if pressed and g.DragDropHoldJustPressedId ~= id then if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnMask_) == 0 or (g.NavActivateId == id and not is_multi_select) then - toggled = true + toggled = true -- Single click end if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnArrow) ~= 0 then - toggled = toggled or (is_mouse_x_over_arrow and not g.NavHighlightItemUnderNav) + toggled = toggled or (is_mouse_x_over_arrow and not g.NavHighlightItemUnderNav) -- Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job end if bit32.band(flags, ImGuiTreeNodeFlags.OpenOnDoubleClick) ~= 0 and g.IO.MouseClickedCount[0] == 2 then - toggled = true + toggled = true -- Double click end elseif pressed and g.DragDropHoldJustPressedId == id then IM_ASSERT(bit32.band(button_flags, ImGuiButtonFlags.PressedOnDragDropHold) ~= 0) - if not is_open then + if not is_open then -- When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again. toggled = true else - pressed = false + pressed = false -- Cancel press so it doesn't trigger selection. end end @@ -7206,7 +7741,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavMoveRequestCancel() end - if g.NavId == id and g.NavMoveDir == ImGuiDir.Right and not is_open then + if g.NavId == id and g.NavMoveDir == ImGuiDir.Right and not is_open then -- If there's something upcoming on the line we may want to give it the priority? toggled = true ImGui.NavClearPreferredPosForAxis(ImGuiAxis.X) ImGui.NavMoveRequestCancel() @@ -7219,6 +7754,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end end + -- Multi-selection support (footer) if is_multi_select then local pressed_copy = pressed and not toggled selected, pressed_copy = ImGui.MultiSelectItemFooter(id, selected, pressed_copy) @@ -7236,9 +7772,10 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) local text_col = ImGui.GetColorU32(ImGuiCol.Text) local nav_render_cursor_flags = ImGuiNavRenderCursorFlags.Compact if is_multi_select then - nav_render_cursor_flags = bit32.bor(nav_render_cursor_flags, ImGuiNavRenderCursorFlags.AlwaysDraw) + nav_render_cursor_flags = bit32.bor(nav_render_cursor_flags, ImGuiNavRenderCursorFlags.AlwaysDraw) -- Always show the nav rectangle end if display_frame then + -- Framed type local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header)) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding) ImGui.RenderNavCursor(frame_bb, id, nav_render_cursor_flags) @@ -7249,7 +7786,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.RenderBullet(window.DrawList, ImVec2(text_pos.x - text_offset_x * 0.60, text_pos.y + g.FontSize * 0.5), text_col) elseif not is_leaf then ImGui.RenderArrow(window.DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y), text_col, is_open and ((bit32.band(flags, ImGuiTreeNodeFlags.UpsideDownArrow) ~= 0) and ImGuiDir.Up or ImGuiDir.Down) or ImGuiDir.Right, 1.0) - else + else -- Leaf without bullet, left-adjusted text text_pos.x = text_pos.x - (text_offset_x - padding.x) end if bit32.band(flags, ImGuiTreeNodeFlags.ClipLabelForTrailingButton) ~= 0 then @@ -7259,6 +7796,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) -- ImGui.LogSetNextTextDecoration("###", "###") -- end else + -- Unframed typed for tree nodes if hovered or selected then local bg_col = ImGui.GetColorU32((held and hovered) and ImGuiCol.HeaderActive or (hovered and ImGuiCol.HeaderHovered or ImGuiCol.Header)) ImGui.RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false, 0.0) @@ -7281,6 +7819,7 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) ImGui.TreeNodeDrawLineToChildNode(ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.5)) end + -- Label if display_frame then ImGui.RenderTextClipped(text_pos, frame_bb.Max, label, label_end, label_size) else @@ -7293,16 +7832,18 @@ function ImGui.TreeNodeBehavior(id, flags, label, label_end) end if is_open and store_tree_node_stack_data then - TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) + TreeNodeStoreStackData(flags, text_pos.x - text_offset_x) -- Call before TreePushOverrideID() end if is_open and bit32.band(flags, ImGuiTreeNodeFlags.NoTreePushOnOpen) == 0 then - ImGui.TreePushOverrideID(id) + ImGui.TreePushOverrideID(id) -- Could use TreePush(label) but this avoid computing twice end -- IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); return is_open end +-- Draw horizontal line from our parent node +-- This is only called for visible child nodes so we are not too fussy anymore about performances --- @param target_pos ImVec2 function ImGui.TreeNodeDrawLineToChildNode(target_pos) local g = GImGui @@ -7311,6 +7852,7 @@ function ImGui.TreeNodeDrawLineToChildNode(target_pos) return end + -- FIXME: Could this be simplified using new stroke flags? local parent_data = g.TreeNodeStack.Data[g.TreeNodeStack.Size] local x1 = ImTrunc(parent_data.DrawLinesX1) local x2 = ImTrunc(target_pos.x - g.Style.ItemInnerSpacing.x) @@ -7332,6 +7874,7 @@ function ImGui.TreeNodeDrawLineToChildNode(target_pos) end end +-- Draw vertical line of the hierarchy --- @param data ImGuiTreeNodeStackData function ImGui.TreeNodeDrawLineToTreePop(data) local g = GImGui @@ -7344,7 +7887,7 @@ function ImGui.TreeNodeDrawLineToTreePop(data) y2_full = ImMax(g.CurrentTable.RowPosY2, y2_full) end y2_full = ImTrunc(y2_full - g.Style.ItemSpacing.y - g.FontSize * 0.5) - if y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full then + if y2 + (g.Style.ItemSpacing.y + g.Style.TreeLinesRounding) < y2_full then -- FIXME: threshold to use ToNodes Y2 instead of Full Y2 when close by ItemSpacing.y y2 = y2_full end end @@ -7352,10 +7895,12 @@ function ImGui.TreeNodeDrawLineToTreePop(data) if y2 <= y1 then return end - local x = ImTrunc(data.DrawLinesX1 - g.Style.TreeLinesSize * 0.5) + g.Style.TreeLinesSize * 0.5 + local x = ImTrunc(data.DrawLinesX1 - g.Style.TreeLinesSize * 0.5) + g.Style.TreeLinesSize * 0.5 -- Draw line centered at X1, but snap to pixels boundary. if data.DrawLinesTableColumn ~= -1 then ImGui.TablePushColumnChannel(data.DrawLinesTableColumn) end + + -- We use AddLine() instead of AddLineV() as we provide coordinates for line center (FIXME-OPT) window.DrawList:AddLine(ImVec2(x, y1), ImVec2(x, y2), ImGui.GetColorU32(ImGuiCol.TreeLines), g.Style.TreeLinesSize) if data.DrawLinesTableColumn ~= -1 then ImGui.TablePopColumnChannel() @@ -7391,12 +7936,14 @@ function ImGui.TreePop() local data = g.TreeNodeStack.Data[g.TreeNodeStack.Size] IM_ASSERT(data.ID == window.IDStack:back()) + -- Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags.NavLeftJumpsToParent is enabled) if bit32.band(data.TreeFlags, ImGuiTreeNodeFlags.NavLeftJumpsToParent) ~= 0 then if g.NavIdIsAlive and g.NavMoveDir == ImGuiDir.Left and g.NavWindow == window and ImGui.NavMoveRequestButNoResultYet() then ImGui.NavMoveRequestResolveWithPastTreeNode(g.NavMoveResultLocal, data) end end + -- Draw hierarchy lines if data.DrawLinesX1 ~= FLT_MAX and window.DC.CursorPos.y >= window.ClipRect.Min.y then ImGui.TreeNodeDrawLineToTreePop(data) end @@ -7406,10 +7953,11 @@ function ImGui.TreePop() window.DC.TreeRecordsClippedNodesY2Mask = bit32.band(window.DC.TreeRecordsClippedNodesY2Mask, bit32.bnot(tree_depth_mask)) end - IM_ASSERT(window.IDStack.Size > 1) + 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. ImGui.PopID() end +-- Set next TreeNode/CollapsingHeader open state. --- @param is_open bool --- @param cond? ImGuiCond function ImGui.SetNextItemOpen(is_open, cond) @@ -7430,6 +7978,7 @@ function ImGui.GetTreeNodeToLabelSpacing() return g.FontSize + (g.Style.FramePadding.x * 2.0) end +-- Set next TreeNode/CollapsingHeader storage id. --- @param storage_id ImGuiID function ImGui.SetNextItemStorageID(storage_id) local g = GImGui @@ -7440,8 +7989,14 @@ function ImGui.SetNextItemStorageID(storage_id) g.NextItemData.StorageId = storage_id end +-- CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags.NoTreePushOnOpen flag). +-- This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags.CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). -- Overloads: CollapsingHeader(label, flags?) -> is_open -- CollapsingHeader(label, p_visible: bool, flags?) -> is_open, p_visible +-- p_visible == nil : regular collapsing header +-- p_visible == true : show a small close button on the corner of the header, clicking the button will set p_visible = false (returned as 2nd value) +-- p_visible == false : do not show the header at all +-- Do not mistake this with the Open state of the header itself, which you can adjust with SetNextItemOpen() or ImGuiTreeNodeFlags.DefaultOpen. --- @param label string @native function ImGui.CollapsingHeader(label, a, b) @@ -7466,6 +8021,8 @@ function ImGui.CollapsingHeader(label, a, b) local is_open = ImGui.TreeNodeBehavior(id, flags, label) if p_visible ~= nil then -- Create a small overlapping close button + -- FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + -- FIXME: CloseButton can overlap into text, need find a way to clip the text somehow. local g = GImGui local last_item_backup = ImGuiLastItemData() ImGuiLastItemData_Copy(last_item_backup, g.LastItemData) @@ -7482,15 +8039,15 @@ function ImGui.CollapsingHeader(label, a, b) return is_open, p_visible end ----------------------------------------------------------------- --- [SECTION] SELECTABLE ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: Selectable +------------------------------------------------------------------------------- -- - Selectable() ----------------------------------------------------------------- +------------------------------------------------------------------------------- -- Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image. -- But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id. --- With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowOverlap are also frequently used flags. +-- With this scheme, ImGuiSelectableFlags.SpanAllColumns and ImGuiSelectableFlags.AllowOverlap are also frequently used flags. -- FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported. --- @param label string --- @param selected? bool @@ -7512,6 +8069,7 @@ function ImGui.Selectable(label, selected, flags, size_arg) local g = GImGui local style = g.Style + -- Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle. local id = window:GetID(label) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) @@ -7546,6 +8104,7 @@ function ImGui.Selectable(label, selected, flags, size_arg) bb.Max.x = bb.Max.x + (spacing_x - spacing_L) bb.Max.y = bb.Max.y + (spacing_y - spacing_U) end + -- if g.IO.KeyCtrl then ImGui.GetForegroundDrawList():AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)) end local disabled_item = bit32.band(flags, ImGuiSelectableFlags.Disabled) ~= 0 local extra_item_flags = disabled_item and ImGuiItemFlags.Disabled or ImGuiItemFlags.None @@ -7570,16 +8129,14 @@ function ImGui.Selectable(label, selected, flags, size_arg) local is_multi_select = bit32.band(g.LastItemData.ItemFlags, ImGuiItemFlags.IsMultiSelect) ~= 0 if not is_visible then - if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(bb) then - -- Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd) + if not is_multi_select or not g.BoxSelectState.UnclipMode or not g.BoxSelectState.UnclipRect:Overlaps(bb) then -- Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd) return false, selected end end local disabled_global = bit32.band(g.CurrentItemFlags, ImGuiItemFlags.Disabled) ~= 0 - if disabled_item and not disabled_global then - -- Only testing this as an optimization + if disabled_item and not disabled_global then -- Only testing this as an optimization ImGui.BeginDisabled() end @@ -7638,7 +8195,7 @@ function ImGui.Selectable(label, selected, flags, size_arg) -- Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad if pressed or (hovered and bit32.band(flags, ImGuiSelectableFlags.SetNavIdOnHover) ~= 0) then if not g.NavHighlightItemUnderNav and g.NavWindow == window and g.NavLayer == window.DC.NavLayerCurrent then - ImGui.SetNavID(id, window.DC.NavLayerCurrent, g.CurrentFocusScopeId, ImGui.WindowRectAbsToRel(window, bb)) -- (bb == NavRect) + ImGui.SetNavID(id, window.DC.NavLayerCurrent, g.CurrentFocusScopeId, ImGui.WindowRectAbsToRel(window, bb)) -- (bb == NavRect) if g.IO.ConfigNavCursorVisibleAuto then g.NavCursorVisible = false end @@ -7704,15 +8261,25 @@ function ImGui.Selectable(label, selected, flags, size_arg) ImGui.EndDisabled() end - -- Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui::IsItemToggledSelection() to retrieve + -- Selectable() always returns a pressed state! + -- Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui.IsItemToggledSelection() to retrieve -- selection toggle, only useful if you need that state updated (e.g. for rendering purpose) before reaching EndMultiSelect(). return pressed, selected end ----------------------------------------------------------------- --- [SECTION] LISTBOX ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: ListBox +------------------------------------------------------------------------------- +-- - BeginListBox() +-- - EndListBox() +-- - ListBox() +------------------------------------------------------------------------------- +-- 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. +-- 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.5f * item_height). --- @param label string --- @param size_arg? ImVec2 function ImGui.BeginListBox(label, size_arg) @@ -7728,6 +8295,8 @@ function ImGui.BeginListBox(label, size_arg) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) + -- Size default to hold ~7.25 items. + -- Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. local size = ImTrunc(ImGui.CalcItemSize(size_arg, ImGui.CalcItemWidth(), ImGui.GetTextLineHeightWithSpacing() * 7.25 + style.FramePadding.y * 2.0)) local frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)) local frame_bb = ImRect(window.DC.CursorPos, window.DC.CursorPos + frame_size) @@ -7737,10 +8306,11 @@ function ImGui.BeginListBox(label, size_arg) if not ImGui.IsRectVisible(bb.Min, bb.Max) then ImGui.ItemSize(bb:GetSize(), style.FramePadding.y) ImGui.ItemAdd(bb, 0, frame_bb) - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values return false end + -- FIXME-OPT: We could omit the BeginGroup() if label_size.x == 0.0f but would need to omit the EndGroup() as well. ImGui.BeginGroup() if label_size.x > 0.0 then local label_pos = ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y) @@ -7759,9 +8329,11 @@ function ImGui.EndListBox() IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.ChildWindow) ~= 0, "Mismatched BeginListBox/EndListBox calls. Did you test the return value of BeginListBox?") ImGui.EndChild() - ImGui.EndGroup() + ImGui.EndGroup() -- This is only required to be able to do IsItemXXX query on the whole ListBox including label end +-- This is merely a helper around BeginListBox(), EndListBox(). +-- Considering using those directly to submit custom data or store selection differently. -- Overloads: (label, current_item, items[], items_count?, height_in_items?) or (label, current_item, getter, user_data, items_count, height_in_items?) --- @param current_item int # 0-based --- @return int current_item @@ -7771,6 +8343,7 @@ function ImGui.ListBox(label, current_item, a, b, c, d) local getter, user_data, items_count, height_in_items = Items_ResolveArgs(a, b, c, d) if height_in_items == nil then height_in_items = -1 end + -- Calculate size from "height_in_items" if height_in_items < 0 then height_in_items = ImMin(items_count, 7) end @@ -7781,9 +8354,11 @@ function ImGui.ListBox(label, current_item, a, b, c, d) return current_item, false end + -- Assume all items have even height (= 1 line of text). If you need items of different height, + -- you can create a custom version of ListBox() in your code without using the clipper. local value_changed = false local clipper = ImGuiListClipper() - clipper:Begin(items_count, ImGui.GetTextLineHeightWithSpacing()) + clipper:Begin(items_count, ImGui.GetTextLineHeightWithSpacing()) -- We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. clipper:IncludeItemByIndex(current_item) while clipper:Step() do for i = clipper.DisplayStart, clipper.DisplayEnd - 1 do @@ -7813,9 +8388,16 @@ function ImGui.ListBox(label, current_item, a, b, c, d) return current_item, value_changed end ----------------------------------------------------------------- --- [SECTION] BASIC PLOTTING ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] Widgets: PlotLines, PlotHistogram +------------------------------------------------------------------------------- +-- - PlotEx() [Internal] +-- - PlotLines() +-- - PlotHistogram() +------------------------------------------------------------------------------- +-- Plot/Graph widgets are not very good. +-- Consider using ImPlot (https://github.com/epezent/implot) which is much better! +------------------------------------------------------------------------------- --- @param plot_type ImGuiPlotType --- @param label string @@ -7852,6 +8434,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local _, hovered, _ = ImGui.ButtonBehavior(frame_bb, id) + -- Determine scale from values if not specified if scale_min == FLT_MAX or scale_max == FLT_MAX then local v_min = FLT_MAX local v_max = -FLT_MAX @@ -7878,6 +8461,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local res_w = ImMin(math.floor(frame_size.x), values_count) + ((plot_type == ImGuiPlotType.Lines) and -1 or 0) local item_count = values_count + ((plot_type == ImGuiPlotType.Lines) and -1 or 0) + -- Tooltip on hover if hovered and inner_bb:Contains(g.IO.MousePos) then local t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0, 0.999) local v_idx = math.floor(t * item_count) + 1 @@ -7898,8 +8482,8 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local v0 = values_getter(data, (0 + values_offset) % values_count + 1) local t0 = 0.0 - local tp0 = ImVec2(t0, 1.0 - ImSaturate((v0 - scale_min) * inv_scale)) - local histogram_zero_line_t = (scale_min * scale_max < 0.0) and (1 + scale_min * inv_scale) or (scale_min < 0.0 and 0.0 or 1.0) + local tp0 = ImVec2(t0, 1.0 - ImSaturate((v0 - scale_min) * inv_scale)) -- Point in the normalized space of our target rectangle + local histogram_zero_line_t = (scale_min * scale_max < 0.0) and (1 + scale_min * inv_scale) or (scale_min < 0.0 and 0.0 or 1.0) -- Where does the zero line stands local col_base = ImGui.GetColorU32((plot_type == ImGuiPlotType.Lines) and ImGuiCol.PlotLines or ImGuiCol.PlotHistogram) local col_hovered = ImGui.GetColorU32((plot_type == ImGuiPlotType.Lines) and ImGuiCol.PlotLinesHovered or ImGuiCol.PlotHistogramHovered) @@ -7911,6 +8495,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value local v1 = values_getter(data, (v1_idx - 1 + values_offset + 1) % values_count + 1) local tp1 = ImVec2(t1, 1.0 - ImSaturate((v1 - scale_min) * inv_scale)) + -- NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. local pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0) local pos1 if plot_type == ImGuiPlotType.Lines then @@ -7933,6 +8518,7 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value end end + -- Text overlay if overlay_text then ImGui.RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, nil, nil, ImVec2(0.5, 0.0)) end @@ -7941,6 +8527,8 @@ function ImGui.PlotEx(plot_type, label, values_getter, data, values_count, value ImGui.RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label, 1, label_end, false) end + -- Return hovered index or -1 if none are hovered. + -- This is currently not exposed in the public API because we need a larger redesign of the whole thing, but in the short-term we are making it available in PlotEx(). return idx_hovered end @@ -7992,6 +8580,7 @@ function ImGui.PlotLines(label, values_or_getter, data, values_count, values_off end end +-- Plot Histogram (the data provided _is_ histogram data. it doesn't compute the histogram of your data) --- @param label string --- @param values_or_getter table|fun(data:table, i:int) # 1-based table or a function --- @param data? table # 1-based table @@ -8017,10 +8606,21 @@ function ImGui.PlotHistogram(label, values_or_getter, data, values_count, values end end ----------------------------------------------------------------- --- [SECTION] MENU RELATED ----------------------------------------------------------------- +------------------------------------------------------------------------------- +-- [SECTION] MenuItem, BeginMenu, EndMenu, etc. +------------------------------------------------------------------------------- +-- - ImGuiMenuColumns [Internal] +-- - BeginMenuBar() +-- - EndMenuBar() +-- - BeginMainMenuBar() +-- - EndMainMenuBar() +-- - BeginMenu() +-- - EndMenu() +-- - MenuItemEx() [Internal] +-- - MenuItem() +------------------------------------------------------------------------------- +-- Helpers for internal use --- @param spacing float --- @param window_reappearing bool function MT.ImGuiMenuColumns:Update(spacing, window_reappearing) @@ -8081,7 +8681,7 @@ function ImGui.BeginMenuBar() end IM_ASSERT(not window.DC.MenuBarAppending) - ImGui.BeginGroup() -- FIXME: Misleading to use a group for that backup/restore + ImGui.BeginGroup() -- Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore ImGui.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. @@ -8093,7 +8693,7 @@ function ImGui.BeginMenuBar() clip_rect:ClipWith(window.OuterRectClipped) ImGui.PushClipRect(clip_rect.Min, clip_rect.Max, false) - -- We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags) + -- We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags). ImVec2_Copy(window.DC.CursorPos, ImVec2(bar_rect.Min.x + window.DC.MenuBarOffset.x, bar_rect.Min.y + window.DC.MenuBarOffset.y)) ImVec2_Copy(window.DC.CursorMaxPos, window.DC.CursorPos) window.DC.LayoutType = ImGuiLayoutType.Horizontal @@ -8115,24 +8715,28 @@ function ImGui.EndMenuBar() IM_ASSERT(bit32.band(window.Flags, ImGuiWindowFlags.MenuBar) ~= 0) 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 + -- Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings. if ImGui.NavMoveRequestButNoResultYet() and (g.NavMoveDir == ImGuiDir.Left or g.NavMoveDir == ImGuiDir.Right) and bit32.band(g.NavWindow.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then + -- Try to find out if the request is for one of our child menu local nav_earliest_child = g.NavWindow while nav_earliest_child.ParentWindow and bit32.band(nav_earliest_child.ParentWindow.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 do nav_earliest_child = nav_earliest_child.ParentWindow end if nav_earliest_child.ParentWindow == window and nav_earliest_child.DC.ParentLayoutType == ImGuiLayoutType.Horizontal and bit32.band(g.NavMoveFlags, ImGuiNavMoveFlags.Forwarded) == 0 then + -- To do so we claim focus back, restore NavId and then process the movement request for yet another frame. + -- This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth bothering) local layer = ImGuiNavLayer.Menu - IM_ASSERT(bit32.band(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, layer)) ~= 0) + IM_ASSERT(bit32.band(window.DC.NavLayersActiveMaskNext, bit32.lshift(1, layer)) ~= 0) -- Sanity check (FIXME: Seems unnecessary) ImGui.FocusWindow(window) ImGui.SetNavID(window.NavLastIds[layer], layer, 0, window.NavRectRel[layer]) + -- FIXME-NAV: How to deal with this when not using g.IO.ConfigNavCursorVisibleAuto? if g.NavCursorVisible then - g.NavCursorVisible = false + g.NavCursorVisible = false -- Hide nav cursor for the current frame so we don't see the intermediary selection. Will be set again g.NavCursorHideFrames = 2 end g.NavHighlightItemUnderNav = true g.NavMousePosDirty = true - ImGui.NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags) + ImGui.NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags) -- Repeat end else ImGui.NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags.WrapX) @@ -8140,14 +8744,14 @@ function ImGui.EndMenuBar() ImGui.PopClipRect() ImGui.PopID() - 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 + 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 + -- FIXME: Extremely confusing, cleanup by (a) working on WorkRect stack system (b) not using a Group confusingly here. local group_data = g.GroupStack:back() group_data.EmitItem = false local restore_cursor_max_pos = ImVec2() ImVec2_Copy(restore_cursor_max_pos, group_data.BackupCursorMaxPos) - window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, window.DC.CursorMaxPos.x - window.Scroll.x) -- Convert ideal extents for scrolling layer equivalent + window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, window.DC.CursorMaxPos.x - window.Scroll.x) -- Convert ideal extents for scrolling layer equivalent. ImGui.EndGroup() -- Restore position on layer 0 // FIXME: Misleading to use a group for that backup/restore window.DC.LayoutType = ImGuiLayoutType.Vertical window.DC.IsSameLine = false @@ -8157,6 +8761,8 @@ function ImGui.EndMenuBar() end -- Important: calling order matters! +-- FIXME: Somehow overlapping with docking tech. +-- FIXME: The "rect-cut" aspect of this could be formalized into a lower-level helper (rect-cut: https://halt.software/dead-simple-layouts) --- @param name string --- @param viewport_p? ImGuiViewport --- @param dir ImGuiDir @@ -8168,6 +8774,7 @@ function ImGui.BeginViewportSideBar(name, viewport_p, dir, axis_size, window_fla local bar_window = ImGui.FindWindowByName(name) local viewport = viewport_p or ImGui.GetMainViewport() if bar_window == nil or bar_window.BeginCount == 0 then + -- Calculate and set window size/position local avail_rect = viewport:GetBuildWorkRect() local axis = (dir == ImGuiDir.Up or dir == ImGuiDir.Down) and ImGuiAxis.Y or ImGuiAxis.X local pos = ImVec2(avail_rect.Min.x, avail_rect.Min.y) @@ -8179,6 +8786,7 @@ function ImGui.BeginViewportSideBar(name, viewport_p, dir, axis_size, window_fla ImGui.SetNextWindowPos(pos) ImGui.SetNextWindowSize(size) + -- Report our size into work area (for next frame) using actual window size if dir == ImGuiDir.Up or dir == ImGuiDir.Left then viewport.BuildWorkInsetMin[axis] = viewport.BuildWorkInsetMin[axis] + axis_size elseif dir == ImGuiDir.Down or dir == ImGuiDir.Right then @@ -8189,7 +8797,7 @@ function ImGui.BeginViewportSideBar(name, viewport_p, dir, axis_size, window_fla window_flags = bit32.bor(window_flags or 0, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoResize, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoDocking) ImGui.SetNextWindowViewport(viewport.ID) ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 0.0) - ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, ImVec2(0, 0)) + ImGui.PushStyleVar(ImGuiStyleVar.WindowMinSize, ImVec2(0, 0)) -- Lift normal size constraint local _, is_open = ImGui.Begin(name, nil, window_flags) ImGui.PopStyleVar(2) @@ -8200,8 +8808,12 @@ function ImGui.BeginMainMenuBar() local g = GImGui local viewport = ImGui.GetMainViewport() + -- Notify of viewport change so GetFrameHeight() can be accurate in case of DPI change ImGui.SetCurrentViewport(nil, viewport) + -- For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set. + -- FIXME: This could be generalized as an opt-in way to clamp window.DC.CursorStartPos to avoid SafeArea? + -- FIXME: Consider removing support for safe area down the line... it's messy. Nowadays consoles have support for TV calibration in OS settings. g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0)) local window_flags = bit32.bor(ImGuiWindowFlags.NoScrollbar, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.MenuBar) local height = ImGui.GetFrameHeight() @@ -8212,6 +8824,7 @@ function ImGui.BeginMainMenuBar() return false end + -- 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 = bit32.band(g.CurrentWindow.Flags, bit32.bnot(ImGuiWindowFlags.NoSavedSettings)) ImGui.BeginMenuBar() return is_open @@ -8219,11 +8832,13 @@ end function ImGui.EndMainMenuBar() local g = GImGui - IM_ASSERT_USER_ERROR_RET(g.CurrentWindow.DC.MenuBarAppending, "Calling EndMainMenuBar() not from a menu-bar!") + IM_ASSERT_USER_ERROR_RET(g.CurrentWindow.DC.MenuBarAppending, "Calling EndMainMenuBar() not from a menu-bar!") -- Not technically testing that it is the main menu bar ImGui.EndMenuBar() - g.CurrentWindow.Flags = bit32.bor(g.CurrentWindow.Flags, ImGuiWindowFlags.NoSavedSettings) + g.CurrentWindow.Flags = bit32.bor(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 nil focus. if g.CurrentWindow == g.NavWindow and g.NavLayer == ImGuiNavLayer.Main and not g.NavAnyRequest and g.ActiveId == 0 then ImGui.FocusTopMostWindowUnderOne(g.NavWindow, nil, nil, bit32.bor(ImGuiFocusRequestFlags.UnlessBelowModal, ImGuiFocusRequestFlags.RestoreFocusedChild)) end @@ -8238,6 +8853,17 @@ local function IsRootOfOpenMenuSet() return false end + -- Initially we used 'upper_popup.OpenParentId == window.IDStack:back()' to differentiate multiple menu sets from each others + -- (e.g. inside menu bar vs loose menu items) based on parent ID. + -- This would however prevent the use of e.g. PushID() user code submitting menus. + -- Previously this worked between popup and a first child menu because the first child menu always had the _ChildWindow flag, + -- making hovering on parent popup possible while first child menu was focused - but this was generally a bug with other side effects. + -- Instead we don't treat Popup specifically (in order to consistently support menu features in them), maybe the first child menu of a Popup + -- doesn't have the _ChildWindow flag, and we rely on this IsRootOfOpenMenuSet() check to allow hovering between root window/popup and first child menu. + -- In the end, lack of ID check made it so we could no longer differentiate between separate menu sets. To compensate for that, we at least check parent window nav layer. + -- This fixes the most common case of menu opening on hover when moving between window content and menu bar. Multiple different menu sets in same nav layer would still + -- open on hover, but that should be a lesser problem, because if such menus are close in proximity in window content then it won't feel weird and if they are far apart + -- it likely won't be a problem anyone runs into. local upper_popup = g.OpenPopupStack.Data[g.BeginPopupStack.Size + 1] if window.DC.NavLayerCurrent ~= upper_popup.ParentNavLayer then return false @@ -8259,30 +8885,41 @@ function ImGui.BeginMenuEx(label, icon, enabled) local id = window:GetID(label) local menu_is_open = ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) + -- Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu) + -- The first menu in a hierarchy isn't so hovering doesn't get across (otherwise e.g. resizing borders with ImGuiButtonFlags.FlattenChildren would react), but top-most BeginMenu() will bypass that limitation. local window_flags = bit32.bor(ImGuiWindowFlags.ChildMenu, ImGuiWindowFlags.AlwaysAutoResize, ImGuiWindowFlags.NoMove, ImGuiWindowFlags.NoTitleBar, ImGuiWindowFlags.NoSavedSettings, ImGuiWindowFlags.NoNavFocus) if bit32.band(window.Flags, ImGuiWindowFlags.ChildMenu) ~= 0 then window_flags = bit32.bor(window_flags, ImGuiWindowFlags.ChildWindow) end + -- If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin(). + -- We are relying on a O(N) search - so O(N log N) over the frame - which seems like the most efficient for the expected small amount of BeginMenu() calls per frame. + -- If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used. if g.MenusIdSubmittedThisFrame:contains(id) then if menu_is_open then - menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags) + menu_is_open = ImGui.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() + g.NextWindowData:ClearFlags() -- we behave like Begin() and need to consume those values end return menu_is_open end + -- Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu g.MenusIdSubmittedThisFrame:push_back(id) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) + -- Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent without always being a Child window) + -- This is only done for items for the menu set and not the full parent window. local menuset_is_open = IsRootOfOpenMenuSet() if menuset_is_open then g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoWindowHoverableCheck) end + -- The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu, + -- However the final position is going to be different! It is chosen by FindBestWindowPosForPopup(). + -- e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering. local popup_pos local pos = ImVec2() ImVec2_Copy(pos, window.DC.CursorPos) @@ -8298,6 +8935,9 @@ function ImGui.BeginMenuEx(label, icon, enabled) local selectable_flags = bit32.bor(ImGuiSelectableFlags.SelectOnClick, ImGuiSelectableFlags.NoAutoClosePopups) local offsets = window.DC.MenuColumns if window.DC.LayoutType == ImGuiLayoutType.Horizontal then + -- 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() window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * 0.5) ImGui.PushStyleVarX(ImGuiStyleVar.ItemSpacing, style.ItemSpacing.x * 2.0) local text_pos = ImVec2(window.DC.CursorPos.x + offsets.OffsetLabel, pos.y + window.DC.CurrLineTextBaseOffset) @@ -8305,13 +8945,16 @@ function ImGui.BeginMenuEx(label, icon, enabled) -- TODO: ImGui.LogSetNextTextDecoration("[", "]") ImGui.RenderText(text_pos, label, 1, label_end, false) ImGui.PopStyleVar() - window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) + window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) -- -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). popup_pos = ImVec2(pos.x - 1.0 - IM_TRUNC(style.ItemSpacing.x * 0.5), text_pos.y - style.FramePadding.y + window.MenuBarHeight) else + -- 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.) local icon_w if (icon and icon ~= "") then icon_w = ImGui.CalcTextSize(icon, nil).x else icon_w = 0.0 end local checkmark_w = IM_TRUNC(g.FontSize * 1.20) - local min_w = offsets:DeclColumns(icon_w, label_size.x, 0.0, checkmark_w) + local min_w = offsets:DeclColumns(icon_w, label_size.x, 0.0, checkmark_w) -- Feedback to next frame local extra_w = ImMax(0.0, ImGui.GetContentRegionAvail().x - min_w) local text_pos = ImVec2(window.DC.CursorPos.x, pos.y + window.DC.CurrLineTextBaseOffset) pressed = ImGui.Selectable("", menu_is_open, bit32.bor(selectable_flags, ImGuiSelectableFlags.SpanAvailWidth), ImVec2(min_w, label_size.y)) @@ -8330,6 +8973,8 @@ function ImGui.BeginMenuEx(label, icon, enabled) ImGui.EndDisabled() end + -- Once dragged, release ActiveId + key ownership. This is to allow the idiom of mouse down a menu, dragging elsewhere, up on some other MenuItem(). (#8233, #9394) + -- Could move logic into lower-level ImGuiButtonFlags.AutoReleaseActiveId + ImGuiButtonFlags.AutoReleaseKeyOwner? Easier once we get rid of the Selectable() middle-man here. if g.ActiveId == id and g.HoveredId ~= id and g.ActiveIdSource == ImGuiInputSource.Mouse and ImGui.IsMouseDragging(0) then ImGui.ClearActiveID() ImGui.SetKeyOwner(ImGuiKey.MouseLeft, ImGuiKeyOwner_NoOwner) @@ -8340,12 +8985,14 @@ function ImGui.BeginMenuEx(label, icon, enabled) local want_open = false local want_open_nav_init = false local want_close = false - if window.DC.LayoutType == ImGuiLayoutType.Vertical then + if window.DC.LayoutType == ImGuiLayoutType.Vertical then -- (window.Flags & (ImGuiWindowFlags.Popup|ImGuiWindowFlags.ChildMenu)) + -- Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu + -- Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. local moving_toward_child_menu = false - local child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) and g.OpenPopupStack[g.BeginPopupStack.Size + 1] or nil + local child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) and g.OpenPopupStack[g.BeginPopupStack.Size + 1] or nil -- Popup candidate (testing below) local child_menu_window = (child_popup and child_popup.Window and child_popup.Window.ParentWindow == window) and child_popup.Window or nil if g.HoveredWindow == window and child_menu_window ~= nil then - local ref_unit = g.FontSize + local ref_unit = g.FontSize -- FIXME-DPI local child_dir = (window.Pos.x < child_menu_window.Pos.x) and 1.0 or -1.0 local next_window_rect = child_menu_window:Rect() local ta = (g.IO.MousePos - g.IO.MouseDelta) @@ -8358,46 +9005,53 @@ function ImGui.BeginMenuEx(label, icon, enabled) tb = next_window_rect:GetTR() tc = next_window_rect:GetBR() end - local pad_farmost_h = ImClamp(ImFabs(ta.x - tb.x) * 0.30, ref_unit * 0.5, ref_unit * 2.5) + local pad_farmost_h = ImClamp(ImFabs(ta.x - tb.x) * 0.30, ref_unit * 0.5, ref_unit * 2.5) -- Add a bit of extra slack. ta.x = ta.x + child_dir * -0.5 tb.x = tb.x + child_dir * ref_unit tc.x = tc.x + child_dir * ref_unit - tb.y = ta.y + ImMax((tb.y - pad_farmost_h) - ta.y, -ref_unit * 8.0) + tb.y = ta.y + ImMax((tb.y - pad_farmost_h) - ta.y, -ref_unit * 8.0) -- Triangle has maximum height to limit the slope and the bias toward large sub-menus tc.y = ta.y + ImMin((tc.y + pad_farmost_h) - ta.y, ref_unit * 8.0) moving_toward_child_menu = ImStd.ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos) + -- ImGui.GetForegroundDrawList():AddTriangleFilled(ta, tb, tc, moving_toward_child_menu and IM_COL32(0, 128, 0, 128) or IM_COL32(128, 0, 0, 128)) -- [DEBUG] end + -- The 'HovereWindow == window' check creates an inconsistency (e.g. moving away from menu slowly tends to hit same window, whereas moving away fast does not) + -- But we also need to not close the top-menu menu when moving over void. Perhaps we should extend the triangle check to a larger polygon. + -- (Remember to test this on BeginPopup("A")->BeginMenu("B") sequence which behaves slightly differently as B isn't a Child of A and hovering isn't shared.) if menu_is_open and not hovered and g.HoveredWindow == window and not moving_toward_child_menu and not g.NavHighlightItemUnderNav and g.ActiveId == 0 then want_close = true end - if not menu_is_open and pressed then + -- Open + -- (note: at this point 'hovered' actually includes the NavDisableMouseHover == false test) + if not menu_is_open and pressed then -- Click/activate to open want_open = true - elseif not menu_is_open and hovered and not moving_toward_child_menu then + elseif not menu_is_open and hovered and not moving_toward_child_menu then -- Hover to open want_open = true - elseif not menu_is_open and hovered and g.HoveredIdTimer >= 0.30 and g.MouseStationaryTimer >= 0.30 then + elseif not menu_is_open and hovered and g.HoveredIdTimer >= 0.30 and g.MouseStationaryTimer >= 0.30 then -- Hover to open (timer fallback) want_open = true end - if g.NavId == id and g.NavMoveDir == ImGuiDir.Right then + if g.NavId == id and g.NavMoveDir == ImGuiDir.Right then -- Nav-Right to open want_open = true want_open_nav_init = true ImGui.NavMoveRequestCancel() ImGui.SetNavCursorVisibleAfterMove() end else - if menu_is_open and pressed and menuset_is_open then + -- Menu bar + if menu_is_open and pressed and menuset_is_open then -- Click an open menu again to close it want_close = true want_open = false menu_is_open = false - elseif pressed or (hovered and menuset_is_open and not menu_is_open) then + elseif pressed or (hovered and menuset_is_open and not menu_is_open) then -- First click to open, then hover to open others want_open = true - elseif g.NavId == id and g.NavMoveDir == ImGuiDir.Down then + elseif g.NavId == id and g.NavMoveDir == ImGuiDir.Down then -- Nav-Down to open want_open = true ImGui.NavMoveRequestCancel() end end - if not enabled then + if not enabled then -- explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' want_close = true end if want_close and ImGui.IsPopupOpen(id, ImGuiPopupFlags.None) then @@ -8412,32 +9066,38 @@ function ImGui.BeginMenuEx(label, icon, enabled) end if want_open and not menu_is_open and g.OpenPopupStack.Size > g.BeginPopupStack.Size then + -- Don't reopen/recycle same menu level in the same frame if it is a different menu ID, first close the other menu and yield for a frame. ImGui.OpenPopup(label) elseif want_open then menu_is_open = true - ImGui.OpenPopup(label, ImGuiPopupFlags.NoReopen) + ImGui.OpenPopup(label, ImGuiPopupFlags.NoReopen) -- | (want_open_nav_init ? ImGuiPopupFlags.NoReopenAlwaysNavInit : 0)) end if menu_is_open then local last_item_in_parent = ImGuiLastItemData() ImGuiLastItemData_Copy(last_item_in_parent, g.LastItemData) - ImGui.SetNextWindowPos(popup_pos, ImGuiCond.Always) - ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.PopupRounding) - menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags) + ImGui.SetNextWindowPos(popup_pos, ImGuiCond.Always) -- Note: misleading: the value will serve as reference for FindBestWindowPosForPopup(), not actual pos. + ImGui.PushStyleVar(ImGuiStyleVar.ChildRounding, style.PopupRounding) -- First level will use _PopupRounding, subsequent will use _ChildRounding + menu_is_open = ImGui.BeginPopupMenuEx(id, label, window_flags) -- menu_is_open may be 'false' when the popup is completely clipped (e.g. zero size display) ImGui.PopStyleVar() if menu_is_open then + -- Implement what ImGuiPopupFlags.NoReopenAlwaysNavInit would do: + -- Perform an init request in the case the popup was already open (via a previous mouse hover) if want_open and want_open_nav_init and not g.NavInitRequest then ImGui.FocusWindow(g.CurrentWindow, ImGuiFocusRequestFlags.UnlessBelowModal) ImGui.NavInitWindow(g.CurrentWindow, false) end + + -- Restore LastItemData so IsItemXXXX functions can work after BeginMenu()/EndMenu() + -- (This fixes using IsItemClicked() and IsItemHovered(), but IsItemHovered() also relies on its support for ImGuiItemFlags.NoWindowHoverableCheck) ImGuiLastItemData_Copy(g.LastItemData, last_item_in_parent) if g.HoveredWindow == window then g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end end else - g.NextWindowData:ClearFlags() + g.NextWindowData:ClearFlags() -- We behave like Begin() and need to consume those values end return menu_is_open @@ -8452,11 +9112,12 @@ function ImGui.BeginMenu(label, enabled) end function ImGui.EndMenu() + -- Nav: When a left move request our menu failed, close ourselves. local g = GImGui local window = g.CurrentWindow IM_ASSERT_USER_ERROR_RET(bit32.band(window.Flags, bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.ChildMenu)) == bit32.bor(ImGuiWindowFlags.Popup, ImGuiWindowFlags.ChildMenu), "Calling EndMenu() in wrong window!") - local parent_window = window.ParentWindow + local parent_window = window.ParentWindow -- Should always be ~= nil is we passed assert. if window.BeginCount == window.BeginCountPreviousFrame then if g.NavMoveDir == ImGuiDir.Left and ImGui.NavMoveRequestButNoResultYet() then if g.NavWindow and g.NavWindow.RootWindowForNav == window and parent_window.DC.LayoutType == ImGuiLayoutType.Vertical then @@ -8490,11 +9151,14 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) local label_end = ImGui.FindRenderedTextEnd(label) local label_size = ImGui.CalcTextSize(label, label_end, false) + -- See BeginMenuEx() for comments about this. local menuset_is_open = IsRootOfOpenMenuSet() if menuset_is_open then g.NextItemData.ItemFlagsSet = bit32.bor(g.NextItemData.ItemFlagsSet, ImGuiItemFlags.NoWindowHoverableCheck) end + -- We've been using the equivalent of ImGuiSelectableFlags.SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73), + -- but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only. ImGui.PushID(label) if not enabled then ImGui.BeginDisabled() @@ -8502,11 +9166,14 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) local pressed + -- We use ImGuiSelectableFlags.NoSetKeyOwner to allow down on one menu item, move, up on another. local backup_rounding = style.SelectableRounding style.SelectableRounding = style.MenuItemRounding local selectable_flags = bit32.bor(ImGuiSelectableFlags.SelectOnRelease, ImGuiSelectableFlags.SetNavIdOnHover) local offsets = window.DC.MenuColumns if window.DC.LayoutType == ImGuiLayoutType.Horizontal then + -- Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful + -- Note that in this situation: we don't render the shortcut, we render a highlight instead of the selected tick mark. window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * 0.5) local text_pos = ImVec2(window.DC.CursorPos.x + offsets.OffsetLabel, window.DC.CursorPos.y + window.DC.CurrLineTextBaseOffset) ImGui.PushStyleVarX(ImGuiStyleVar.ItemSpacing, style.ItemSpacing.x * 2.0) @@ -8515,8 +9182,11 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) if bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 then ImGui.RenderText(text_pos, label, 1, label_end, false) end - window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) + window.DC.CursorPos.x = window.DC.CursorPos.x + IM_TRUNC(style.ItemSpacing.x * (-1.0 + 0.5)) -- -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). else + -- 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.) local icon_w = 0.0 if icon and icon ~= "" then icon_w = ImGui.CalcTextSize(icon, nil).x @@ -8525,8 +9195,8 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) if shortcut and shortcut ~= "" then shortcut_w = ImGui.CalcTextSize(shortcut, nil).x end - local checkmark_w = IM_TRUNC(g.FontSize * 1.20) - local min_w = offsets:DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w) + local checkmark_w = IM_TRUNC(g.FontSize * 1.20) -- FIXME: Always accounted for, even in a menu with none, because 'selected' has no neutral setting. + local min_w = offsets:DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w) -- Feedback for next frame local stretch_w = ImMax(0.0, ImGui.GetContentRegionAvail().x - min_w) local text_pos = ImVec2(pos.x, pos.y + window.DC.CurrLineTextBaseOffset) pressed = ImGui.Selectable("", false, bit32.bor(selectable_flags, ImGuiSelectableFlags.SpanAvailWidth), ImVec2(min_w, label_size.y)) @@ -8550,6 +9220,8 @@ function ImGui.MenuItemEx(label, icon, shortcut, selected, enabled) end style.SelectableRounding = backup_rounding + -- Once dragged, release ActiveId + key ownership. This is to allow the idiom of mouse down a menu, dragging elsewhere, up on some other MenuItem(). (#8233, #9394) + -- Could move logic into lower-level ImGuiButtonFlags_AutoReleaseActiveId + ImGuiButtonFlags_AutoReleaseKeyOwner? Easier once we get rid of the Selectable() middle-man here. local id = g.LastItemData.ID if g.ActiveId == id and g.HoveredId ~= id and g.ActiveIdSource == ImGuiInputSource.Mouse and ImGui.IsMouseDragging(0) then ImGui.ClearActiveID() @@ -8630,12 +9302,18 @@ local function SortTabsByBeginOrder(tab_bar) for i = 1, tab_bar.Tabs.Size do data[i] = arr[i] end end +-- Scrolling happens only in the central section (leading/trailing sections are not scrolling) local function TabBarCalcScrollableWidth(tab_bar, sections) return tab_bar.BarRect:GetWidth() - sections[1].Width - sections[3].Width - sections[2].Spacing end +-- TabCount: Number of tabs in this section. +-- Width: Sum of width of tabs in this section (after shrinking down) +-- Spacing: Horizontal spacing at the end of the section. local function ImGuiTabBarSection() return { TabCount = 0, Width = 0.0, WidthAfterShrinkMinWidth = 0.0, Spacing = 0.0 } end +-- 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. -- items: 1-based array of ImGuiShrinkWidthItem, `first` = 1-based index of first item, `count` items function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) if count <= 0 then return end @@ -8644,6 +9322,7 @@ function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) if it.Width >= 0.0 then it.Width = ImMax(it.Width - width_excess, width_min) end return end + -- Sort largest first, smallest last. local slice = {} for n = 1, count do slice[n] = items[first + n - 1] end table.sort(slice, function(a, b) @@ -8668,6 +9347,9 @@ function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) width_excess = width_excess - w end end + + -- Round width and redistribute remainder + -- Ensure that e.g. the right-most tab of a shrunk tab-bar always reaches exactly at the same distance from the right-most edge of the tab bar separator. width_excess = 0.0 for n = 1, count do local width_rounded = ImTrunc(it[n].Width) @@ -8689,15 +9371,39 @@ function ImGui.ShrinkWidths(items, first, count, width_excess, width_min) end end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Widgets: BeginTabBar, EndTabBar, etc. ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - BeginTabBar() +-- - BeginTabBarEx() [Internal] +-- - EndTabBar() +-- - TabBarLayout() [Internal] +-- - TabBarCalcTabID() [Internal] +-- - TabBarCalcMaxTabWidth() [Internal] +-- - TabBarFindTabById() [Internal] +-- - TabBarFindTabByOrder() [Internal] +-- - TabBarFindMostRecentlySelectedTabForActiveWindow() [Internal] +-- - TabBarGetCurrentTab() [Internal] +-- - TabBarGetTabName() [Internal] +-- - TabBarAddTab() [Internal] +-- - TabBarRemoveTab() [Internal] +-- - TabBarCloseTab() [Internal] +-- - TabBarScrollClamp() [Internal] +-- - TabBarScrollToTab() [Internal] +-- - TabBarQueueFocus() [Internal] +-- - TabBarQueueReorder() [Internal] +-- - TabBarProcessReorderFromMousePos() [Internal] +-- - TabBarProcessReorder() [Internal] +-- - TabBarScrollingButtons() [Internal] +-- - TabBarTabListPopupButton() [Internal] +------------------------------------------------------------------------------- function ImGui.TabBarFindByID(id) SyncContext() return GImGui.TabBars:GetByKey(id) end +-- Remove TabBar data (currently only used by TestEngine) function ImGui.TabBarRemove(tab_bar) SyncContext() GImGui.TabBars:Remove(tab_bar.ID, tab_bar) @@ -8716,6 +9422,7 @@ function ImGui.BeginTabBar(str_id, flags) tab_bar.ID = id tab_bar.SeparatorMinX = tab_bar_bb.Min.x - IM_TRUNC(window.WindowPadding.x * 0.5) tab_bar.SeparatorMaxX = tab_bar_bb.Max.x + IM_TRUNC(window.WindowPadding.x * 0.5) + -- if (g.NavWindow and ImGui.IsWindowChildOf(g.NavWindow, window, false, false)) flags = bit32.bor(flags, ImGuiTabBarFlags.IsFocused) return ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) end @@ -8727,14 +9434,16 @@ function ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) if window.SkipItems then return false end IM_ASSERT(tab_bar.ID ~= 0) - if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then + if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then -- Already done ImGui.PushOverrideID(tab_bar.ID) end + -- Add to stack g.CurrentTabBarStack:push_back(tab_bar) g.CurrentTabBar = tab_bar tab_bar.Window = window + -- Append with multiple BeginTabBar()/EndTabBar() pairs. ImVec2_Copy(tab_bar.BackupCursorPos, window.DC.CursorPos) if tab_bar.CurrFrameVisible == g.FrameCount then ImVec2_CopyV(window.DC.CursorPos, tab_bar.BarRect.Min.x, tab_bar.BarRect.Max.y + tab_bar.ItemSpacingY) @@ -8742,21 +9451,23 @@ function ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) return true end + -- Ensure correct ordering when toggling ImGuiTabBarFlags.Reorderable flag, or when a new tab was added while being not reorderable if bit32.band(flags, ImGuiTabBarFlags.Reorderable) ~= bit32.band(tab_bar.Flags, ImGuiTabBarFlags.Reorderable) or (tab_bar.TabsAddedNew and bit32.band(flags, ImGuiTabBarFlags.Reorderable) == 0) then - if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then + if bit32.band(flags, ImGuiTabBarFlags.DockNode) == 0 then -- FIXME: TabBar with DockNode can now be hybrid SortTabsByBeginOrder(tab_bar) end end tab_bar.TabsAddedNew = false + -- Flags if bit32.band(flags, ImGuiTabBarFlags.FittingPolicyMask_) == 0 then flags = bit32.bor(flags, ImGuiTabBarFlags.FittingPolicyDefault_) end tab_bar.Flags = flags tab_bar.BarRect = ImRect(tab_bar_bb.Min, tab_bar_bb.Max) - tab_bar.WantLayout = true + tab_bar.WantLayout = true -- Layout will be done on the first call to ItemTab() tab_bar.PrevFrameVisible = tab_bar.CurrFrameVisible tab_bar.CurrFrameVisible = g.FrameCount tab_bar.PrevTabsContentsHeight = tab_bar.CurrTabsContentsHeight @@ -8767,8 +9478,11 @@ function ImGui.BeginTabBarEx(tab_bar, tab_bar_bb, flags) tab_bar.LastTabItemIdx = -1 tab_bar.BeginCount = 1 + -- Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap ImVec2_CopyV(window.DC.CursorPos, tab_bar.BarRect.Min.x, tab_bar.BarRect.Max.y + tab_bar.ItemSpacingY) + -- Draw separator + -- (it would be misleading to draw this in EndTabBar() suggesting that it may be drawn over tabs, as tab bar are appendable) local col = ImGui.GetColorU32(bit32.band(flags, ImGuiTabBarFlags.IsFocused) ~= 0 and ImGuiCol.TabSelected or ImGuiCol.TabDimmedSelected) if g.Style.TabBarBorderSize > 0.0 then local y = tab_bar.BarRect.Max.y @@ -8786,8 +9500,10 @@ function ImGui.EndTabBar() local tab_bar = g.CurrentTabBar IM_ASSERT(tab_bar ~= nil, "Mismatched BeginTabBar()/EndTabBar()!") + -- Fallback in case no TabItem have been submitted if tab_bar.WantLayout then ImGui.TabBarLayout(tab_bar) end + -- Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). local tab_bar_appearing = (tab_bar.PrevFrameVisible + 1 < g.FrameCount) if tab_bar.VisibleTabWasSubmitted or tab_bar.VisibleTabId == 0 or tab_bar_appearing then tab_bar.CurrTabsContentsHeight = ImMax(window.DC.CursorPos.y - tab_bar.BarRect.Max.y, tab_bar.CurrTabsContentsHeight) @@ -8800,7 +9516,7 @@ function ImGui.EndTabBar() end tab_bar.LastTabItemIdx = -1 - if bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0 then + if bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0 then -- Already done ImGui.PopID() end @@ -8808,22 +9524,27 @@ function ImGui.EndTabBar() if g.CurrentTabBarStack.Size == 0 then g.CurrentTabBar = nil else g.CurrentTabBar = g.CurrentTabBarStack.Data[g.CurrentTabBarStack.Size] end end +-- This is called only once a frame before by the first call to ItemTab() +-- The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions. function ImGui.TabBarLayout(tab_bar) SyncContext() local g = GImGui tab_bar.WantLayout = false + -- Track selected tab when resizing our parent down local 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) local tabs = tab_bar.Tabs local tab_dst_n = 0 local need_sort_by_section = false - local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- 1-based: [1]=Leading,[2]=Central,[3]=Trailing + local sections = { ImGuiTabBarSection(), ImGuiTabBarSection(), ImGuiTabBarSection() } -- Layout sections: Leading, Central, Trailing (1-based: [1]=Leading,[2]=Central,[3]=Trailing) for tab_src_n = 0, tabs.Size - 1 do local tab = tabs.Data[tab_src_n + 1] if tab.LastFrameVisible < tab_bar.PrevFrameVisible or tab.WantClose then + -- Remove tab if tab_bar.VisibleTabId == tab.ID then tab_bar.VisibleTabId = 0 end if tab_bar.SelectedTabId == tab.ID then tab_bar.SelectedTabId = 0 end if tab_bar.NextSelectedTabId == tab.ID then tab_bar.NextSelectedTabId = 0 end @@ -8831,6 +9552,7 @@ function ImGui.TabBarLayout(tab_bar) if tab_dst_n ~= tab_src_n then tabs.Data[tab_dst_n + 1] = tab end tab.IndexDuringLayout = tab_dst_n + -- We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another) local curr_tab_section_n = TabItemGetSectionIdx(tab) if tab_dst_n > 0 then local prev_tab = tabs.Data[tab_dst_n] @@ -8849,10 +9571,12 @@ function ImGui.TabBarLayout(tab_bar) if need_sort_by_section then SortTabsBySection(tab_bar) end + -- Calculate spacing between sections local tab_spacing = g.Style.ItemInnerSpacing.x sections[1].Spacing = (sections[1].TabCount > 0 and (sections[2].TabCount + sections[3].TabCount) > 0) and tab_spacing or 0.0 sections[2].Spacing = (sections[2].TabCount > 0 and sections[3].TabCount > 0) and tab_spacing or 0.0 + -- Setup next selected tab local scroll_to_tab_id = 0 if tab_bar.NextScrollToTabId ~= 0 then scroll_to_tab_id = tab_bar.NextScrollToTabId @@ -8864,6 +9588,7 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.SelectedTabId end + -- Process order change request (we could probably process it when requested but it's just saner to do it in a single spot). if tab_bar.ReorderRequestTabId ~= 0 then if ImGui.TabBarProcessReorder(tab_bar) then if tab_bar.ReorderRequestTabId == tab_bar.SelectedTabId then @@ -8873,23 +9598,28 @@ function ImGui.TabBarLayout(tab_bar) tab_bar.ReorderRequestTabId = 0 end + -- Tab List Popup (will alter tab_bar.BarRect and therefore the available width!) local tab_list_popup_button = bit32.band(tab_bar.Flags, ImGuiTabBarFlags.TabListPopupButton) ~= 0 if tab_list_popup_button then - local tab_to_select = ImGui.TabBarTabListPopupButton(tab_bar) + local tab_to_select = ImGui.TabBarTabListPopupButton(tab_bar) -- NB: Will alter BarRect.Min.x! if tab_to_select then tab_bar.SelectedTabId = tab_to_select.ID scroll_to_tab_id = tab_to_select.ID end end - -- shrink buffer layout: leading, trailing, central (0-based offsets) + -- Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central + -- (whereas our tabs are stored as: leading, central, trailing) + -- (shrink_buffer_indexes holds 0-based offsets) local shrink_buffer_indexes = { 0, sections[1].TabCount + sections[3].TabCount, sections[1].TabCount } local swb = g.ShrinkWidthBuffer swb:resize(tabs.Size) for i = 1, tabs.Size do if swb.Data[i] == nil then swb.Data[i] = ImGuiShrinkWidthItem() end end + -- Minimum shrink width local shrink_min_width = (bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyMixed) ~= 0) and g.Style.TabMinWidthShrink or 1.0 + -- Compute ideal tabs widths + store them into shrink buffer local most_recently_selected_tab = nil local curr_section_n = -1 local found_selected_tab_id = false @@ -8903,6 +9633,9 @@ function ImGui.TabBarLayout(tab_bar) if tab.ID == tab_bar.SelectedTabId then found_selected_tab_id = true end if scroll_to_tab_id == 0 and g.NavJustMovedToId == tab.ID then scroll_to_tab_id = tab.ID end + -- Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar. + -- Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet, + -- and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window. local tab_name = ImGui.TabBarGetTabName(tab_bar, tab) local has_close_button_or_unsaved_marker = bit32.band(tab.Flags, ImGuiTabItemFlags.NoCloseButton) == 0 or bit32.band(tab.Flags, ImGuiTabItemFlags.UnsavedDocument) ~= 0 tab.ContentWidth = (tab.RequestedWidth >= 0.0) and tab.RequestedWidth or ImGui.TabItemCalcSize(tab_name, has_close_button_or_unsaved_marker).x @@ -8916,6 +9649,7 @@ function ImGui.TabBarLayout(tab_bar) section.WidthAfterShrinkMinWidth = section.WidthAfterShrinkMinWidth + ImMin(tab.ContentWidth, shrink_min_width) + ((section_n == curr_section_n) and tab_spacing or 0.0) curr_section_n = section_n + -- Store data so we can build an array sorted by width if we need to shrink tabs down local item = swb.Data[shrink_buffer_indexes[section_n + 1] + 1] shrink_buffer_indexes[section_n + 1] = shrink_buffer_indexes[section_n + 1] + 1 item.Index = tab_n @@ -8924,6 +9658,7 @@ function ImGui.TabBarLayout(tab_bar) tab.Width = ImMax(tab.ContentWidth, 1.0) end + -- Compute total ideal width (used for e.g. auto-resizing a window) local width_all_tabs_after_min_width_shrink = 0.0 tab_bar.WidthAllTabsIdeal = 0.0 for section_n = 1, 3 do @@ -8931,6 +9666,9 @@ function ImGui.TabBarLayout(tab_bar) width_all_tabs_after_min_width_shrink = width_all_tabs_after_min_width_shrink + sections[section_n].WidthAfterShrinkMinWidth + sections[section_n].Spacing end + -- Horizontal scrolling buttons + -- - Important: note that TabBarScrollButtons() will alter BarRect.Max.x. + -- - Selection skips buttons and might cross through sections if there are Tabs in Leading/Trailing sections. local can_scroll = bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyScroll) ~= 0 or bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyMixed) ~= 0 local width_all_tabs_to_use_for_scroll = (bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyScroll) ~= 0) and tab_bar.WidthAllTabs or width_all_tabs_after_min_width_shrink tab_bar.ScrollButtonEnabled = (width_all_tabs_to_use_for_scroll > tab_bar.BarRect:GetWidth() and tabs.Size > 1) @@ -8948,23 +9686,26 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.SelectedTabId end + -- Shrink widths if full tabs don't fit in their allocated space local section_0_w = sections[1].Width + sections[1].Spacing local section_1_w = sections[2].Width + sections[2].Spacing local section_2_w = sections[3].Width + sections[3].Spacing local central_section_is_visible = (section_0_w + section_2_w) < tab_bar.BarRect:GetWidth() local width_excess if central_section_is_visible then - width_excess = ImMax(section_1_w - (tab_bar.BarRect:GetWidth() - section_0_w - section_2_w), 0.0) + width_excess = ImMax(section_1_w - (tab_bar.BarRect:GetWidth() - section_0_w - section_2_w), 0.0) -- Excess used to shrink central section else - width_excess = (section_0_w + section_2_w) - tab_bar.BarRect:GetWidth() + width_excess = (section_0_w + section_2_w) - tab_bar.BarRect:GetWidth() -- Excess used to shrink leading/trailing section end + -- With ImGuiTabBarFlags.FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore local can_shrink = bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyShrink) ~= 0 or bit32.band(tab_bar.Flags, ImGuiTabBarFlags.FittingPolicyMixed) ~= 0 if width_excess >= 1.0 and (can_shrink or not central_section_is_visible) then local shrink_data_count = central_section_is_visible and sections[2].TabCount or (sections[1].TabCount + sections[3].TabCount) local shrink_data_offset = central_section_is_visible and (sections[1].TabCount + sections[3].TabCount) or 0 ImGui.ShrinkWidths(swb.Data, shrink_data_offset + 1, shrink_data_count, width_excess, shrink_min_width) + -- Apply shrunk values into tabs and sections for tab_n = shrink_data_offset, shrink_data_offset + shrink_data_count - 1 do local item = swb.Data[tab_n + 1] local tab = tabs.Data[item.Index + 1] @@ -8998,6 +9739,7 @@ function ImGui.TabBarLayout(tab_bar) section_tab_index = section_tab_index + section.TabCount end + -- If we have lost the selected tab, select the next most recently active one local tab_bar_appearing = (tab_bar.PrevFrameVisible + 1 < g.FrameCount) if found_selected_tab_id == false and not tab_bar_appearing then tab_bar.SelectedTabId = 0 @@ -9007,6 +9749,7 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.SelectedTabId end + -- Lock in visible tab tab_bar.VisibleTabId = tab_bar.SelectedTabId tab_bar.VisibleTabWasSubmitted = false @@ -9016,6 +9759,7 @@ function ImGui.TabBarLayout(tab_bar) scroll_to_tab_id = tab_bar.VisibleTabId end + -- Apply request requests if scroll_to_tab_id ~= 0 then ImGui.TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections) elseif tab_bar.ScrollButtonEnabled and ImGui.IsMouseHoveringRect(tab_bar.BarRect.Min, tab_bar.BarRect.Max, true) and ImGui.IsWindowContentHoverable(g.CurrentWindow) then @@ -9029,9 +9773,12 @@ function ImGui.TabBarLayout(tab_bar) ImGui.SetKeyOwner(wheel_key, tab_bar.ID) end + -- Update scrolling tab_bar.ScrollingAnim = ImGui.TabBarScrollClamp(tab_bar, tab_bar.ScrollingAnim) tab_bar.ScrollingTarget = ImGui.TabBarScrollClamp(tab_bar, tab_bar.ScrollingTarget) if tab_bar.ScrollingAnim ~= tab_bar.ScrollingTarget then + -- Scrolling speed adjust itself so we can always reach our target in 1/3 seconds. + -- Teleport if we are aiming far off the visible line tab_bar.ScrollingSpeed = ImMax(tab_bar.ScrollingSpeed, 70.0 * g.FontSize) tab_bar.ScrollingSpeed = ImMax(tab_bar.ScrollingSpeed, math.abs(tab_bar.ScrollingTarget - tab_bar.ScrollingAnim) / 0.3) local teleport = (tab_bar.PrevFrameVisible + 1 < g.FrameCount) or (tab_bar.ScrollingTargetDistToVisibility > 10.0 * g.FontSize) @@ -9042,12 +9789,14 @@ function ImGui.TabBarLayout(tab_bar) tab_bar.ScrollingRectMinX = tab_bar.BarRect.Min.x + sections[1].Width + sections[1].Spacing tab_bar.ScrollingRectMaxX = tab_bar.BarRect.Max.x - sections[3].Width - sections[2].Spacing + -- Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame) local window = g.CurrentWindow ImVec2_Copy(window.DC.CursorPos, tab_bar.BarRect.Min) ImGui.ItemSize(ImVec2(tab_bar.WidthAllTabs, tab_bar.BarRect:GetHeight()), tab_bar.FramePadding.y) window.DC.IdealMaxPos.x = ImMax(window.DC.IdealMaxPos.x, tab_bar.BarRect.Min.x + tab_bar.WidthAllTabsIdeal) end +-- Dockable windows uses Name/ID in the global namespace. Non-dockable items use the ID stack. function ImGui.TabBarCalcTabID(tab_bar, label, docked_window) if docked_window ~= nil then IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) ~= 0) @@ -9072,6 +9821,7 @@ function ImGui.TabBarFindTabByID(tab_bar, tab_id) return nil end +-- Order = visible order, not submission order! (which is tab.BeginOrder) --- @param order int # 0-based visible order function ImGui.TabBarFindTabByOrder(tab_bar, order) if order < 0 or order >= tab_bar.Tabs.Size then return nil end @@ -9084,6 +9834,7 @@ function ImGui.TabBarGetTabOrder(tab_bar, tab) return i and (i - 1) or -1 end +-- FIXME: See references to #2304 in TODO.txt function ImGui.TabBarFindMostRecentlySelectedTabForActiveWindow(tab_bar) local most_recently_selected_tab = nil for n = 1, tab_bar.Tabs.Size do @@ -9113,22 +9864,25 @@ function ImGui.TabBarGetTabPos(tab_bar, tab) return tab_bar.BarRect.Min + ImVec2(tab.Offset, 0.0) end +-- The purpose of this call is to register tab in advance so we can control their order at the time they appear. +-- Otherwise calling this is unnecessary as tabs are appending as needed by the BeginTabItem() function. function ImGui.TabBarAddTab(tab_bar, tab_flags, window) local g = ImGui.GetCurrentContext() IM_ASSERT(ImGui.TabBarFindTabByID(tab_bar, window.TabId) == nil) - IM_ASSERT(g.CurrentTabBar ~= tab_bar) + IM_ASSERT(g.CurrentTabBar ~= tab_bar) -- Can't work while the tab bar is active as our tab doesn't have an X offset yet, in theory we could/should test something like (tab_bar.CurrFrameVisible < g.FrameCount) but we'd need to solve why triggers the commented early-out assert in BeginTabBarEx() (probably dock node going from implicit to explicit in same frame) if not window.HasCloseButton then - tab_flags = bit32.bor(tab_flags, ImGuiTabItemFlags.NoCloseButton) + tab_flags = bit32.bor(tab_flags, ImGuiTabItemFlags.NoCloseButton) -- Set _NoCloseButton immediately because it will be used for first-frame width calculation. end local new_tab = ImGuiTabItem() new_tab.ID = window.TabId new_tab.Flags = tab_flags - new_tab.LastFrameVisible = tab_bar.CurrFrameVisible + new_tab.LastFrameVisible = tab_bar.CurrFrameVisible -- Required so BeginTabBar() doesn't ditch the tab if new_tab.LastFrameVisible == -1 then new_tab.LastFrameVisible = g.FrameCount - 1 end - new_tab.Window = window + new_tab.Window = window -- Required so tab bar layout can compute the tab width before tab submission tab_bar.Tabs:push_back(new_tab) end +-- The *TabId fields are already set by the docking system _before_ the actual TabItem was created, so we clear them regardless. function ImGui.TabBarRemoveTab(tab_bar, tab_id) local tab = ImGui.TabBarFindTabByID(tab_bar, tab_id) if tab then tab_bar.Tabs:erase(tab_bar.Tabs:find_index(tab)) end @@ -9137,9 +9891,13 @@ function ImGui.TabBarRemoveTab(tab_bar, tab_id) if tab_bar.NextSelectedTabId == tab_id then tab_bar.NextSelectedTabId = 0 end end +-- Called on manual closure attempt function ImGui.TabBarCloseTab(tab_bar, tab) - if bit32.band(tab.Flags, ImGuiTabItemFlags.Button) ~= 0 then return end + if bit32.band(tab.Flags, ImGuiTabItemFlags.Button) ~= 0 then return end -- A button appended with TabItemButton(). + if bit32.band(tab.Flags, bit32.bor(ImGuiTabItemFlags.UnsavedDocument, ImGuiTabItemFlags.NoAssumedClosure)) == 0 then + -- This will remove a frame of lag for selecting another tab on closure. + -- However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure tab.WantClose = true if tab_bar.VisibleTabId == tab.ID then tab.LastFrameVisible = -1 @@ -9147,6 +9905,7 @@ function ImGui.TabBarCloseTab(tab_bar, tab) tab_bar.NextSelectedTabId = 0 end else + -- Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup) if tab_bar.VisibleTabId ~= tab.ID then ImGui.TabBarQueueFocus(tab_bar, tab) end end end @@ -9156,10 +9915,13 @@ function ImGui.TabBarScrollClamp(tab_bar, scrolling) return ImMax(scrolling, 0.0) end +-- Note: we may scroll to tab that are not selected! e.g. using keyboard arrow keys function ImGui.TabBarScrollToTab(tab_bar, tab_id, sections) local tab = ImGui.TabBarFindTabByID(tab_bar, tab_id) if tab == nil then return end + -- Clamp attempt to scroll to leading/trailing sections items. + -- This could be done at the TabBarScrollingButtons() call site as well, but here works. if bit32.band(tab.Flags, ImGuiTabItemFlags.Leading) ~= 0 then tab = tab_bar.Tabs.Data[sections[1].TabCount + 1] elseif bit32.band(tab.Flags, ImGuiTabItemFlags.Trailing) ~= 0 then @@ -9167,18 +9929,25 @@ function ImGui.TabBarScrollToTab(tab_bar, tab_id, sections) end if tab == nil or bit32.band(tab.Flags, ImGuiTabItemFlags.SectionMask_) ~= 0 then return end + -- When scrolling to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) + -- Disable the margin if the scrolling section is too small for the target tab: prefer displaying a maximum of the label. local g = ImGui.GetCurrentContext() local margin = ImClamp(tab_bar.ScrollingRectMaxX - tab_bar.ScrollingRectMinX - tab.Width, g.Style.ItemInnerSpacing.x, g.FontSize * 1.0) local order = ImGui.TabBarGetTabOrder(tab_bar, tab) + + -- Scrolling happens only in the central section (leading/trailing sections are not scrolling) local scrollable_width = TabBarCalcScrollableWidth(tab_bar, sections) + -- We make all tabs positions all relative Sections[0].Width to make code simpler local tab_x1 = tab.Offset - sections[1].Width + ((order > sections[1].TabCount - 1) and -margin or 0.0) local tab_x2 = tab.Offset - sections[1].Width + tab.Width + ((order + 1 < tab_bar.Tabs.Size - sections[3].TabCount) and margin or 1.0) tab_bar.ScrollingTargetDistToVisibility = 0.0 if tab_bar.ScrollingTarget > tab_x1 or (tab_x2 - tab_x1 >= scrollable_width) then + -- Scroll to the left tab_bar.ScrollingTargetDistToVisibility = ImMax(tab_bar.ScrollingAnim - tab_x2, 0.0) tab_bar.ScrollingTarget = tab_x1 elseif tab_bar.ScrollingTarget < tab_x2 - scrollable_width then + -- Scroll to the right tab_bar.ScrollingTargetDistToVisibility = ImMax((tab_x1 - scrollable_width) - tab_bar.ScrollingAnim, 0.0) tab_bar.ScrollingTarget = tab_x2 - scrollable_width end @@ -9187,7 +9956,7 @@ end --- TabBarQueueFocus(tab_bar, tab) or TabBarQueueFocus(tab_bar, tab_name) function ImGui.TabBarQueueFocus(tab_bar, tab) if type(tab) == "string" then - IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0) + IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) == 0) -- Only supported for manual/explicit tab bars tab_bar.NextSelectedTabId = ImGui.TabBarCalcTabID(tab_bar, tab, nil) return end @@ -9210,17 +9979,22 @@ function ImGui.TabBarQueueReorderFromMousePos(tab_bar, src_tab, mouse_pos) local is_central_section = bit32.band(src_tab.Flags, ImGuiTabItemFlags.SectionMask_) == 0 local bar_offset = tab_bar.BarRect.Min.x - (is_central_section and tab_bar.ScrollingTarget or 0) + -- Count number of contiguous tabs we are crossing over local dir = ((bar_offset + src_tab.Offset) > mouse_pos.x) and -1 or 1 local src_idx = ImGui.TabBarGetTabOrder(tab_bar, src_tab) local dst_idx = src_idx local i = src_idx while i >= 0 and i < tab_bar.Tabs.Size do + -- Reordered tabs must share the same section local dst_tab = tab_bar.Tabs.Data[i + 1] if bit32.band(dst_tab.Flags, ImGuiTabItemFlags.NoReorder) ~= 0 then break end if bit32.band(dst_tab.Flags, ImGuiTabItemFlags.SectionMask_) ~= bit32.band(src_tab.Flags, ImGuiTabItemFlags.SectionMask_) then break end dst_idx = i + + -- Include spacing after tab, so when mouse cursor is between tabs we would not continue checking further tabs that are not hovered. local x1 = bar_offset + dst_tab.Offset - tab_spacing local x2 = bar_offset + dst_tab.Offset + dst_tab.Width + tab_spacing + -- ImGui.GetForegroundDrawList():AddRect(ImVec2(x1, tab_bar.BarRect.Min.y), ImVec2(x2, tab_bar.BarRect.Max.y), IM_COL32(255, 0, 0, 255)) if (dir < 0 and mouse_pos.x > x1) or (dir > 0 and mouse_pos.x < x2) then break end i = i + dir end @@ -9234,10 +10008,13 @@ function ImGui.TabBarProcessReorder(tab_bar) local tab1 = ImGui.TabBarFindTabByID(tab_bar, tab_bar.ReorderRequestTabId) if tab1 == nil or bit32.band(tab1.Flags, ImGuiTabItemFlags.NoReorder) ~= 0 then return false end + -- IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.Reorderable) ~= 0) -- <- this may happen when using debug tools local tab1_order = ImGui.TabBarGetTabOrder(tab_bar, tab1) local tab2_order = tab1_order + tab_bar.ReorderRequestOffset if tab2_order < 0 or tab2_order >= tab_bar.Tabs.Size then return false end + -- Reordered tabs must share the same section + -- (Note: TabBarQueueReorderFromMousePos() also has a similar test but since we allow direct calls to TabBarQueueReorder() we do it here too) local tab2 = tab_bar.Tabs.Data[tab2_order + 1] if bit32.band(tab2.Flags, ImGuiTabItemFlags.NoReorder) ~= 0 then return false end if bit32.band(tab1.Flags, ImGuiTabItemFlags.SectionMask_) ~= bit32.band(tab2.Flags, ImGuiTabItemFlags.SectionMask_) then return false end @@ -9258,6 +10035,7 @@ function ImGui.TabBarScrollingButtons(tab_bar) local scrolling_buttons_width = arrow_button_size.x * 2.0 local backup_cursor_pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y) + -- window.DrawList:AddRect(ImVec2(tab_bar.BarRect.Max.x - scrolling_buttons_width, tab_bar.BarRect.Min.y), ImVec2(tab_bar.BarRect.Max.x, tab_bar.BarRect.Max.y), IM_COL32(255,0,0,255)) local select_dir = 0 local tc = g.Style.Colors[ImGuiCol.Text] @@ -9286,9 +10064,15 @@ function ImGui.TabBarScrollingButtons(tab_bar) if tab_item then local selected_order = ImGui.TabBarGetTabOrder(tab_bar, tab_item) local target_order = selected_order + select_dir + + -- Skip tab item buttons until another tab item is found or end is reached while tab_to_scroll_to == nil do + -- If we are at the end of the list, still scroll to make our tab visible local idx = (target_order >= 0 and target_order < tab_bar.Tabs.Size) and target_order or selected_order tab_to_scroll_to = tab_bar.Tabs.Data[idx + 1] + + -- Cross through buttons + -- (even if first/last item is a button, return it so we can update the scroll) if bit32.band(tab_to_scroll_to.Flags, ImGuiTabItemFlags.Button) ~= 0 then target_order = target_order + select_dir selected_order = selected_order + select_dir @@ -9307,6 +10091,7 @@ function ImGui.TabBarTabListPopupButton(tab_bar) local g = ImGui.GetCurrentContext() local window = g.CurrentWindow + -- We use g.Style.FramePadding.y to match the square ArrowButton size local tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y local backup_cursor_pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y) ImVec2_CopyV(window.DC.CursorPos, tab_bar.BarRect.Min.x - g.Style.FramePadding.y, tab_bar.BarRect.Min.y) @@ -9336,9 +10121,18 @@ function ImGui.TabBarTabListPopupButton(tab_bar) return tab_to_select end ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- -- [SECTION] Widgets: BeginTabItem, EndTabItem, etc. ---------------------------------------------------------------------------------------- +------------------------------------------------------------------------------- +-- - BeginTabItem() +-- - EndTabItem() +-- - TabItemButton() +-- - TabItemEx() [Internal] +-- - SetTabItemClosed() +-- - TabItemCalcSize() [Internal] +-- - TabItemBackground() [Internal] +-- - TabItemLabelAndCloseButton() [Internal] +------------------------------------------------------------------------------- --- @return bool visible, bool? p_open function ImGui.BeginTabItem(label, p_open, flags) @@ -9349,13 +10143,13 @@ function ImGui.BeginTabItem(label, p_open, flags) local tab_bar = g.CurrentTabBar IM_ASSERT(tab_bar ~= nil, "Needs to be called between BeginTabBar() and EndTabBar()!") - IM_ASSERT(bit32.band(flags, ImGuiTabItemFlags.Button) == 0) + IM_ASSERT(bit32.band(flags, ImGuiTabItemFlags.Button) == 0) -- BeginTabItem() Can't be used with button flags, use TabItemButton() instead! local ret ret, p_open = ImGui.TabItemEx(tab_bar, label, p_open, flags, nil) if ret and bit32.band(flags, ImGuiTabItemFlags.NoPushId) == 0 then local tab = tab_bar.Tabs.Data[tab_bar.LastTabItemIdx + 1] - ImGui.PushOverrideID(tab.ID) + ImGui.PushOverrideID(tab.ID) -- We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label) end return ret, p_open end @@ -9396,6 +10190,7 @@ end --- @return bool ret, bool? p_open function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) + -- Layout whole tab bar if not already done local g = ImGui.GetCurrentContext() if tab_bar.WantLayout then local backup_next_item_data = {} @@ -9409,14 +10204,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) local style = g.Style local id = ImGui.TabBarCalcTabID(tab_bar, label, docked_window) + -- If the user called us with p_open == false, we early out and don't render. + -- We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. if p_open ~= nil and not p_open then ImGui.ItemAdd(ImRect(), id, nil, ImGuiItemFlags.NoNav) return false, p_open end IM_ASSERT(p_open == nil or bit32.band(flags, ImGuiTabItemFlags.Button) == 0) - IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) ~= bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) + IM_ASSERT(bit32.band(flags, bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) ~= bit32.bor(ImGuiTabItemFlags.Leading, ImGuiTabItemFlags.Trailing)) -- Can't use both Leading and Trailing + -- Store into ImGuiTabItemFlags.NoCloseButton, also honor ImGuiTabItemFlags.NoCloseButton passed by user (although not documented) local has_p_open = (p_open ~= nil) if bit32.band(flags, ImGuiTabItemFlags.NoCloseButton) ~= 0 then has_p_open = false @@ -9424,6 +10222,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) flags = bit32.bor(flags, ImGuiTabItemFlags.NoCloseButton) end + -- Acquire tab data local tab = ImGui.TabBarFindTabByID(tab_bar, id) local tab_is_new = false if tab == nil then @@ -9435,6 +10234,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end tab_bar.LastTabItemIdx = ImGui.TabBarGetTabOrder(tab_bar, tab) + -- Calculate tab contents size local size = ImGui.TabItemCalcSize(label, has_p_open or bit32.band(flags, ImGuiTabItemFlags.UnsavedDocument) ~= 0) tab.RequestedWidth = -1.0 if bit32.band(g.NextItemData.HasFlags, ImGuiNextItemDataFlags.HasWidth) ~= 0 then @@ -9455,6 +10255,8 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) tab.Flags = flags tab.Window = docked_window + -- Append name (port: stored on tab.Name) + -- (regular tabs are permitted in a DockNode tab bar, but window tabs not permitted in a non-DockNode tab bar) if docked_window ~= nil then IM_ASSERT(bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DockNode) ~= 0) tab.NameOffset = -1 @@ -9464,26 +10266,32 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) tab.Name = label end + -- Update selected tab if not is_tab_button then if tab_appearing and bit32.band(tab_bar.Flags, ImGuiTabBarFlags.AutoSelectNewTabs) ~= 0 and tab_bar.NextSelectedTabId == 0 then if not tab_bar_appearing or tab_bar.SelectedTabId == 0 then - ImGui.TabBarQueueFocus(tab_bar, tab) + ImGui.TabBarQueueFocus(tab_bar, tab) -- New tabs gets activated end end - if bit32.band(flags, ImGuiTabItemFlags.SetSelected) ~= 0 and tab_bar.SelectedTabId ~= id then + if bit32.band(flags, ImGuiTabItemFlags.SetSelected) ~= 0 and tab_bar.SelectedTabId ~= id then -- _SetSelected can only be passed on explicit tab bar ImGui.TabBarQueueFocus(tab_bar, tab) end end + -- Lock visibility + -- (Note: tab_contents_visible ~= tab_selected... because Ctrl+Tab operations may preview some tabs without selecting them!) local tab_contents_visible = (tab_bar.VisibleTabId == id) if tab_contents_visible then tab_bar.VisibleTabWasSubmitted = true end + -- On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches if not tab_contents_visible and tab_bar.SelectedTabId == 0 and tab_bar_appearing and docked_window == nil then if tab_bar.Tabs.Size == 1 and bit32.band(tab_bar.Flags, ImGuiTabBarFlags.AutoSelectNewTabs) == 0 then tab_contents_visible = true end end + -- Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted + -- and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'. if tab_appearing and (not tab_bar_appearing or tab_is_new) then ImGui.ItemAdd(ImRect(), id, nil, ImGuiItemFlags.NoNav) if is_tab_button then return false, p_open end @@ -9492,14 +10300,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) if tab_bar.SelectedTabId == id then tab.LastFrameSelected = g.FrameCount end + -- Backup current layout position local backup_main_cursor_pos = ImVec2(window.DC.CursorPos.x, window.DC.CursorPos.y) + -- Layout local is_central_section = bit32.band(tab.Flags, ImGuiTabItemFlags.SectionMask_) == 0 size.x = tab.Width local pos = ImGui.TabBarGetTabPos(tab_bar, tab) ImVec2_Copy(window.DC.CursorPos, pos) local bb = ImRect(pos, pos + size) + -- We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) local want_clip_rect = is_central_section and (bb.Min.x < tab_bar.ScrollingRectMinX or bb.Max.x > tab_bar.ScrollingRectMaxX) if want_clip_rect then ImGui.PushClipRect(ImVec2(ImClamp(bb.Min.x, tab_bar.ScrollingRectMinX, tab_bar.ScrollingRectMaxX), bb.Min.y - 1), ImVec2(tab_bar.ScrollingRectMaxX, bb.Max.y), true) @@ -9515,8 +10326,9 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) return tab_contents_visible, p_open end + -- Click to Select a tab local button_flags = bit32.bor(is_tab_button and ImGuiButtonFlags.PressedOnClickRelease or ImGuiButtonFlags.PressedOnClick, ImGuiButtonFlags.AllowOverlap) - if g.DragDropActive and not ImGuiPayload_IsDataType(g.DragDropPayload, IMGUI_PAYLOAD_TYPE_WINDOW) then + if g.DragDropActive and not ImGuiPayload_IsDataType(g.DragDropPayload, IMGUI_PAYLOAD_TYPE_WINDOW) then -- FIXME: May be an opt-in property of the payload to disable this button_flags = bit32.bor(button_flags, ImGuiButtonFlags.PressedOnDragDropHold) end local hovered, held, pressed @@ -9527,18 +10339,24 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end if pressed and not is_tab_button then ImGui.TabBarQueueFocus(tab_bar, tab) end + -- Transfer active id window so the active id is not owned by the dock host (as StartMouseMovingWindow() + -- will only do it on the drag). This allows FocusWindow() to be more conservative in how it clears active id. if held and docked_window and g.ActiveId == id and g.ActiveIdIsJustActivated then g.ActiveIdWindow = docked_window end + -- Drag and drop a single floating window node moves it local node = docked_window and docked_window.DockNode or nil local single_floating_window_node = node and node:IsFloatingNode() and (node.Windows.Size == 1) if held and single_floating_window_node and ImGui.IsMouseDragging(0, 0.0) then + -- Move ImGui.StartMouseMovingWindow(docked_window) elseif held and not tab_appearing and ImGui.IsMouseDragging(0) then + -- Drag and drop: re-order tabs local drag_dir = 0 local drag_distance_from_edge_x = 0.0 if not g.DragDropActive and (bit32.band(tab_bar.Flags, ImGuiTabBarFlags.Reorderable) ~= 0 or docked_window ~= nil) then + -- While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x if g.IO.MouseDelta.x < 0.0 and g.IO.MousePos.x < bb.Min.x then drag_dir = -1 drag_distance_from_edge_x = bb.Min.x - g.IO.MousePos.x @@ -9550,13 +10368,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end end + -- Extract a Dockable window out of it's tab bar local can_undock = docked_window ~= nil and bit32.band(docked_window.Flags, ImGuiWindowFlags.NoMove) == 0 and bit32.band(node.MergedFlags, ImGuiDockNodeFlags.NoUndocking) == 0 if can_undock then + -- We use a variable threshold to distinguish dragging tabs within a tab bar and extracting them out of the tab bar local undocking_tab = (g.DragDropActive and g.DragDropPayload.SourceId == id) - if not undocking_tab then + if not undocking_tab then -- and (not g.IO.ConfigDockingWithShift or g.IO.KeyShift) local threshold_base = g.FontSize local threshold_x = threshold_base * 2.2 local threshold_y = (threshold_base * 1.5) + ImClamp((math.abs(g.IO.MouseDragMaxDistanceAbs[0].x) - threshold_base * 2.0) * 0.20, 0.0, threshold_base * 4.0) + -- ImGui.GetForegroundDrawList():AddRect(ImVec2(bb.Min.x - threshold_x, bb.Min.y - threshold_y), ImVec2(bb.Max.x + threshold_x, bb.Max.y + threshold_y), IM_COL32_WHITE) -- [DEBUG] + local distance_from_edge_y = ImMax(bb.Min.y - g.IO.MousePos.y, g.IO.MousePos.y - bb.Max.y) if distance_from_edge_y >= threshold_y then undocking_tab = true end if drag_distance_from_edge_x > threshold_x then @@ -9567,6 +10389,8 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end if undocking_tab then + -- Undock + -- FIXME: refactor to share more code with e.g. StartMouseMovingWindow ImGui.DockContextQueueUndockWindow(g, docked_window) g.MovingWindow = docked_window ImGui.SetActiveID(g.MovingWindow.MoveId, g.MovingWindow) @@ -9577,6 +10401,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end end + -- Render tab shape local is_visible = bit32.band(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.Visible) ~= 0 and bit32.band(flags, ImGuiTabItemFlags.Invisible) == 0 if is_visible then local display_draw_list = window.DrawList @@ -9586,6 +10411,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) else col_idx = tab_bar_focused and ImGuiCol.Tab or ImGuiCol.TabDimmed end ImGui.TabItemBackground(display_draw_list, bb, flags, ImGui.GetColorU32(col_idx)) if tab_contents_visible and bit32.band(tab_bar.Flags, ImGuiTabBarFlags.DrawSelectedOverline) ~= 0 and style.TabBarOverlineSize > 0.0 then + -- Might be moved to TabItemBackground() ? local tl = ImVec2(bb.Min.x, bb.Min.y + style.TabBarOverlineSize * 0.5) local tr = ImVec2(bb.Max.x, bb.Min.y + style.TabBarOverlineSize * 0.5) local overline_col = ImGui.GetColorU32(tab_bar_focused and ImGuiCol.TabSelectedOverline or ImGuiCol.TabDimmedSelectedOverline) @@ -9600,6 +10426,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end ImGui.RenderNavCursor(bb, id) + -- Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. local hovered_unblocked = ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByPopup) if tab_bar.SelectedTabId ~= tab.ID and hovered_unblocked and (ImGui.IsMouseClicked(1) or ImGui.IsMouseReleased(1)) and not is_tab_button then ImGui.TabBarQueueFocus(tab_bar, tab) @@ -9609,6 +10436,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) flags = bit32.bor(flags, ImGuiTabItemFlags.NoCloseWithMiddleMouseButton) end + -- Render tab label, process close button local close_button_id = has_p_open and ImGui.GetIDWithSeed("#CLOSE", nil, docked_window and docked_window.ID or id) or 0 local label_flags = tab_just_unsaved and bit32.band(flags, bit32.bnot(ImGuiTabItemFlags.UnsavedDocument)) or flags local just_closed, text_clipped = ImGui.TabItemLabelAndCloseButton(display_draw_list, bb, label_flags, tab_bar.FramePadding, label, id, close_button_id, tab_contents_visible) @@ -9617,10 +10445,17 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) ImGui.TabBarCloseTab(tab_bar, tab) end + -- 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 and (hovered or g.HoveredId == close_button_id) then g.LastItemData.StatusFlags = bit32.bor(g.LastItemData.StatusFlags, ImGuiItemStatusFlags.HoveredWindow) end + -- 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 and g.HoveredId == id and not held then if bit32.band(tab_bar.Flags, ImGuiTabBarFlags.NoTooltip) == 0 and bit32.band(tab.Flags, ImGuiTabItemFlags.NoTooltip) == 0 then local label_end = ImGui.FindRenderedTextEnd(label) @@ -9629,6 +10464,7 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) end end + -- Restore main window position so user can draw there if want_clip_rect then ImGui.PopClipRect() end ImVec2_Copy(window.DC.CursorPos, backup_main_cursor_pos) @@ -9636,6 +10472,9 @@ function ImGui.TabItemEx(tab_bar, label, p_open, flags, docked_window) return tab_contents_visible, p_open end +-- [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. +-- To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar(). +-- Tabs closed by the close button will automatically be flagged to avoid this issue. function ImGui.SetTabItemClosed(label) local g = ImGui.GetCurrentContext() local is_within_manual_tab_bar = g.CurrentTabBar and bit32.band(g.CurrentTabBar.Flags, ImGuiTabBarFlags.DockNode) == 0 @@ -9643,7 +10482,7 @@ function ImGui.SetTabItemClosed(label) local tab_bar = g.CurrentTabBar local tab_id = ImGui.TabBarCalcTabID(tab_bar, label, nil) local tab = ImGui.TabBarFindTabByID(tab_bar, tab_id) - if tab then tab.WantClose = true end + if tab then tab.WantClose = true end -- Will be processed by next call to TabBarLayout() else local window = ImGui.FindWindowByName(label) if window and window.DockIsActive then @@ -9667,7 +10506,7 @@ function ImGui.TabItemCalcSize(label, has_close_button_or_unsaved_marker) local label_size = ImGui.CalcTextSize(label, nil, true) local size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0) if has_close_button_or_unsaved_marker then - size.x = size.x + g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize) + size.x = size.x + g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize) -- We use Y intentionally to fit the close button circle. else size.x = size.x + g.Style.FramePadding.x + 1.0 end @@ -9675,11 +10514,12 @@ function ImGui.TabItemCalcSize(label, has_close_button_or_unsaved_marker) end function ImGui.TabItemBackground(draw_list, bb, flags, col) + -- While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it. local g = ImGui.GetCurrentContext() local width = bb:GetWidth() IM_ASSERT(width > 0.0) local rounding = ImMax(0.0, ImMin(bit32.band(flags, ImGuiTabItemFlags.Button) ~= 0 and g.Style.FrameRounding or g.Style.TabRounding, width * 0.5 - 1.0)) - local y1 = bb.Min.y + 1.0 + local y1 = bb.Min.y + 1.0 -- Leave a bit of room in title bars. local y2 = bb.Max.y - g.Style.TabBarBorderSize draw_list:AddRectFilled(ImVec2(bb.Min.x, y1), ImVec2(bb.Max.x, y2), col, rounding, ImDrawFlags.RoundCornersTop) if g.Style.TabBorderSize > 0.0 then @@ -9691,6 +10531,8 @@ function ImGui.TabItemBackground(draw_list, bb, flags, col) end end +-- Render text label (with custom clipping) + Unsaved Document marker + Close Button logic +-- We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. --- @return bool just_closed, bool text_clipped function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, label, tab_id, close_button_id, is_contents_visible) local g = ImGui.GetCurrentContext() @@ -9699,15 +10541,24 @@ function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, l if bb:GetWidth() <= 1.0 then return false, false end + -- Render text label (with clipping + alpha gradient) + unsaved marker local text_ellipsis_clip_bb = ImRect(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 local 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.0, text_clipped and IM_COL32(255, 0, 0, 255) or IM_COL32(0, 255, 0, 255)) local button_sz = g.FontSize local button_pos = ImVec2(ImMax(bb.Min.x, bb.Max.x - frame_padding.x - button_sz), bb.Min.y + frame_padding.y) + -- Close Button & Unsaved Marker + -- We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap() + -- 'hovered' will be true when hovering the Tab but NOT when hovering the close button + -- 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button + -- 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false local close_button_pressed = false local close_button_visible = false - local is_hovered = g.HoveredId == tab_id or g.HoveredId == close_button_id or g.ActiveId == tab_id or g.ActiveId == close_button_id + local is_hovered = g.HoveredId == tab_id or g.HoveredId == close_button_id or g.ActiveId == tab_id or g.ActiveId == close_button_id -- Any interaction account for this too. if close_button_id ~= 0 then if is_contents_visible then @@ -9717,6 +10568,7 @@ function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, l end end + -- When tabs/document is unsaved, the unsaved marker takes priority over the close button. local unsaved_marker_visible = bit32.band(flags, ImGuiTabItemFlags.UnsavedDocument) ~= 0 and (button_pos.x + button_sz <= bb.Max.x) and (not close_button_visible or not is_hovered) if unsaved_marker_visible then local bullet_pos = button_pos + ImVec2(button_sz, button_sz) * 0.5 @@ -9727,11 +10579,15 @@ function ImGui.TabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, l if ImGui.CloseButton(close_button_id, button_pos) then close_button_pressed = true end ImGuiLastItemData_Copy(g.LastItemData, last_item_backup) + -- Close with middle mouse button if is_hovered and bit32.band(flags, ImGuiTabItemFlags.NoCloseWithMiddleMouseButton) == 0 and ImGui.IsMouseClicked(2) then close_button_pressed = true end end + -- 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.. local ellipsis_max_x = text_ellipsis_clip_bb.Max.x if close_button_visible or unsaved_marker_visible then local visible_without_hover = unsaved_marker_visible or ((is_contents_visible and g.Style.TabCloseButtonMinWidthSelected or g.Style.TabCloseButtonMinWidthUnselected) < 0.0) diff --git a/imstb_rectpack.lua b/imstb_rectpack.lua index 93257f1..6915eb8 100644 --- a/imstb_rectpack.lua +++ b/imstb_rectpack.lua @@ -4,6 +4,63 @@ -- ALL TABLES IN THIS FILE ARE 1-BASED! -- Avoids table creation when possible +-- [DEAR IMGUI] +-- This is a slightly modified version of stb_rect_pack.h 1.01. +-- Grep for [DEAR IMGUI] to find the changes. +-- +-- stb_rect_pack.h - v1.01 - public domain - rectangle packing +-- Sean Barrett 2014 +-- +-- Useful for e.g. packing rectangular textures into an atlas. +-- Does not do rotation. +-- +-- Not necessarily the awesomest packing method, but better than +-- the totally naive one in stb_truetype (which is primarily what +-- this is meant to replace). +-- +-- Has only had a few tests run, may have issues. +-- +-- More docs to come. +-- +-- Uses table.sort and assert (STBRP_SORT and STBRP_ASSERT below). +-- +-- This library currently uses the Skyline Bottom-Left algorithm. +-- +-- Please note: better rectangle packers are welcome! Please +-- implement them to the same API, but with a different init +-- function. +-- +-- Credits +-- +-- Library +-- Sean Barrett +-- Minor features +-- Martins Mozeiko +-- github:IntellectualKitty +-- +-- Bugfixes / warning fixes +-- Jeremy Jaussaud +-- Fabian Giesen +-- +-- Version history: +-- +-- 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section +-- 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles +-- 0.99 (2019-02-07) warning fixes +-- 0.11 (2017-03-03) return packing success/fail result +-- 0.10 (2016-10-25) remove cast-away-const to avoid warnings +-- 0.09 (2016-08-27) fix compiler warnings +-- 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) +-- 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) +-- 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort +-- 0.05: added STBRP_ASSERT to allow replacing assert +-- 0.04: fixed minor bug in STBRP_LARGE_RECTS support +-- 0.01: initial release +-- +-- LICENSE +-- +-- See end of file for license information. + --- The `prev_link` can be stbrp_context or stbrp_node --- @diagnostic disable @@ -13,7 +70,13 @@ local STBRP_SORT = table.sort local STBRP_ASSERT = assert local STBRP__NOTUSED = function(_) end +------------------------------------------------------------------------------- +-- +-- INCLUDE SECTION +-- + local STBRP__MAXVAL = 0x7fffffff +-- Mostly for internal use, but this is the maximum supported coordinate value. --- @enum STBRP_HEURISTIC_Skyline local STBRP_HEURISTIC_Skyline = { @@ -44,12 +107,17 @@ local STBRP__PREV_LINK_TYPE = { --- @nodiscard local function stbrp_rect() return { + -- reserved for your use: id = 0, + + -- input: w = 0, h = 0, + + -- output: x = 0, y = 0, - was_packed = 0 + was_packed = 0 -- non-zero if valid packing } end @@ -92,7 +160,7 @@ local function stbrp_context() active_head = nil, free_head = nil, - extra = {stbrp_node(), stbrp_node()} + extra = {stbrp_node(), stbrp_node()} -- we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2' } end @@ -113,13 +181,14 @@ local function stbrp__findresult() } end --------------------------- --------------------------- ---- ---- IMPLEMENTATION SECTION ---- ---- +------------------------------------------------------------------------------- +-- +-- IMPLEMENTATION SECTION +-- +-- Optionally select which packing heuristic the library should use. Different +-- heuristics will produce better/worse results for different data sets. +-- If you call init again, this will be reset to the default. --- @param context stbrp_context --- @param heuristic int local function stbrp_setup_heuristic(context, heuristic) @@ -131,16 +200,49 @@ local function stbrp_setup_heuristic(context, heuristic) end end +-- Optionally call this function after init but before doing any packing to +-- change the handling of the out-of-temp-memory scenario, described above. +-- If you call init again, this will be reset to the default (false). --- @param context stbrp_context --- @param allow_out_of_mem boolean local function stbrp_setup_allow_out_of_mem(context, allow_out_of_mem) if allow_out_of_mem then + -- if it's ok to run out of memory, then don't bother aligning them; + -- this gives better packing, but may fail due to OOM (even though + -- the rectangles easily fit). @TODO a smarter approach would be to only + -- quantize once we've hit OOM, then we could get rid of this parameter. context.align = 1 else + -- if it's not ok to run out of memory, then quantize the widths + -- so that num_nodes is always enough nodes. + -- + -- I.e. num_nodes * align >= width + -- align >= width / num_nodes + -- align = ceil(width/num_nodes) + context.align = (context.width + context.num_nodes - 1) / context.num_nodes end end +-- Initialize a rectangle packer to: +-- pack a rectangle that is 'width' by 'height' in dimensions +-- using temporary storage provided by the array 'nodes', which is 'num_nodes' long +-- +-- You must call this function every time you start packing into a new target. +-- +-- There is no "shutdown" function. The 'nodes' memory must stay valid for +-- the following stbrp_pack_rects() call (or calls), but can be freed after +-- the call (or calls) finish. +-- +-- Note: to guarantee best results, either: +-- 1. make sure 'num_nodes' >= 'width' +-- or 2. call stbrp_setup_allow_out_of_mem() defined above with 'allow_out_of_mem = true' +-- +-- If you don't do either of the above things, widths will be quantized to multiples +-- of small integers to guarantee the algorithm doesn't run out of temporary storage. +-- +-- If you do #2, then the non-quantized algorithm will be used, but the algorithm +-- may run out of temporary storage and be unable to pack some rectangles. --- @param context stbrp_context --- @param width int --- @param height int @@ -160,6 +262,7 @@ function stbrp_init_target(context, width, height, nodes, num_nodes) context.num_nodes = num_nodes stbrp_setup_allow_out_of_mem(context, false) + -- node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly) context.extra[1].x = 0 context.extra[1].y = 0 context.extra[1].next = context.extra[2] @@ -168,6 +271,8 @@ function stbrp_init_target(context, width, height, nodes, num_nodes) context.extra[2].next = nil end +-- find minimum y position if it starts at x1 +-- Returns (min_y, waste_area) --- @param c stbrp_context --- @param first stbrp_node --- @param x0 int @@ -181,7 +286,7 @@ local function stbrp__skyline_find_min_y(c, first, x0, width) STBRP_ASSERT(first.x <= x0) - STBRP_ASSERT(node.next.x > x0) + STBRP_ASSERT(node.next.x > x0) -- we ended up handling this in the caller for efficiency STBRP_ASSERT(node.x <= x0) @@ -190,14 +295,19 @@ local function stbrp__skyline_find_min_y(c, first, x0, width) local visited_width = 0 while node.x < x1 do if node.y > min_y then + -- raise min_y higher. + -- we've accounted for all waste up to min_y, + -- but we'll now add more waste for everything we've visited waste_area = waste_area + visited_width * (node.y - min_y) min_y = node.y + -- the first time through, visited_width might be reduced if node.x < x0 then visited_width = visited_width + node.next.x - x0 else visited_width = visited_width + node.next.x - node.x end else + -- add waste area local under_width = node.next.x - node.x if under_width + visited_width > width then under_width = width - visited_width @@ -223,10 +333,12 @@ local function stbrp__skyline_find_best_pos(c, width, height) local best_prev_link = nil local best_prev_link_type = nil + -- align to multiple of c.align width = width + c.align - 1 width = width - width % c.align STBRP_ASSERT(width % c.align == 0) + -- if it can't possibly fit, bail immediately if width > c.width or height > c.height then fr.prev_link = nil fr.prev_link_type = nil @@ -242,7 +354,8 @@ local function stbrp__skyline_find_best_pos(c, width, height) while (node.x + width <= c.width) do local y, waste = stbrp__skyline_find_min_y(c, node, node.x, width) - if c.heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight then + if c.heuristic == STBRP_HEURISTIC_Skyline.BL_sortHeight then -- actually just want to test BL + -- bottom left if y < best_y then best_y = y best_prev_link = prev_link @@ -250,7 +363,9 @@ local function stbrp__skyline_find_best_pos(c, width, height) best_x = node.x end else + -- best-fit if y + height <= c.height then + -- can only use it if it first vertically if y < best_y or (y == best_y and waste < best_waste) then best_y = y best_waste = waste @@ -266,12 +381,30 @@ local function stbrp__skyline_find_best_pos(c, width, height) node = node.next end + -- if doing best-fit (BF), we also have to try aligning right edge to each node position + -- + -- e.g, if fitting + -- + -- ____________________ + -- |____________________| + -- + -- into + -- + -- | | + -- | ____________| + -- |____________| + -- + -- then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned + -- + -- This makes BF take about 2x the time + if c.heuristic == STBRP_HEURISTIC_Skyline.BF_sortHeight then local tail = c.active_head local node_scan = c.active_head local prev_link_scan = c local prev_link_scan_type = STBRP__PREV_LINK_TYPE.ACTIVE_HEAD + -- find first node that's admissible while tail and tail.x < width do tail = tail.next end @@ -280,6 +413,7 @@ local function stbrp__skyline_find_best_pos(c, width, height) local xpos = tail.x - width STBRP_ASSERT(xpos >= 0) + -- find the left position that matches this while node_scan.next and node_scan.next.x <= xpos do prev_link_scan = node_scan prev_link_scan_type = STBRP__PREV_LINK_TYPE.NEXT @@ -295,6 +429,7 @@ local function stbrp__skyline_find_best_pos(c, width, height) if y <= best_y then if y < best_y or waste < best_waste or (waste == best_waste and xpos < best_x) then best_x = xpos + -- STBRP_ASSERT(y <= best_y); [DEAR IMGUI] best_y = y best_waste = waste best_prev_link = prev_link_scan @@ -320,19 +455,29 @@ end --- @param height int --- @return stbrp__findresult local function stbrp__skyline_pack_rectangle(context, width, height) + -- find best position according to heuristic local res = stbrp__skyline_find_best_pos(context, width, height) + -- bail if: + -- 1. it failed + -- 2. the best node doesn't fit (we don't always check this) + -- 3. we're out of memory if res.prev_link == nil or res.y + height > context.height or context.free_head == nil then res.prev_link = nil res.prev_link_type = nil return res end + -- on success, create new node local node = context.free_head node.x = res.x node.y = res.y + height context.free_head = node.next + -- insert the new node into the right starting point, and + -- let 'cur' point to the remaining nodes needing to be + -- stitched back in + local cur if res.prev_link_type == STBRP__PREV_LINK_TYPE.ACTIVE_HEAD then cur = res.prev_link.active_head @@ -341,6 +486,7 @@ local function stbrp__skyline_pack_rectangle(context, width, height) end if cur.x < res.x then + -- preserve the existing one, so start testing with the next one local next = cur.next cur.next = node cur = next @@ -352,13 +498,17 @@ local function stbrp__skyline_pack_rectangle(context, width, height) end end + -- from here, traverse cur and free the nodes, until we get to one + -- that shouldn't be freed while cur.next and cur.next.x <= res.x + width do local next = cur.next + -- move the current node to the free list cur.next = context.free_head context.free_head = cur cur = next end + -- stitch the list back in node.next = cur if cur.x < res.x + width then @@ -390,6 +540,29 @@ local function rect_original_order(a, b) return a.was_packed < b.was_packed end +-- Assign packed locations to rectangles. The rectangles are of type +-- 'stbrp_rect' defined above, stored in the array 'rects', and there +-- are 'num_rects' many of them. +-- +-- Rectangles which are successfully packed have the 'was_packed' flag +-- set to a non-zero value and 'x' and 'y' store the minimum location +-- on each axis (i.e. bottom-left in cartesian coordinates, top-left +-- if you imagine y increasing downwards). Rectangles which do not fit +-- have the 'was_packed' flag set to 0. +-- +-- You should not try to access the 'rects' array from another thread +-- while this function is running, as the function temporarily reorders +-- the array while it executes. +-- +-- To pack into another rectangle, you need to call stbrp_init_target +-- again. To continue packing into the same rectangle, you can call +-- this function again. Calling this multiple times with multiple rect +-- arrays will probably produce worse packing results than calling it +-- a single time with the full rectangle array, but the option is +-- available. +-- +-- The function returns 1 if all of the rectangles were successfully +-- packed and 0 otherwise. --- @param context stbrp_context --- @param rects stbrp_rect[] --- @param num_rects int @@ -397,15 +570,17 @@ end local function stbrp_pack_rects(context, rects, num_rects) local all_rects_packed = 1 + -- we use the 'was_packed' field internally to allow sorting/unsorting for i = 1, num_rects do rects[i].was_packed = (i - 1) end + -- sort according to heuristic STBRP_SORT(rects, rect_height_compare) for i = 1, num_rects do if rects[i].w == 0 or rects[i].h == 0 then - rects[i].x = 0 + rects[i].x = 0 -- empty rect needs no space rects[i].y = 0 else local fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h) @@ -419,8 +594,10 @@ local function stbrp_pack_rects(context, rects, num_rects) end end + -- unsort STBRP_SORT(rects, rect_original_order) + -- set was_packed flags and all_rects_packed status for i = 1, num_rects do rects[i].was_packed = (rects[i].x == STBRP__MAXVAL and rects[i].y == STBRP__MAXVAL) and 0 or 1 if rects[i].was_packed == 0 then @@ -428,6 +605,7 @@ local function stbrp_pack_rects(context, rects, num_rects) end end + -- return the all_rects_packed status return all_rects_packed end @@ -441,3 +619,43 @@ return { setup_allow_out_of_mem = stbrp_setup_allow_out_of_mem, setup_heuristic = stbrp_setup_heuristic } + +-- ------------------------------------------------------------------------------ +-- This software is available under 2 licenses -- choose whichever you prefer. +-- ------------------------------------------------------------------------------ +-- ALTERNATIVE A - MIT License +-- Copyright (c) 2017 Sean Barrett +-- Permission is hereby granted, free of charge, to any person obtaining a copy of +-- this software and associated documentation files (the "Software"), to deal in +-- the Software without restriction, including without limitation the rights to +-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +-- of the Software, and to permit persons to whom the Software is furnished to do +-- so, subject to the following conditions: +-- The above copyright notice and this permission notice shall be included in all +-- copies or substantial portions of the Software. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +-- SOFTWARE. +-- ------------------------------------------------------------------------------ +-- ALTERNATIVE B - Public Domain (www.unlicense.org) +-- This is free and unencumbered software released into the public domain. +-- Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +-- software, either in source code form or as a compiled binary, for any purpose, +-- commercial or non-commercial, and by any means. +-- In jurisdictions that recognize copyright laws, the author or authors of this +-- software dedicate any and all copyright interest in the software to the public +-- domain. We make this dedication for the benefit of the public at large and to +-- the detriment of our heirs and successors. We intend this dedication to be an +-- overt act of relinquishment in perpetuity of all present and future rights to +-- this software under copyright law. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +-- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-- ------------------------------------------------------------------------------ diff --git a/imstb_textedit.lua b/imstb_textedit.lua index e7194c6..60d4299 100644 --- a/imstb_textedit.lua +++ b/imstb_textedit.lua @@ -1,6 +1,221 @@ --- Dear ImGui -- This is a Lua port of original `imstb_textedit.h` +-- [DEAR IMGUI] +-- This is a slightly modified version of stb_textedit.h 1.14. +-- Those changes would need to be pushed into nothings/stb: +-- - Fix in stb_textedit_discard_redo (see https://github.com/nothings/stb/issues/321) +-- - Fix in stb_textedit_find_charpos to handle last line (see https://github.com/ocornut/imgui/issues/6000 + #6783) +-- - Added name to struct or it may be forward declared in our code. +-- - Added UTF-8 support (see https://github.com/nothings/stb/issues/188 + https://github.com/ocornut/imgui/pull/7925) +-- - Changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +-- Grep for [DEAR IMGUI] to find some changes. +-- - Also renamed macros used or defined outside of IMSTB_TEXTEDIT_IMPLEMENTATION block from STB_TEXTEDIT_* to IMSTB_TEXTEDIT_* + +-- stb_textedit.h - v1.14 - public domain - Sean Barrett +-- Development of this library was sponsored by RAD Game Tools +-- +-- This C header file implements the guts of a multi-line text-editing +-- widget; you implement display, word-wrapping, and low-level string +-- insertion/deletion, and stb_textedit will map user inputs into +-- insertions & deletions, plus updates to the cursor position, +-- selection state, and undo state. +-- +-- It is intended for use in games and other systems that need to build +-- their own custom widgets and which do not have heavy text-editing +-- requirements (this library is not recommended for use for editing large +-- texts, as its performance does not scale and it has limited undo). +-- +-- Non-trivial behaviors are modelled after Windows text controls. +-- +-- +-- LICENSE +-- +-- See end of file for license information. +-- +-- +-- DEPENDENCIES +-- +-- Uses the C runtime function 'memmove', which you can override +-- by defining IMSTB_TEXTEDIT_memmove before the implementation. +-- (In this port: ImStb.TEXTEDIT_memmove.) +-- +-- +-- VERSION HISTORY +-- +-- !!!! (2025-10-23) changed STB_TEXTEDIT_INSERTCHARS() to return inserted count (instead of 0/1 bool), allowing partial insertion. +-- 1.14 (2021-07-11) page up/down, various fixes +-- 1.13 (2019-02-07) fix bug in undo size management +-- 1.12 (2018-01-29) user can change STB_TEXTEDIT_KEYTYPE, fix redo to avoid crash +-- 1.11 (2017-03-03) fix HOME on last line, dragging off single-line textfield +-- 1.10 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +-- 1.9 (2016-08-27) customizable move-by-word +-- 1.8 (2016-04-02) better keyboard handling when mouse button is down +-- 1.7 (2015-09-13) change y range handling in case baseline is non-0 +-- 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove +-- 1.5 (2014-09-10) add support for secondary keys for OS X +-- 1.4 (2014-08-17) fix signed/unsigned warnings +-- 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary +-- 1.2 (2014-05-27) fix some RAD types that had crept into the new code +-- 1.1 (2013-12-15) move-by-word (requires STB_TEXTEDIT_IS_SPACE ) +-- 1.0 (2012-07-26) improve documentation, initial public release +-- 0.3 (2012-02-24) bugfixes, single-line mode; insert mode +-- 0.2 (2011-11-28) fixes to undo/redo +-- 0.1 (2010-07-08) initial version +-- +-- ADDITIONAL CONTRIBUTORS +-- +-- Ulf Winklemann: move-by-word in 1.1 +-- Fabian Giesen: secondary key inputs in 1.5 +-- Martins Mozeiko: STB_TEXTEDIT_memmove in 1.6 +-- Louis Schnellbach: page up/down in 1.14 +-- +-- Bugfixes: +-- Scott Graham +-- Daniel Keller +-- Omar Cornut +-- Dan Thompson +-- +-- USAGE +-- +-- The basic concept is that you provide a "string" object which +-- behaves like an array of characters. stb_textedit uses indices to +-- refer to positions in the string, implicitly representing positions +-- in the displayed textedit. This is true for both plain text and +-- rich text; even with rich text stb_truetype interacts with your +-- code as if there was an array of all the displayed characters. +-- +-- Symbols you must define for implementation mode (in this port: fields of ImStb, see below): +-- +-- STB_TEXTEDIT_STRING the type of object representing a string being edited, +-- typically this is a wrapper object with other data you need +-- +-- STB_TEXTEDIT_STRINGLEN(obj) the length of the string (ideally O(1)) +-- STB_TEXTEDIT_LAYOUTROW(r,obj,n) returns the results of laying out a line of characters +-- starting from character #n (see discussion below) +-- STB_TEXTEDIT_GETWIDTH(obj,n,i) returns the pixel delta from the xpos of the i'th character +-- to the xpos of the i+1'th char for a line of characters +-- starting at character #n (i.e. accounts for kerning +-- with previous char) +-- STB_TEXTEDIT_GETCHAR(obj,i) returns the i'th character of obj, 1-based in this port +-- STB_TEXTEDIT_NEWLINE the character returned by _GETCHAR() we recognize +-- as manually wordwrapping for end-of-line positioning +-- +-- STB_TEXTEDIT_DELETECHARS(obj,i,n) delete n characters starting at i +-- STB_TEXTEDIT_INSERTCHARS(obj,i,c,c_offset,n) try to insert n characters at i (taken from array c starting at c_offset) +-- returns number of characters actually inserted. [DEAR IMGUI] +-- +-- STB_TEXTEDIT_K_SHIFT a power of two that is or'd in to a keyboard input to represent the shift key +-- +-- STB_TEXTEDIT_K_LEFT keyboard input to move cursor left +-- STB_TEXTEDIT_K_RIGHT keyboard input to move cursor right +-- STB_TEXTEDIT_K_UP keyboard input to move cursor up +-- STB_TEXTEDIT_K_DOWN keyboard input to move cursor down +-- STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page +-- STB_TEXTEDIT_K_PGDOWN keyboard input to move cursor down a page +-- STB_TEXTEDIT_K_LINESTART keyboard input to move cursor to start of line -- e.g. HOME +-- STB_TEXTEDIT_K_LINEEND keyboard input to move cursor to end of line -- e.g. END +-- STB_TEXTEDIT_K_TEXTSTART keyboard input to move cursor to start of text -- e.g. ctrl-HOME +-- STB_TEXTEDIT_K_TEXTEND keyboard input to move cursor to end of text -- e.g. ctrl-END +-- STB_TEXTEDIT_K_DELETE keyboard input to delete selection or character under cursor +-- STB_TEXTEDIT_K_BACKSPACE keyboard input to delete selection or character left of cursor +-- STB_TEXTEDIT_K_UNDO keyboard input to perform undo +-- STB_TEXTEDIT_K_REDO keyboard input to perform redo +-- +-- STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to +-- STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to +-- STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word -- e.g. ctrl-LEFT +-- STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word -- e.g. ctrl-RIGHT +-- +-- 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, +-- i.e. (STB_TEXTEDIT_K_RIGHT|STB_TEXTEDIT_K_SHIFT) should be shifted right-arrow. +-- +-- STB_TEXTEDIT_LAYOUTROW returns information about the shape of one displayed +-- row of characters assuming they start on the i'th character--the width and +-- the height and the number of characters consumed. This allows this library +-- to traverse the entire layout incrementally. You need to compute word-wrapping +-- here. +-- +-- Each textfield keeps its own insert mode state, which is not how normal +-- applications work. To keep an app-wide insert mode, update/copy the +-- "insert_mode" field of STB_TexteditState before/after calling API functions. +-- +-- API (in this port: fields of the table returned by this file) +-- +-- initialize_state(state, is_single_line) +-- +-- click(str, state, x, y) +-- drag(str, state, x, y) +-- cut(str, state) -> bool +-- paste(str, state, text, len) -> bool +-- key(str, state, key) +-- text(str, state, text, text_len) +-- +-- Each of these functions potentially updates the string and updates the +-- state. +-- +-- initialize_state: +-- set the textedit state to a known good default state when initially +-- constructing the textedit. +-- +-- click: +-- call this with the mouse x,y on a mouse down; it will update the cursor +-- and reset the selection start/end to the cursor point. the x,y must +-- be relative to the text widget, with (0,0) being the top left. +-- +-- drag: +-- call this with the mouse x,y on a mouse drag/up; it will update the +-- cursor and the selection end point +-- +-- cut: +-- call this to delete the current selection; returns true if there was +-- one. you should FIRST copy the current selection to the system paste buffer. +-- (To copy, just copy the current selection out of the string yourself.) +-- +-- paste: +-- call this to paste text at the current cursor point or over the current +-- selection if there is one. +-- +-- key: +-- call this for keyboard inputs sent to the textfield. you can use it +-- for "key down" events or for "translated" key events. +-- +-- 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 +-- the STB_TexteditState. +-- +-- +-- Notes: +-- +-- This is designed to be usable in IMGUI, so it allows for the possibility of +-- running in an IMGUI that has NOT cached the multi-line layout. For this +-- reason, it provides an interface that is compatible with computing the +-- layout incrementally--we try to make sure we make as few passes through +-- as possible. (For example, to locate the mouse pointer in the text, we +-- could define functions that return the X and Y positions of characters +-- and binary search Y and then X, but if we're doing dynamic layout this +-- will run the layout algorithm many times, so instead we manually search +-- forward in one pass. Similar logic applies to e.g. up-arrow and +-- down-arrow movement.) +-- +-- If it's run in a widget that *has* cached the layout, then this is less +-- efficient, but it's not horrible on modern computers. But you wouldn't +-- want to edit million-line files with it. + -- ALL TABLES IN THIS FILE ARE 1-BASED! -- Character Indexing: -- idx=n, the n'th char (1-based) @@ -13,6 +228,10 @@ local STB_TEXTEDIT_STRINGLEN = ImStb.TEXTEDIT_STRINGLEN local STB_TEXTEDIT_GETCHAR = ImStb.TEXTEDIT_GETCHAR local STB_TEXTEDIT_GETWIDTH = ImStb.TEXTEDIT_GETWIDTH local STB_TEXTEDIT_LAYOUTROW = ImStb.TEXTEDIT_LAYOUTROW +-- [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. local IMSTB_TEXTEDIT_GETNEXTCHARINDEX = ImStb.TEXTEDIT_GETNEXTCHARINDEX local IMSTB_TEXTEDIT_GETPREVCHARINDEX = ImStb.TEXTEDIT_GETPREVCHARINDEX local STB_TEXTEDIT_MOVEWORDLEFT = ImStb.TEXTEDIT_MOVEWORDLEFT @@ -22,34 +241,35 @@ local STB_TEXTEDIT_MOVELINEEND = ImStb.TEXTEDIT_MOVELINEEND local STB_TEXTEDIT_DELETECHARS = ImStb.TEXTEDIT_DELETECHARS local STB_TEXTEDIT_INSERTCHARS = ImStb.TEXTEDIT_INSERTCHARS -STB_TEXTEDIT_NEWLINE = 10 +STB_TEXTEDIT_NEWLINE = 10 -- the character returned by _GETCHAR() we recognize as manually wordwrapping for end-of-line positioning STB_TEXTEDIT_K_LEFT = 0x200000 -- keyboard input to move cursor left STB_TEXTEDIT_K_RIGHT = 0x200001 -- keyboard input to move cursor right STB_TEXTEDIT_K_UP = 0x200002 -- keyboard input to move cursor up STB_TEXTEDIT_K_DOWN = 0x200003 -- keyboard input to move cursor down -STB_TEXTEDIT_K_LINESTART = 0x200004 -- keyboard input to move cursor to start of line -STB_TEXTEDIT_K_LINEEND = 0x200005 -- keyboard input to move cursor to end of line -STB_TEXTEDIT_K_TEXTSTART = 0x200006 -- keyboard input to move cursor to start of text -STB_TEXTEDIT_K_TEXTEND = 0x200007 -- keyboard input to move cursor to end of text +STB_TEXTEDIT_K_LINESTART = 0x200004 -- keyboard input to move cursor to start of line -- e.g. HOME +STB_TEXTEDIT_K_LINEEND = 0x200005 -- keyboard input to move cursor to end of line -- e.g. END +STB_TEXTEDIT_K_TEXTSTART = 0x200006 -- keyboard input to move cursor to start of text -- e.g. ctrl-HOME +STB_TEXTEDIT_K_TEXTEND = 0x200007 -- keyboard input to move cursor to end of text -- e.g. ctrl-END STB_TEXTEDIT_K_DELETE = 0x200008 -- keyboard input to delete selection or character under cursor STB_TEXTEDIT_K_BACKSPACE = 0x200009 -- keyboard input to delete selection or character left of cursor STB_TEXTEDIT_K_UNDO = 0x20000A -- keyboard input to perform undo STB_TEXTEDIT_K_REDO = 0x20000B -- keyboard input to perform redo -STB_TEXTEDIT_K_WORDLEFT = 0x20000C -- keyboard input to move cursor left one word -STB_TEXTEDIT_K_WORDRIGHT = 0x20000D -- keyboard input to move cursor right one word +STB_TEXTEDIT_K_WORDLEFT = 0x20000C -- keyboard input to move cursor left one word -- e.g. ctrl-LEFT +STB_TEXTEDIT_K_WORDRIGHT = 0x20000D -- keyboard input to move cursor right one word -- e.g. ctrl-RIGHT STB_TEXTEDIT_K_PGUP = 0x20000E -- keyboard input to move cursor up a page STB_TEXTEDIT_K_PGDOWN = 0x20000F -- keyboard input to move cursor down a page -STB_TEXTEDIT_K_SHIFT = 0x400000 +STB_TEXTEDIT_K_SHIFT = 0x400000 -- a power of two that is or'd in to a keyboard input to represent the shift key -IMSTB_TEXTEDIT_UNDOSTATECOUNT = 99 -local IMSTB_TEXTEDIT_UNDOCHARCOUNT = 999 +IMSTB_TEXTEDIT_UNDOSTATECOUNT = 99 -- the number of undo states to allow +local IMSTB_TEXTEDIT_UNDOCHARCOUNT = 999 -- the number of characters to store in the undo buffer local IMSTB_TEXTEDIT_memmove = ImStb.TEXTEDIT_memmove +-- forward declarations local stb_text_undo local stb_text_redo ----------------------------------------------------------------- ----------------------------------------------------------------- +------------------------------------------------------------------------------- +------------------------------------------------------------------------------- --- --- STB_TexteditState --- @@ -72,6 +292,7 @@ local stb_text_redo --- @nodiscard local function StbUndoRecord() return { + -- private data where = 1, insert_length = 0, delete_length = 0, @@ -101,6 +322,7 @@ local function StbUndoState() end return { + -- private data undo_rec = undo_rec, undo_char = undo_char, @@ -131,16 +353,34 @@ end --- @nodiscard function STB_TexteditState() return { - cursor = 0, + --------------------- + -- + -- public data + -- - select_start = 0, + cursor = 0, + -- position of the text cursor within the string + + select_start = 0, -- selection start point select_end = 0, + -- selection start and end point in characters; if equal, no selection. + -- note that start may be less than or greater than end (e.g. when + -- dragging the mouse, start is where the initial click was, and you + -- can drag in either direction) insert_mode = false, + -- each textfield keeps its own insert mode state. to keep an app-wide + -- insert mode, copy this value in/out of the app state row_count_per_page = 0, + -- page size in number of row. + -- this value MUST be set to >0 for pageup or pagedown in multilines documents. - cursor_at_end_of_line = false, + --------------------- + -- + -- private data + -- + cursor_at_end_of_line = false, -- not implemented yet initialized = false, has_preferred_x = false, single_line = false, @@ -148,7 +388,7 @@ function STB_TexteditState() padding2 = 0, padding3 = 0, - preferred_x = 0.0, + preferred_x = 0.0, -- this determines where the cursor up/down tries to seek to along x undostate = StbUndoState() } @@ -159,12 +399,20 @@ local function STB_TEXT_HAS_SELECTION(s) return s.select_start ~= s.select_end end +------------------------------------------------------------------------------- +--- +--- StbTexteditRow +--- +--- Result of layout query, used by stb_textedit to determine where +--- the text in each row is. + +-- result of layout query --- @class StbTexteditRow ---- @field x0 float # starting x location +--- @field x0 float # starting x location, end x location (allows for align=right, etc) --- @field x1 float # end x location --- @field baseline_y_delta float # position of baseline relative to previous row's baseline ---- @field ymin float # height of row above baseline ---- @field ymax float # height of row below baseline +--- @field ymin float # height of row above and below baseline +--- @field ymax float # height of row above and below baseline --- @field num_chars int --- @return StbTexteditRow @@ -196,10 +444,15 @@ end ---------------------------------------- ---------------------------------------- --- ---- Implementation +--- Implementation mode --- --- +------------------------------------------------------------------------------- +--- +--- Mouse input handling +--- + local stb_text_locate_coord do -- only create once, reuse later @@ -351,6 +604,7 @@ end --- --- +-- forward declarations local stb_text_makeundo_insert local stb_text_makeundo_delete local stb_text_makeundo_replace @@ -399,8 +653,8 @@ function stb_textedit_find_charpos(find, str, n, single_line) local z = STB_TEXTEDIT_STRINGLEN(str) local first - -- special case if it's at the end (may not be needed?) if n == z + 1 and single_line then + -- special case if it's at the end (may not be needed?) STB_TEXTEDIT_LAYOUTROW(r, str, 1) find.y = 0 find.first_char = 1 @@ -420,18 +674,18 @@ function stb_textedit_find_charpos(find, str, n, single_line) if n < i + r.num_chars - 1 then break end - if str.LastMoveDirectionLR == ImGuiDir.Right and str.Stb.cursor > 1 and str.Stb.cursor == i + r.num_chars and STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) ~= STB_TEXTEDIT_NEWLINE then -- [IMGUI] Wrapping point handling + if str.LastMoveDirectionLR == ImGuiDir.Right and str.Stb.cursor > 1 and str.Stb.cursor == i + r.num_chars and STB_TEXTEDIT_GETCHAR(str, i + r.num_chars - 1) ~= STB_TEXTEDIT_NEWLINE then -- [DEAR IMGUI] Wrapping point handling break end - if (i - 1) + r.num_chars == z and z > 0 and STB_TEXTEDIT_GETCHAR(str, z) ~= STB_TEXTEDIT_NEWLINE then -- [IMGUI] special handling for last line - break + if (i - 1) + r.num_chars == z and z > 0 and STB_TEXTEDIT_GETCHAR(str, z) ~= STB_TEXTEDIT_NEWLINE then -- [DEAR IMGUI] special handling for last line + break -- [DEAR IMGUI] end prev_start = i i = i + r.num_chars find.y = find.y + r.baseline_y_delta - if i == z + 1 then -- [IMGUI] - r.num_chars = 0 - break + if i == z + 1 then -- [DEAR IMGUI] + r.num_chars = 0 -- [DEAR IMGUI] + break -- [DEAR IMGUI] end end @@ -479,7 +733,7 @@ local function stb_textedit_delete(str, state, where, len) state.has_preferred_x = false end --- delete the selection +-- delete the section --- @param str IMSTB_TEXTEDIT_STRING --- @param state STB_TexteditState local function stb_textedit_delete_selection(str, state) @@ -498,7 +752,7 @@ local function stb_textedit_delete_selection(str, state) end end --- canonicalize the selection so start <= end +-- canoncialize the selection so start <= end --- @param state STB_TexteditState local function stb_textedit_sortselection(state) if state.select_end < state.select_start then @@ -579,7 +833,7 @@ local function stb_textedit_paste_internal(str, state, text, len) end -- API key: process text input --- [IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. +-- [DEAR IMGUI] Added stb_textedit_text(), extracted out and called by stb_textedit_key() for backward compatibility. --- @param str IMSTB_TEXTEDIT_STRING --- @param state STB_TexteditState --- @param text IMSTB_TEXTEDIT_CHARTYPE[] @@ -732,7 +986,7 @@ function stb_textedit_key(str, state, key) break end - -- [IMGUI] + -- [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 then -- break @@ -929,8 +1183,8 @@ end ----------------------------------------------------- --- --- Undo processing ---- OPTIMIZE: the undo/redo buffer should be circular --- +--- @OPTIMIZE: the undo/redo buffer should be circular --- @param state StbUndoState local function stb_textedit_flush_redo(state) @@ -950,7 +1204,7 @@ local function stb_textedit_discard_undo(state) IMSTB_TEXTEDIT_memmove(state.undo_char, 1, state.undo_char, n + 1, state.undo_char_point - 1) for i = 1, state.undo_point do if state.undo_rec[i].char_storage >= 0 then - state.undo_rec[i].char_storage = state.undo_rec[i].char_storage - n -- OPTIMIZE: get rid of char_storage and infer it + state.undo_rec[i].char_storage = state.undo_rec[i].char_storage - n -- @OPTIMIZE: get rid of char_storage and infer it end end end @@ -983,7 +1237,7 @@ local function stb_textedit_discard_redo(state) end -- now move all the redo records towards the end of the buffer; the first one is at 'redo_point' - -- [IMGUI] + -- [DEAR IMGUI] local move_size = IMSTB_TEXTEDIT_UNDOSTATECOUNT - state.redo_point - 1 IMSTB_TEXTEDIT_memmove(state.undo_rec, state.redo_point + 1, state.undo_rec, state.redo_point, move_size) @@ -1129,6 +1383,9 @@ function stb_text_redo(str, state) local u = s.undo_rec[s.undo_point] local r = s.undo_rec[s.redo_point] + -- we KNOW there must be room for the undo record, because the redo record + -- was derived from an undo record + u.delete_length = r.insert_length u.insert_length = r.delete_length u.where = r.where @@ -1137,6 +1394,7 @@ function stb_text_redo(str, state) if r.delete_length > 0 then -- the redo record requires us to delete characters, so the undo record -- needs to store the characters + if s.undo_char_point + u.insert_length > s.redo_char_point then u.insert_length = 0 u.delete_length = 0 @@ -1144,6 +1402,7 @@ function stb_text_redo(str, state) u.char_storage = s.undo_char_point s.undo_char_point = s.undo_char_point + u.insert_length + -- now save the characters for i = 0, u.insert_length - 1 do s.undo_char[u.char_storage + i] = STB_TEXTEDIT_GETCHAR(str, u.where + i) end @@ -1153,6 +1412,7 @@ function stb_text_redo(str, state) end if r.insert_length ~= 0 then + -- easy case: need to insert n characters r.insert_length = STB_TEXTEDIT_INSERTCHARS(str, r.where, s.undo_char, r.char_storage, r.insert_length) s.redo_char_point = s.redo_char_point + r.insert_length end @@ -1199,6 +1459,7 @@ function stb_text_makeundo_replace(str, state, where, old_length, new_length) end end +-- reset the state to default --- @param state STB_TexteditState --- @param is_single_line bool local function stb_textedit_clear_state(state, is_single_line) @@ -1222,7 +1483,7 @@ return { click = stb_textedit_click, drag = stb_textedit_drag, createundo = stb_text_createundo, - initialize_state = stb_textedit_clear_state, + initialize_state = stb_textedit_clear_state, -- API initialize text = stb_textedit_text, key = stb_textedit_key, @@ -1236,3 +1497,43 @@ return { HAS_SELECTION = STB_TEXT_HAS_SELECTION } + +------------------------------------------------------------------------------- +-- This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------- +-- ALTERNATIVE A - MIT License +-- Copyright (c) 2017 Sean Barrett +-- Permission is hereby granted, free of charge, to any person obtaining a copy of +-- this software and associated documentation files (the "Software"), to deal in +-- the Software without restriction, including without limitation the rights to +-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +-- of the Software, and to permit persons to whom the Software is furnished to do +-- so, subject to the following conditions: +-- The above copyright notice and this permission notice shall be included in all +-- copies or substantial portions of the Software. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +-- SOFTWARE. +------------------------------------------------------------------------------- +-- ALTERNATIVE B - Public Domain (www.unlicense.org) +-- This is free and unencumbered software released into the public domain. +-- Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +-- software, either in source code form or as a compiled binary, for any purpose, +-- commercial or non-commercial, and by any means. +-- In jurisdictions that recognize copyright laws, the author or authors of this +-- software dedicate any and all copyright interest in the software to the public +-- domain. We make this dedication for the benefit of the public at large and to +-- the detriment of our heirs and successors. We intend this dedication to be an +-- overt act of relinquishment in perpetuity of all present and future rights to +-- this software under copyright law. +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +-- ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +-- WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------- diff --git a/imstb_truetype.lua b/imstb_truetype.lua index 17c4773..31810a9 100644 --- a/imstb_truetype.lua +++ b/imstb_truetype.lua @@ -1,6 +1,164 @@ --- Dear ImGui -- This is a Lua port of original `imstb_truetype.h` +-- [DEAR IMGUI] +-- This is a slightly modified version of stb_truetype.h 1.26. +-- Mostly fixing for compiler and static analyzer warnings. +-- Grep for [DEAR IMGUI] to find the changes. + +-- stb_truetype.h - v1.26 - public domain +-- authored from 2009-2021 by Sean Barrett / RAD Game Tools +-- +-- ======================================================================= +-- +-- NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES +-- +-- This library does no range checking of the offsets found in the file, +-- meaning an attacker can use it to read arbitrary memory. +-- +-- ======================================================================= +-- +-- This library processes TrueType files: +-- parse files +-- extract glyph metrics +-- extract glyph shapes +-- render glyphs to one-channel bitmaps with antialiasing (box filter) +-- +-- Todo: +-- non-MS cmaps +-- crashproof on bad data +-- hinting? (no longer patented) +-- cleartype-style AA? +-- optimize: build edge-list directly from curves +-- optimize: rasterize directly from curves? +-- +-- ADDITIONAL CONTRIBUTORS +-- +-- Mikko Mononen: compound shape support, more cmap formats +-- Tor Andersson: kerning, subpixel rendering +-- Dougall Johnson: OpenType / Type 2 font handling +-- Daniel Ribeiro Maciel: basic GPOS-based kerning +-- +-- Misc other: +-- Ryan Gordon +-- Simon Glass +-- github:IntellectualKitty +-- Imanol Celaya +-- Daniel Ribeiro Maciel +-- +-- Bug/warning reports/fixes: +-- "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe +-- Cass Everitt Martins Mozeiko github:aloucks +-- stoiko (Haemimont Games) Cap Petschulat github:oyvindjam +-- Brian Hook Omar Cornut github:vassvik +-- Walter van Niftrik Ryan Griege +-- David Gow Peter LaValle +-- David Given Sergey Popov +-- Ivan-Assen Ivanov Giumo X. Clanjor +-- Anthony Pesch Higor Euripedes +-- Johan Duparc Thomas Fields +-- Hou Qiming Derek Vinyard +-- Rob Loach Cort Stratton +-- Kenney Phillis Jr. Brian Costabile +-- Ken Voskuil (kaesve) +-- +-- USAGE +-- +-- "Load" a font file from a memory buffer (you have to keep the buffer loaded) +-- stbtt_InitFont() +-- stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +-- +-- Character advance/positioning +-- stbtt_GetFontVMetrics() +-- +-- Starting with version 1.06, the rasterizer was replaced with a new, +-- faster and generally-more-precise rasterizer. The new rasterizer more +-- accurately measures pixel coverage for anti-aliasing, except in the case +-- where multiple shapes overlap, in which case it overestimates the AA pixel +-- coverage. Thus, anti-aliasing of intersecting shapes may look wrong. +-- (This port only implements the new rasterizer.) +-- +-- ADDITIONAL DOCUMENTATION +-- +-- Some important concepts to understand to use this library: +-- +-- Codepoint +-- Characters are defined by unicode codepoints, e.g. 65 is +-- uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is +-- the hiragana for "ma". +-- +-- Glyph +-- A visual character shape (every codepoint is rendered as +-- some glyph) +-- +-- Glyph index +-- A font-specific integer ID representing a glyph +-- +-- Baseline +-- Glyph shapes are defined relative to a baseline, which is the +-- bottom of uppercase characters. Characters extend both above +-- and below the baseline. +-- +-- Current Point +-- As you draw text to the screen, you keep track of a "current point" +-- which is the origin of each character. The current point's vertical +-- position is the baseline. Even "baked fonts" use this model. +-- +-- Vertical Font Metrics +-- The vertical qualities of the font, used to vertically position +-- and space the characters. See docs for stbtt_GetFontVMetrics. +-- +-- Font Size in Pixels or Points +-- The preferred interface for specifying font sizes in stb_truetype +-- is to specify how tall the font's vertical extent should be in pixels. +-- +-- DETAILED USAGE: +-- +-- Scale: +-- Select how high you want the font to be, in pixels. +-- Call ScaleForPixelHeight to compute a scale factor SF that will be +-- used by all other functions. +-- +-- Current point: +-- Set the current point where the first character will appear. The +-- first character could extend left of the current point; this is font +-- dependent. You can either choose a current point that is the leftmost +-- point and hope, or add some padding, or check the bounding box or +-- left-side-bearing of the first character to be displayed and set +-- the current point based on that. +-- +-- Displaying a character: +-- Compute the bounding box of the character. It will contain signed values +-- relative to . I.e. if it returns x0,y0,x1,y1, +-- then the character should be displayed in the rectangle from +-- to = n then @@ -598,23 +765,25 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.fontstart = fontstart info.cff = stbtt__new_buf(nil, 0) - cmap = stbtt__find_table(data, fontstart, "cmap") - info.loca = stbtt__find_table(data, fontstart, "loca") - info.head = stbtt__find_table(data, fontstart, "head") - info.glyf = stbtt__find_table(data, fontstart, "glyf") - info.hhea = stbtt__find_table(data, fontstart, "hhea") - info.hmtx = stbtt__find_table(data, fontstart, "hmtx") - info.kern = stbtt__find_table(data, fontstart, "kern") - info.gpos = stbtt__find_table(data, fontstart, "GPOS") + cmap = stbtt__find_table(data, fontstart, "cmap") -- required + info.loca = stbtt__find_table(data, fontstart, "loca") -- required + info.head = stbtt__find_table(data, fontstart, "head") -- required + info.glyf = stbtt__find_table(data, fontstart, "glyf") -- required + info.hhea = stbtt__find_table(data, fontstart, "hhea") -- required + info.hmtx = stbtt__find_table(data, fontstart, "hmtx") -- required + info.kern = stbtt__find_table(data, fontstart, "kern") -- not required + info.gpos = stbtt__find_table(data, fontstart, "GPOS") -- not required if (cmap == 0 or info.head == 0 or info.hhea == 0 or info.hmtx == 0) then return false end if info.glyf ~= 0 then + -- required for truetype if info.loca == 0 then return false end else + -- initialization for CFF / Type2 fonts (OTF) local cff = stbtt__find_table(data, fontstart, "CFF ") if cff == 0 then return false @@ -623,14 +792,16 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.fontdicts = stbtt__new_buf(nil, 0) info.fdselect = stbtt__new_buf(nil, 0) - info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- TODO: this should use size from table + -- @TODO this should use size from table (not 512MB) + info.cff = stbtt__new_buf(data, 64 * 1024 * 1024, cff) -- PORT: 64MB here instead of 512MB local b = info.cff -- read the header stbtt__buf_skip(b, 2) - stbtt__buf_seek(b, stbtt__buf_get8(b)) + stbtt__buf_seek(b, stbtt__buf_get8(b)) -- hdrsize - -- TODO: the name INDEX could list multiple fonts, but we just use the first one. + -- @TODO the name INDEX could list multiple fonts, + -- but we just use the first one. stbtt__cff_get_index(b) -- name INDEX local topdictidx = stbtt__cff_get_index(b) local topdict = stbtt__cff_index_get(topdictidx, 0) @@ -643,6 +814,7 @@ local function stbtt_InitFont_internal(info, data, fontstart) local fdselectoff = stbtt__dict_get_ints(topdict, bit32.bor(0x100, 37), 1) info.subrs = stbtt__get_subrs(b, topdict) + -- we only support Type 2 charstrings if cstype[1] ~= 2 then return false end @@ -651,6 +823,7 @@ local function stbtt_InitFont_internal(info, data, fontstart) end if fdarrayoff[1] ~= 0 then + -- looks like a CID font if fdselectoff[1] == 0 then return false end @@ -673,19 +846,26 @@ local function stbtt_InitFont_internal(info, data, fontstart) info.svg = -1 + -- find a cmap encoding table we understand *now* to avoid searching + -- later. (todo: could make this installable) + -- the same regardless of glyph. numTables = ttUSHORT(data, cmap + 2) info.index_map = 0 for i = 0, numTables - 1 do local encoding_record = cmap + 4 + 8 * i + -- find an encoding we understand: local platform_id = ttUSHORT(data, encoding_record) if platform_id == STBTT_PLATFORM_ID.MICROSOFT then local ms_eid = ttUSHORT(data, encoding_record + 2) if ms_eid == STBTT_MS_EID.UNICODE_BMP or ms_eid == STBTT_MS_EID.UNICODE_FULL then + -- MS/Unicode info.index_map = cmap + ttULONG(data, encoding_record + 4) end elseif platform_id == STBTT_PLATFORM_ID.UNICODE then + -- Mac/iOS has these + -- all the encodingIDs are unicode, so we don't bother to check it info.index_map = cmap + ttULONG(data, encoding_record + 4) end end @@ -697,6 +877,11 @@ local function stbtt_InitFont_internal(info, data, fontstart) return true end +-- If you're going to perform multiple operations on the same character +-- and you want a speed-up, call this function with the character you're +-- going to process, then use glyph-based functions instead of the +-- codepoint-based functions. +-- Returns 0 if the character codepoint is not defined in the font. --- @param info stbtt_fontinfo --- @param unicode_codepoint int function stbtt_FindGlyphIndex(info, unicode_codepoint) @@ -704,7 +889,7 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) local index_map = info.index_map local format = ttUSHORT(data, index_map + 0) - if format == 0 then + if format == 0 then -- apple byte encoding local bytes = ttUSHORT(data, index_map + 2) if unicode_codepoint < bytes - 6 then return ttBYTE(data, index_map + 6 + unicode_codepoint) @@ -718,14 +903,15 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) end return 0 elseif format == 2 then - STBTT_assert(false) -- TODO: high-byte mapping for japanese/chinese/korean + STBTT_assert(false) -- @TODO: high-byte mapping for japanese/chinese/korean return 0 - elseif format == 4 then + elseif format == 4 then -- standard mapping for windows fonts: binary search collection of ranges local segcount = bit32.rshift(ttUSHORT(data, index_map + 6), 1) local searchRange = bit32.rshift(ttUSHORT(data, index_map + 8), 1) local entrySelector = ttUSHORT(data, index_map + 10) local rangeShift = bit32.rshift(ttUSHORT(data, index_map + 12), 1) + -- do a binary search of the segments local endCount = index_map + 14 local search = endCount @@ -733,10 +919,13 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) return 0 end + -- they lie from endCount .. endCount + segCount + -- but searchRange is the nearest power of two, so... if unicode_codepoint >= ttUSHORT(data, search + rangeShift * 2) then search = search + rangeShift * 2 end + -- now decrement to bias correctly to find smallest search = search - 2 while entrySelector ~= 0 do searchRange = bit32.rshift(searchRange, 1) @@ -768,8 +957,9 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) local ngroups = ttULONG(data, index_map + 12) local low = 0 local high = ngroups + -- Binary search the right group. while low < high do - local mid = low + bit32.rshift(high - low, 1) + local mid = low + bit32.rshift(high - low, 1) -- rounds down, so low <= mid < high local start_char = ttULONG(data, index_map + 16 + mid * 12) local end_char = ttULONG(data, index_map + 16 + mid * 12 + 4) if unicode_codepoint < start_char then @@ -785,10 +975,10 @@ function stbtt_FindGlyphIndex(info, unicode_codepoint) end end end - return 0 + return 0 -- not found end - -- TODO: + -- @TODO STBTT_assert(false) return 0 end @@ -810,8 +1000,8 @@ end local function stbtt__GetGlyfOffset(info, glyph_index) STBTT_assert(info.cff.size == 0) - if glyph_index >= info.numGlyphs then return -1 end - if info.indexToLocFormat >= 2 then return -1 end + if glyph_index >= info.numGlyphs then return -1 end -- glyph index out of range + if info.indexToLocFormat >= 2 then return -1 end -- unknown index->glyph map format local g1, g2 if info.indexToLocFormat == 0 then @@ -822,9 +1012,10 @@ local function stbtt__GetGlyfOffset(info, glyph_index) g2 = info.glyf + ttULONG(info.data, info.loca + glyph_index * 4 + 4) end - if g1 == g2 then return -1 else return g1 end + if g1 == g2 then return -1 else return g1 end -- if length is 0, return -1 end +-- Gets the bounding box of the visible part of the glyph, in unscaled coordinates --- @return integer, integer?, integer?, integer?, integer? local function stbtt_GetGlyphBox(info, glyph_index) local n, x0, y0, x1, y1 @@ -896,7 +1087,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) local points = (endPtsOfContours + numberOfContours * 2 + 2 + ins) + 1 -- 1-based idx local n = 1 + ttUSHORT(data, endPtsOfContours + numberOfContours * 2 - 2) - local m = n + 2 * numberOfContours + local m = n + 2 * numberOfContours -- a loose bound on how many vertices we might need vertices = {} for i = 1, m do vertices[i] = stbtt_vertex() end @@ -907,7 +1098,11 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) local next_move = 0 local flagcount = 0 - local off = m - n + -- in first pass, we load uninterpreted data into the allocated array + -- above, shifted to the end of the array so we won't overwrite it when + -- we create our final data starting from the front + + local off = m - n -- starting offset for uninterpreted data, regardless of how m ends up being calculated -- first load flags local flags = 0 @@ -934,7 +1129,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) if bit32.band(flags, 2) ~= 0 then local dx = data[points] points = points + 1 - if bit32.band(flags, 16) ~= 0 then + if bit32.band(flags, 16) ~= 0 then -- ??? x = x + dx else x = x - dx @@ -956,7 +1151,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) if bit32.band(flags, 4) ~= 0 then local dy = data[points] points = points + 1 - if bit32.band(flags, 32) ~= 0 then + if bit32.band(flags, 32) ~= 0 then -- ??? y = y + dy else y = y - dy @@ -987,15 +1182,19 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) -- now start the new one start_off = (bit32.band(flags, 1) == 0) if start_off then + -- if we start off with an off-curve point, then when we need to find a point on the curve + -- where we can start, and we need to save some state for when we wraparound. scx = x scy = y if bit32.band(vertices[off + i + 1].type, 1) == 0 then + -- next point is also a curve point, so interpolate an on-point curve sx = bit32.rshift(x + stbtt_int32(vertices[off + i + 1].x), 1) sy = bit32.rshift(y + stbtt_int32(vertices[off + i + 1].y), 1) else + -- otherwise just use the next point as our start point sx = stbtt_int32(vertices[off + i + 1].x) sy = stbtt_int32(vertices[off + i + 1].y) - i = i + 1 + i = i + 1 -- we're using point i+1 as the starting point, so skip it end else sx = x @@ -1007,8 +1206,8 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) next_move = 1 + ttUSHORT(data, endPtsOfContours + j * 2) j = j + 1 else - if bit32.band(flags, 1) == 0 then - if was_off then + if bit32.band(flags, 1) == 0 then -- if it's a curve + if was_off then -- two off-curve control points in a row means interpolate an on-curve midpoint stbtt_setvertex(vertices[num_vertices + 1], STBTT_VTX.CURVE, bit32.rshift(cx + x, 1), bit32.rshift(cy + y, 1), cx, cy) num_vertices = num_vertices + 1 end @@ -1032,6 +1231,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx, sy, scx, scy, cx, cy) elseif numberOfContours < 0 then + -- Compound shapes. local more = 1 local comp = g + 10 num_vertices = 0 @@ -1047,8 +1247,8 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) flags = ttSHORT(data, comp) comp = comp + 2 gidx = ttSHORT(data, comp) comp = comp + 2 - if bit32.band(flags, 2) ~= 0 then - if bit32.band(flags, 1) ~= 0 then + if bit32.band(flags, 2) ~= 0 then -- XY values + if bit32.band(flags, 1) ~= 0 then -- shorts mtx[5] = ttSHORT(data, comp) comp = comp + 2 mtx[6] = ttSHORT(data, comp) comp = comp + 2 else @@ -1056,7 +1256,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) mtx[6] = ttCHAR(data, comp) comp = comp + 1 end else - -- TODO: handle matching point + -- @TODO handle matching point STBTT_assert(false) end @@ -1083,11 +1283,14 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) mtx[4] = ttSHORT(data, comp) / 16384.0 comp = comp + 2 end + -- Find transformation scales. m = STBTT_sqrt(mtx[1] * mtx[1] + mtx[2] * mtx[2]) n = STBTT_sqrt(mtx[3] * mtx[3] + mtx[4] * mtx[4]) + -- Get indexed glyph. comp_num_vertices, comp_verts = stbtt_GetGlyphShape(info, gidx) if comp_num_vertices > 0 then + -- Transform vertices. for i = 1, comp_num_vertices do local v = comp_verts[i] local x = v.x @@ -1100,6 +1303,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) v.cy = stbtt_int16(n * (mtx[2] * x + mtx[4] * y + mtx[6])) end + -- Append vertices. if num_vertices == 0 then -- LUA: No malloc vertices = comp_verts else @@ -1111,6 +1315,7 @@ local function stbtt__GetGlyphShapeTT(info, glyph_index) num_vertices = num_vertices + comp_num_vertices end + -- More components ? more = bit32.band(flags, bit32.lshift(1, 5)) end end @@ -1266,7 +1471,7 @@ local function stbtt__run_charstring(info, glyph_index, c) clear_stack = 1 b0 = stbtt__buf_get8(b) - -- TODO: implement hinting + -- @TODO implement hinting if b0 == 0x13 or b0 == 0x14 then -- hintmask or cntrmask if in_header then maskbits = maskbits + trunc(sp / 2) -- implicit "vstem" @@ -1415,6 +1620,8 @@ local function stbtt__run_charstring(info, glyph_index, c) elseif b0 == 0x0C then -- two-byte escape local b1 = stbtt__buf_get8(b) + -- @TODO These "flex" implementations ignore the flex-depth and resolution, + -- and always draw beziers. if b1 == 0x22 then -- hflex if sp < 7 then return STBTT__CSERR("hflex stack") end local dx1 = s[0] @@ -1547,6 +1754,15 @@ function stbtt__GetGlyphInfoT2(info, glyph_index) return ((r ~= 0) and c.num_vertices or 0), x0, y0, x1, y1 end +-- returns # of vertices and fills *vertices with the pointer to them +-- these are expressed in "unscaled" coordinates +-- +-- The shape is a series of contours. Each one starts with +-- a STBTT_moveto, then consists of a series of mixed +-- STBTT_lineto and STBTT_curveto segments. A lineto +-- draws a line from previous endpoint to its x,y; a curveto +-- draws a quadratic bezier from previous endpoint to +-- its x,y, using cx,cy as the bezier control point. --- @param info stbtt_fontinfo --- @param glyph_index int function stbtt_GetGlyphShape(info, glyph_index) @@ -1557,6 +1773,9 @@ function stbtt_GetGlyphShape(info, glyph_index) end end +-- leftSideBearing is the offset from the current horizontal position to the left edge of the character +-- advanceWidth is the offset from the current horizontal position to the next horizontal position +-- these are expressed in unscaled coordinates --- @param info stbtt_fontinfo --- @param glyph_index int function stbtt_GetGlyphHMetrics(info, glyph_index) @@ -1574,6 +1793,12 @@ function stbtt_GetGlyphHMetrics(info, glyph_index) return advanceWidth, leftSideBearing end +-- ascent is the coordinate above the baseline the font extends; descent +-- is the coordinate below the baseline the font extends (i.e. it is typically negative) +-- lineGap is the spacing between one row's descent and the next row's ascent... +-- so you should advance the vertical position by "ascent - descent + lineGap" +-- these are expressed in unscaled coordinates, so you must multiply by +-- the scale factor for a given size --- @param info stbtt_fontinfo function stbtt_GetFontVMetrics(info) local ascent = ttSHORT(info.data, info.hhea + 4) @@ -1583,6 +1808,12 @@ function stbtt_GetFontVMetrics(info) return ascent, descent, lineGap end +-- computes a scale factor to produce a font whose "height" is 'pixels' tall. +-- Height is measured as the distance from the highest ascender to the lowest +-- descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics +-- and computing: +-- scale = pixels / (ascent - descent) +-- so if you prefer to measure height by the ascent only, use a similar calculation. --- @param info stbtt_fontinfo --- @param height float function stbtt_ScaleForPixelHeight(info, height) @@ -1593,10 +1824,12 @@ end ------------------------------------ ------------------------------------ --- ---- Antialiasing software rasterizer +--- antialiasing software rasterizer --- --- +-- same as stbtt_GetGlyphBitmapBox, but you can specify a subpixel +-- shift for the character --- @param font stbtt_fontinfo --- @param glyph int --- @param scale_x float @@ -1624,6 +1857,11 @@ function stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y, shift_x, return ix0, iy0, ix1, iy1 end +-- get the bbox of the bitmap centered around the glyph origin; so the +-- bitmap width is ix1-ix0, height is iy1-iy0, and location to place +-- the bitmap top left is (leftSideBearing*scale,iy0). +-- (Note that the bitmap uses y-increases-down, but the shape uses +-- y-increases-up, so GlyphBitmapBox and GlyphBox are inverted.) --- @param font stbtt_fontinfo --- @param glyph int --- @param scale_x float @@ -1646,6 +1884,8 @@ end --- stbtt_MakeGlyphBitmap --- stbtt_GetGlyphBitmapSubpixel +-- the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +-- (i.e. it has already been clipped to those) --- @param scanline float[] --- @param x int --- @param e stbtt__active_edge @@ -1687,7 +1927,7 @@ local function stbtt__handle_clipped_edge(scanline, x, e, x0, y0, x1, y1) -- do nothing else STBTT_assert(x0 >= x and x0 <= x + 1 and x1 >= x and x1 <= x + 1) - scanline[x] = scanline[x] + e.direction * (y1 - y0) * (1 - ((x0 - x) + (x1 - x)) / 2) + scanline[x] = scanline[x] + e.direction * (y1 - y0) * (1 - ((x0 - x) + (x1 - x)) / 2) -- coverage = 1 - average x position end end @@ -1725,6 +1965,7 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t while e do -- brute force every pixel + -- compute intersection points with top & bottom STBTT_assert(e.ey >= y_top) @@ -1768,8 +2009,8 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t if x_top >= 0 and x_bottom >= 0 and x_top < len and x_bottom < len then -- from here on, we don't have to range check x values if trunc(x_top) == trunc(x_bottom) then - -- simple case, only spans one pixel local height + -- simple case, only spans one pixel local x = trunc(x_top) height = (sy1 - sy0) * e.direction STBTT_assert(x >= 0 and x < len) @@ -1801,8 +2042,25 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t -- compute intersection with y axis at x2 y_final = y_top + dy * (x2 - x0) + -- x1 x_top x2 x_bottom + -- y_top +------|-----+------------+------------+--------|---+------------+ + -- | | | | | | + -- | | | | | | + -- sy0 | Txxxxx|............|............|............|............| + -- y_crossing | *xxxxx.......|............|............|............| + -- | | xxxxx..|............|............|............| + -- | | /- xx*xxxx........|............|............| + -- | | dy < | xxxxxx..|............|............| + -- y_final | | \- | xx*xxx.........|............| + -- sy1 | | | | xxxxxB...|............| + -- | | | | | | + -- | | | | | | + -- y_bottom +------------+------------+------------+------------+------------+ + -- + -- goal is to measure the area covered by '.' in each pixel + -- if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 - -- TODO: maybe test against sy1 rather than y_bottom? + -- @TODO: maybe test against sy1 rather than y_bottom? if y_crossing > y_bottom then y_crossing = y_bottom end @@ -1824,6 +2082,16 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t end end + -- in second pixel, area covered by line segment found in first pixel + -- is always a rectangle 1 wide * the height of that line segment; this + -- is exactly what the variable 'area' stores. it also gets a contribution + -- from the line segment within it. the THIRD pixel will get the first + -- pixel's rectangle contribution, the second pixel's rectangle contribution, + -- and its own contribution. the 'own contribution' is the same in every pixel except + -- the leftmost and rightmost, a trapezoid that slides down in each pixel. + -- the second pixel's contribution to the third pixel will be the + -- rectangle 1 wide times the height change in the second pixel, which is dy. + step = sign * dy * 1 -- dy is dy/dx, change in y for every 1 change in x, -- which multiplied by 1-pixel-width is how much pixel area changes for each step in x -- so the area advances by 'step' every time @@ -1843,7 +2111,27 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t scanline_fill[x2 + 1] = scanline_fill[x2 + 1] + sign * (sy1 - sy0) end else + -- if edge goes outside of box we're drawing, we require + -- clipping logic. since this does not match the intended use + -- of this library, we use a different, very slow brute + -- force implementation + -- note though that this does happen some of the time because + -- x_top and x_bottom can be extrapolated at the top & bottom of + -- the shape and actually lie outside the bounding box for x = 0, len - 1 do + -- cases: + -- + -- there can be up to two intersections with the pixel. any intersection + -- with left or right edges can be handled by splitting into two (or three) + -- regions. intersections with top & bottom do not necessitate case-wise logic. + -- + -- the old way of doing this found the intersections with the left & right edges, + -- then used some simple logic to produce up to three segments in sorted order + -- from top-to-bottom. however, this had a problem: if an x edge was epsilon + -- across the x border, then the corresponding y position might not be distinct + -- from the other y segment, and it might ignored as an empty segment. to avoid + -- that, we need to explicitly produce segments based on x positions. + -- rename variables to clearly-defined pairs local y0 = y_top local x1 = x @@ -1887,6 +2175,7 @@ local function stbtt__fill_active_edges_new(scanline, scanline_fill, len, e, y_t end end +-- directly AA rasterize edges w/o supersampling --- @param result stbtt__bitmap --- @param e stbtt__edge --- @param n int @@ -1914,28 +2203,33 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of for i = 0, result.w - 1 do scanline[i] = 0 end for i = 0, result.w do scanline2[i] = 0 end + -- update all active edges; + -- remove all active edges that terminate before the top of this scanline local prev = nil local curr = active while curr do local next = curr.next if curr.ey <= scan_y_top then - if prev then prev.next = next + if prev then prev.next = next -- delete from list else active = next end curr.direction = 0 else - prev = curr + prev = curr -- advance through list end curr = next end + -- insert all edges that start before the bottom of this scanline local edge = e[p] while edge.y0 <= scan_y_bottom do if edge.y0 ~= edge.y1 then local z = stbtt__new_active(edge, off_x, scan_y_top) if j == 0 and off_y ~= 0 and z.ey < scan_y_top then + -- this can happen due to subpixel positioning and some kind of fp rounding error i think z.ey = scan_y_top end - STBTT_assert(z.ey >= scan_y_top) + STBTT_assert(z.ey >= scan_y_top) -- if we get really unlucky a tiny bit of an edge can be out of bounds + -- insert at front z.next = active active = z end @@ -1943,6 +2237,7 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of edge = e[p] end + -- now process all active edges if active then stbtt__fill_active_edges_new(scanline, scanline2, result.w, active, scan_y_top) end @@ -1961,10 +2256,11 @@ local function stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, of end end + -- advance all the edges step = active while step do - step.fx = step.fx + step.fdx - step = step.next + step.fx = step.fx + step.fdx -- advance to position for current scanline + step = step.next -- advance through list end y = y + 1 @@ -1999,6 +2295,7 @@ end local function stbtt__rasterize(result, pts, wcount, windings, scale_x, scale_y, shift_x, shift_y, off_x, off_y, invert) local y_scale_inv = (invert) and -scale_y or scale_y local vsubsample = 1 -- STBTT_RASTERIZER_VERSION == 2 + -- vsubsample should divide 255 evenly; otherwise we won't reach full opacity -- now we have to blow out the windings into explicit edge lists local n = 0 @@ -2066,8 +2363,7 @@ local function stbtt__add_point(points, n, x, y) points[n + 1].y = y end --- tessellate until threshold p is happy... --- TODO: warped to compensate for non-linear stretching +-- tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching --- @param points? stbtt__point[] --- @param num_points int --- @param x0 float @@ -2116,7 +2412,7 @@ end --- @param n int --- @return int num_points # updated num_points passed in local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2, x3, y3, objspace_flatness_squared, n) - -- TODO: this "flatness" calculation is just made-up nonsense that seems to work well enough + -- @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough local dx0 = x1 - x0 local dy0 = y1 - y0 local dx1 = x2 - x1 @@ -2159,6 +2455,7 @@ local function stbtt__tesselate_cubic(points, num_points, x0, y0, x1, y1, x2, y2 return num_points end +-- returns number of contours --- @param vertices stbtt_vertex[] --- @param num_verts int --- @param objspace_flatness float @@ -2235,6 +2532,7 @@ local function stbtt_FlattenCurves(vertices, num_verts, objspace_flatness) return points, num_contours, contour_lengths end +-- rasterize a shape with quadratic beziers into a bitmap --- @param result stbtt__bitmap --- @param flatness_in_pixels float --- @param vertices stbtt_vertex[] @@ -2258,6 +2556,11 @@ local function stbtt_Rasterize(result, flatness_in_pixels, vertices, num_verts, end end +-- renders the glyph into storage you pass in for the bitmap, +-- in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap +-- is clipped to out_w/out_h bytes. Call stbtt_GetGlyphBitmapBox to get the +-- width and height and positioning info for it first. You can also specify +-- a subpixel shift for the character. --- @param info stbtt_fontinfo --- @param output unsigned_char[] --- @param out_w int @@ -2286,7 +2589,7 @@ end ----------------- ----------------- --- ---- Bitmap baking +--- bitmap baking --- --- @@ -2298,7 +2601,7 @@ end --------------------------- --------------------------- --- ---- Bitmap baking / packing +--- bitmap baking / packing --- --- @@ -2380,9 +2683,16 @@ local function stbtt__oversample_shift(oversample) if oversample == 0 then return 0.0 end + + -- The prefilter is a box filter of width "oversample", + -- which shifts phase by (oversample - 1)/2 pixels in + -- oversampled space. We want to shift in the opposite + -- direction to counter this. return -(oversample - 1) / (2.0 * oversample) end +-- same as stbtt_MakeGlyphBitmapSubpixel, but prefiltering +-- is performed. Returns (sub_x, sub_y). --- @param info stbtt_fontinfo --- @param output unsigned_char[] --- @param out_w int @@ -2415,7 +2725,7 @@ end ------------------- ------------------- --- ---- SDF computation +--- sdf computation --- --- @@ -2441,10 +2751,20 @@ end --- stbtt__matchpair --- stbtt__matches +-- Each .ttf/.ttc file may have more than one font. Each font has a sequential +-- index number starting from 0. Call this function to get the font offset for +-- a given index; it returns -1 if the index is out of range. A regular .ttf +-- file will only define one font and it always be at offset 0, so it will +-- return '0' for index 0, and -1 for all other indices. --- @param data table --- @param index int function stbtt_GetFontOffsetForIndex(data, index) return stbtt_GetFontOffsetForIndex_internal(data, index) end +-- Given an offset into the file that defines a font, this function builds +-- the necessary cached info for the rest of the system. You must allocate +-- the stbtt_fontinfo yourself (see stbtt_fontinfo()), and stbtt_InitFont will fill it out. You don't +-- need to do anything special to free it, because the contents are pure +-- value data with no additional data structures. Returns false on failure. --- @param info stbtt_fontinfo --- @param data table --- @param offset int