upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/src/imgui/imgui_tables.cpp
diff options
context:
space:
mode:
authorbitflash-coin <bookofshamers@outlook.com>2026-08-04 06:34:32 -0700
committerbitflash-coin <bookofshamers@outlook.com>2026-08-04 06:34:32 -0700
commit5ce650382352c1503f40abf08129ada69402af55 (patch)
tree6a18198901f1e2c4933f1ac53c9365eec512bf63 /src/imgui/imgui_tables.cpp
parentf34113291da7e5e3dc7d2468d4f9c212c05c584b (diff)
public commit
Diffstat (limited to 'src/imgui/imgui_tables.cpp')
-rw-r--r--src/imgui/imgui_tables.cpp4904
1 files changed, 4904 insertions, 0 deletions
diff --git a/src/imgui/imgui_tables.cpp b/src/imgui/imgui_tables.cpp
new file mode 100644
index 0000000..43b5cd5
--- /dev/null
+++ b/src/imgui/imgui_tables.cpp
@@ -0,0 +1,4904 @@
1// dear imgui, v1.92.9
2// (tables and columns code)
3
4/*
5
6Index of this file:
7
8// [SECTION] Commentary
9// [SECTION] Header mess
10// [SECTION] Tables: Main code
11// [SECTION] Tables: Simple accessors
12// [SECTION] Tables: Row changes
13// [SECTION] Tables: Columns changes
14// [SECTION] Tables: Columns width management
15// [SECTION] Tables: Drawing
16// [SECTION] Tables: Sorting
17// [SECTION] Tables: Headers
18// [SECTION] Tables: Context Menu
19// [SECTION] Tables: Settings (.ini data)
20// [SECTION] Tables: Garbage Collection
21// [SECTION] Tables: Debugging
22// [SECTION] Columns, BeginColumns, EndColumns, etc.
23
24*/
25
26// Navigating this file:
27// - In Visual Studio: Ctrl+Comma ("Edit.GoToAll") can follow symbols inside comments, whereas Ctrl+F12 ("Edit.GoToImplementation") cannot.
28// - In Visual Studio w/ Visual Assist installed: Alt+G ("VAssistX.GoToImplementation") can also follow symbols inside comments.
29// - In VS Code, CLion, etc.: Ctrl+Click can follow symbols inside comments.
30
31//-----------------------------------------------------------------------------
32// [SECTION] Commentary
33//-----------------------------------------------------------------------------
34
35//-----------------------------------------------------------------------------
36// Typical tables call flow: (root level is generally public API):
37//-----------------------------------------------------------------------------
38// - BeginTable() user begin into a table
39// | BeginChild() - (if ScrollX/ScrollY is set)
40// | TableBeginInitMemory() - first time table is used
41// | TableResetSettings() - on settings reset
42// | TableLoadSettings() - on settings load
43//-----------------------------------------------------------------------------
44// - TableSetupColumn() user submit columns details (optional)
45// - TableSetupScrollFreeze() user submit scroll freeze information (optional)
46//-----------------------------------------------------------------------------
47// - TableUpdateLayout() [Internal] followup to BeginTable(): setup everything: widths, columns positions, clipping rectangles. Automatically called by the FIRST call to TableNextRow() or TableHeadersRow().
48// | TableApplyQueuedRequests() - apply queued resizing/reordering/hiding requests
49// | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame)
50// | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width
51// | - TableSetColumnDisplayOrder() - apply reordering a column
52// | TableSetupDrawChannels() - setup ImDrawList channels
53// | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission
54// | TableBeginContextMenuPopup()
55// | - TableDrawDefaultContextMenu() - draw right-click context menu contents
56//-----------------------------------------------------------------------------
57// - TableHeadersRow() or TableHeader() user submit a headers row (optional)
58// | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction
59// | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu
60// - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers)
61// - TableNextRow() user begin into a new row (also automatically called by TableHeadersRow())
62// | TableEndRow() - finish existing row
63// | TableBeginRow() - add a new row
64// - TableSetColumnIndex() / TableNextColumn() user begin into a cell
65// | TableEndCell() - close existing column/cell
66// | TableBeginCell() - enter into current column/cell
67// - [...] user emit contents
68//-----------------------------------------------------------------------------
69// - EndTable() user ends the table
70// | TableDrawBorders() - draw outer borders, inner vertical borders
71// | TableMergeDrawChannels() - merge draw channels if clipping isn't required
72// | EndChild() - (if ScrollX/ScrollY is set)
73//-----------------------------------------------------------------------------
74
75//-----------------------------------------------------------------------------
76// TABLE SIZING
77//-----------------------------------------------------------------------------
78// (Read carefully because this is subtle but it does make sense!)
79//-----------------------------------------------------------------------------
80// About 'outer_size':
81// Its meaning needs to differ slightly depending on if we are using ScrollX/ScrollY flags.
82// Default value is ImVec2(0.0f, 0.0f).
83// X
84// - outer_size.x <= 0.0f -> Right-align from window/work-rect right-most edge. With -FLT_MIN or 0.0f will align exactly on right-most edge.
85// - outer_size.x > 0.0f -> Set Fixed width.
86// Y with ScrollX/ScrollY disabled: we output table directly in current window
87// - outer_size.y < 0.0f -> Bottom-align (but will auto extend, unless _NoHostExtendY is set). Not meaningful if parent window can vertically scroll.
88// - outer_size.y = 0.0f -> No minimum height (but will auto extend, unless _NoHostExtendY is set)
89// - outer_size.y > 0.0f -> Set Minimum height (but will auto extend, unless _NoHostExtendY is set)
90// Y with ScrollX/ScrollY enabled: using a child window for scrolling
91// - outer_size.y < 0.0f -> Bottom-align. Not meaningful if parent window can vertically scroll.
92// - outer_size.y = 0.0f -> Bottom-align, consistent with BeginChild(). Not recommended unless table is last item in parent window.
93// - outer_size.y > 0.0f -> Set Exact height. Recommended when using Scrolling on any axis.
94//-----------------------------------------------------------------------------
95// Outer size is also affected by the NoHostExtendX/NoHostExtendY flags.
96// Important to note how the two flags have slightly different behaviors!
97// - 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.
98// - 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.
99// In theory ImGuiTableFlags_NoHostExtendY could be the default and any non-scrolling tables with outer_size.y != 0.0f would use exact height.
100// This would be consistent but perhaps less useful and more confusing (as vertically clipped items are not useful and not easily noticeable).
101//-----------------------------------------------------------------------------
102// About 'inner_width':
103// With ScrollX disabled:
104// - inner_width -> *ignored*
105// With ScrollX enabled:
106// - inner_width < 0.0f -> *illegal* fit in known width (right align from outer_size.x) <-- weird
107// - inner_width = 0.0f -> fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns.
108// - inner_width > 0.0f -> override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space!
109//-----------------------------------------------------------------------------
110// Details:
111// - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept
112// of "available space" doesn't make sense.
113// - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding
114// of what the value does.
115//-----------------------------------------------------------------------------
116
117//-----------------------------------------------------------------------------
118// COLUMNS SIZING POLICIES
119// (Reference: ImGuiTableFlags_SizingXXX flags and ImGuiTableColumnFlags_WidthXXX flags)
120//-----------------------------------------------------------------------------
121// About overriding column sizing policy and width/weight with TableSetupColumn():
122// We use a default parameter of -1 for 'init_width'/'init_weight'.
123// - with ImGuiTableColumnFlags_WidthFixed, init_width <= 0 (default) --> width is automatic
124// - with ImGuiTableColumnFlags_WidthFixed, init_width > 0 (explicit) --> width is custom
125// - with ImGuiTableColumnFlags_WidthStretch, init_weight <= 0 (default) --> weight is 1.0f
126// - with ImGuiTableColumnFlags_WidthStretch, init_weight > 0 (explicit) --> weight is custom
127// Widths are specified _without_ CellPadding. If you specify a width of 100.0f, the column will be cover (100.0f + Padding * 2.0f)
128// and you can fit a 100.0f wide item in it without clipping and with padding honored.
129//-----------------------------------------------------------------------------
130// About default sizing policy (if you don't specify a ImGuiTableColumnFlags_WidthXXXX flag)
131// - with Table policy ImGuiTableFlags_SizingFixedFit --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is equal to contents width
132// - with Table policy ImGuiTableFlags_SizingFixedSame --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is max of all contents width
133// - with Table policy ImGuiTableFlags_SizingStretchSame --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is 1.0f
134// - with Table policy ImGuiTableFlags_SizingStretchWeight --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is proportional to contents
135// Default Width and default Weight can be overridden when calling TableSetupColumn().
136//-----------------------------------------------------------------------------
137// About mixing Fixed/Auto and Stretch columns together:
138// - the typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns.
139// - 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!
140// that is, unless 'inner_width' is passed to BeginTable() to explicitly provide a total width to layout columns in.
141// - when using ImGuiTableFlags_SizingFixedSame with mixed columns, only the Fixed/Auto columns will match their widths to the width of the maximum contents.
142// - when using ImGuiTableFlags_SizingStretchSame with mixed columns, only the Stretch columns will match their weights/widths.
143//-----------------------------------------------------------------------------
144// About using column width:
145// If a column is manually resizable or has a width specified with TableSetupColumn():
146// - you may use GetContentRegionAvail().x to query the width available in a given column.
147// - right-side alignment features such as SetNextItemWidth(-x) or PushItemWidth(-x) will rely on this width.
148// If the column is not resizable and has no width specified with TableSetupColumn():
149// - its width will be automatic and be set to the max of items submitted.
150// - therefore you generally cannot have ALL items of the columns use e.g. SetNextItemWidth(-FLT_MIN).
151// - but if the column has one or more items of known/fixed size, this will become the reference width used by SetNextItemWidth(-FLT_MIN).
152//-----------------------------------------------------------------------------
153
154
155//-----------------------------------------------------------------------------
156// TABLES CLIPPING/CULLING
157//-----------------------------------------------------------------------------
158// About clipping/culling of Rows in Tables:
159// - For large numbers of rows, it is recommended you use ImGuiListClipper to submit only visible rows.
160// ImGuiListClipper is reliant on the fact that rows are of equal height.
161// See 'Demo->Tables->Vertical Scrolling' or 'Demo->Tables->Advanced' for a demo of using the clipper.
162// - Note that auto-resizing columns don't play well with using the clipper.
163// By default a table with _ScrollX but without _Resizable will have column auto-resize.
164// So, if you want to use the clipper, make sure to either enable _Resizable, either setup columns width explicitly with _WidthFixed.
165//-----------------------------------------------------------------------------
166// About clipping/culling of Columns in Tables:
167// - Both TableSetColumnIndex() and TableNextColumn() return true when the column is visible or performing
168// width measurements. Otherwise, you may skip submitting the contents of a cell/column, BUT ONLY if you know
169// it is not going to contribute to row height.
170// In many situations, you may skip submitting contents for every column but one (e.g. the first one).
171// - Case A: column is not hidden by user, and at least partially in sight (most common case).
172// - 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.
173// - Case C: column is hidden explicitly by the user (e.g. via the context menu, or _DefaultHide column flag, etc.).
174//
175// [A] [B] [C]
176// 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.
177// SkipItems: false false true -> [internal] when SkipItems is true, most widgets will early out if submitted, resulting is no layout output.
178// ClipRect: normal zero-width zero-width -> [internal] when ClipRect is zero, ItemAdd() will return false and most widgets will early out mid-way.
179// ImDrawList output: normal dummy dummy -> [internal] when using the dummy channel, ImDrawList submissions (if any) will be wasted (because cliprect is zero-width anyway).
180//
181// - 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.
182// 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.
183//-----------------------------------------------------------------------------
184// About clipping/culling of whole Tables:
185// - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false.
186//-----------------------------------------------------------------------------
187
188//-----------------------------------------------------------------------------
189// [SECTION] Header mess
190//-----------------------------------------------------------------------------
191
192#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
193#define _CRT_SECURE_NO_WARNINGS
194#endif
195
196#ifndef IMGUI_DEFINE_MATH_OPERATORS
197#define IMGUI_DEFINE_MATH_OPERATORS
198#endif
199
200#include "imgui.h"
201#ifndef IMGUI_DISABLE
202#include "imgui_internal.h"
203
204// System includes
205#include <stdint.h> // intptr_t
206
207// Visual Studio warnings
208#ifdef _MSC_VER
209#pragma warning (disable: 4127) // condition expression is constant
210#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
211#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
212#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
213#endif
214#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
215#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
216#endif
217
218// Clang/GCC warnings with -Weverything
219#if defined(__clang__)
220#if __has_warning("-Wunknown-warning-option")
221#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
222#endif
223#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
224#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
225#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
226#pragma clang diagnostic ignored "-Wformat" // warning: format specifies type 'int' but the argument has type 'unsigned int'
227#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
228#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
229#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
230#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
231#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_')
232#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
233#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
234#pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
235#pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
236#pragma clang diagnostic ignored "-Wswitch-default" // warning: 'switch' missing 'default' label
237#elif defined(__GNUC__)
238#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
239#pragma GCC diagnostic ignored "-Wfloat-equal" // warning: comparing floating-point with '==' or '!=' is unsafe
240#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
241#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
242#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'int'/'void*', but argument X has type 'unsigned int'/'ImGuiWindow*'
243#pragma GCC diagnostic ignored "-Wstrict-overflow"
244#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
245#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may change value
246#pragma GCC diagnostic ignored "-Wsign-conversion" // warning: conversion to 'xxxx' from 'xxxx' may change the sign of the result
247#endif
248
249//-----------------------------------------------------------------------------
250// [SECTION] Tables: Main code
251//-----------------------------------------------------------------------------
252// - TableFixFlags() [Internal]
253// - TableFindByID() [Internal]
254// - BeginTable()
255// - BeginTableEx() [Internal]
256// - TableBeginInitMemory() [Internal]
257// - TableApplyQueuedRequests() [Internal]
258// - TableSetupColumnFlags() [Internal]
259// - TableUpdateLayout() [Internal]
260// - TableUpdateBorders() [Internal]
261// - EndTable()
262// - TableSetupColumn()
263// - TableSetupScrollFreeze()
264//-----------------------------------------------------------------------------
265
266// Configuration
267static const int TABLE_DRAW_CHANNEL_BG0 = 0;
268static const int TABLE_DRAW_CHANNEL_BG2_FROZEN = 1;
269static const int TABLE_DRAW_CHANNEL_NOCLIP = 2; // When using ImGuiTableFlags_NoClip (this becomes the last visible channel)
270static const float TABLE_BORDER_SIZE = 1.0f; // FIXME-TABLE: Currently hard-coded because of clipping assumptions with outer borders rendering.
271static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders.
272static const float TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06f; // Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped.
273
274// Helper
275inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags, ImGuiWindow* outer_window)
276{
277 // Adjust flags: set default sizing policy
278 if ((flags & ImGuiTableFlags_SizingMask_) == 0)
279 flags |= ((flags & ImGuiTableFlags_ScrollX) || (outer_window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) ? ImGuiTableFlags_SizingFixedFit : ImGuiTableFlags_SizingStretchSame;
280
281 // Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags_SizingFixedSame
282 if ((flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame)
283 flags |= ImGuiTableFlags_NoKeepColumnsVisible;
284
285 // Adjust flags: enforce borders when resizable
286 if (flags & ImGuiTableFlags_Resizable)
287 flags |= ImGuiTableFlags_BordersInnerV;
288
289 // Adjust flags: disable NoHostExtendX/NoHostExtendY if we have any scrolling going on
290 if (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY))
291 flags &= ~(ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_NoHostExtendY);
292
293 // Adjust flags: NoBordersInBodyUntilResize takes priority over NoBordersInBody
294 if (flags & ImGuiTableFlags_NoBordersInBodyUntilResize)
295 flags &= ~ImGuiTableFlags_NoBordersInBody;
296
297 // Adjust flags: disable saved settings if there's nothing to save
298 if ((flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Sortable)) == 0)
299 flags |= ImGuiTableFlags_NoSavedSettings;
300
301 // Inherit _NoSavedSettings from top-level window (child windows always have _NoSavedSettings set)
302 if (outer_window->RootWindow->Flags & ImGuiWindowFlags_NoSavedSettings)
303 flags |= ImGuiTableFlags_NoSavedSettings;
304
305 return flags;
306}
307
308ImGuiTable* ImGui::TableFindByID(ImGuiID id)
309{
310 ImGuiContext& g = *GImGui;
311 return g.Tables.GetByKey(id);
312}
313
314// Read about "TABLE SIZING" at the top of this file.
315bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
316{
317 ImGuiID id = GetID(str_id);
318 return BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width);
319}
320
321bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
322{
323 ImGuiContext& g = *GImGui;
324 ImGuiWindow* outer_window = GetCurrentWindow();
325 if (outer_window->SkipItems) // Consistent with other tables + beneficial side effect that assert on miscalling EndTable() will be more visible.
326 return false;
327
328 // Sanity checks
329 IM_ASSERT(columns_count > 0 && columns_count < IMGUI_TABLE_MAX_COLUMNS);
330 if (flags & ImGuiTableFlags_ScrollX)
331 IM_ASSERT(inner_width >= 0.0f);
332
333 // If an outer size is specified ahead we will be able to early out when not visible. Exact clipping criteria may evolve.
334 // FIXME: coarse clipping because access to table data causes two issues:
335 // - instance numbers varying/unstable. may not be a direct problem for users, but could make outside access broken or confusing, e.g. TestEngine.
336 // - can't implement support for ImGuiChildFlags_ResizeY as we need to somehow pull the height data from somewhere. this also needs stable instance numbers.
337 // The side-effects of accessing table data on coarse clip would be:
338 // - 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.
339 // - always performing the GetOrAddByKey() O(log N) query in g.Tables.Map[].
340 const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0;
341 const ImVec2 avail_size = GetContentRegionAvail();
342 const ImVec2 actual_outer_size = ImTrunc(CalcItemSize(outer_size, ImMax(avail_size.x, IMGUI_WINDOW_HARD_MIN_SIZE), use_child_window ? ImMax(avail_size.y, IMGUI_WINDOW_HARD_MIN_SIZE) : 0.0f));
343 const ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size);
344 const bool outer_window_is_measuring_size = (outer_window->AutoFitFramesX > 0) || (outer_window->AutoFitFramesY > 0); // Doesn't apply to AlwaysAutoResize windows!
345 if (use_child_window && IsClippedEx(outer_rect, 0) && !outer_window_is_measuring_size)
346 {
347 ItemSize(outer_rect);
348 ItemAdd(outer_rect, id);
349 g.NextWindowData.ClearFlags();
350 return false;
351 }
352
353 // [DEBUG] Debug break requested by user
354 if (g.DebugBreakInTable == id)
355 IM_DEBUG_BREAK();
356
357 // Acquire storage for the table
358 ImGuiTable* table = g.Tables.GetOrAddByKey(id);
359
360 // Acquire temporary buffers
361 const int table_idx = g.Tables.GetIndex(table);
362 if (++g.TablesTempDataStacked > g.TablesTempData.Size)
363 g.TablesTempData.resize(g.TablesTempDataStacked, ImGuiTableTempData());
364 ImGuiTableTempData* temp_data = table->TempData = &g.TablesTempData[g.TablesTempDataStacked - 1];
365 temp_data->TableIndex = table_idx;
366 temp_data->ReconcileColumnsRequests.resize(0); // FIXME: Use shrink(0) everywhere?
367 table->DrawSplitter = &table->TempData->DrawSplitter;
368 table->DrawSplitter->Clear();
369
370 // Fix flags
371 table->IsDefaultSizingPolicy = (flags & ImGuiTableFlags_SizingMask_) == 0;
372 flags = TableFixFlags(flags, outer_window);
373
374 // Initialize
375 const int previous_frame_active = table->LastFrameActive;
376 const int instance_no = (previous_frame_active != g.FrameCount) ? 0 : table->InstanceCurrent + 1;
377 const ImGuiTableFlags previous_flags = table->Flags;
378 const bool is_new_table = (previous_frame_active == -1);
379 table->ID = id;
380 table->Flags = flags;
381 table->LastFrameActive = g.FrameCount;
382 table->OuterWindow = table->InnerWindow = outer_window;
383 table->ColumnsCount = columns_count;
384 table->IsLayoutLocked = false;
385 table->InnerWidth = inner_width;
386 table->NavLayer = (ImS8)outer_window->DC.NavLayerCurrent;
387 temp_data->UserOuterSize = outer_size;
388
389 // Instance data (for instance 0, TableID == TableInstanceID)
390 ImGuiID instance_id;
391 table->InstanceCurrent = (ImS16)instance_no;
392 if (instance_no > 0)
393 {
394 IM_ASSERT(table->ColumnsCount == columns_count && "BeginTable(): Cannot change columns count mid-frame while preserving same ID");
395 if (table->InstanceDataExtra.Size < instance_no)
396 table->InstanceDataExtra.push_back(ImGuiTableInstanceData());
397 instance_id = GetIDWithSeed(instance_no, GetIDWithSeed("##Instances", NULL, id)); // Push "##Instances" followed by (int)instance_no in ID stack.
398 }
399 else
400 {
401 instance_id = id;
402 }
403 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent);
404 table_instance->TableInstanceID = instance_id;
405
406 // When not using a child window, WorkRect.Max will grow as we append contents.
407 if (use_child_window)
408 {
409 // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent
410 // (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing)
411 ImVec2 override_content_size(FLT_MAX, FLT_MAX);
412 if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY))
413 override_content_size.y = FLT_MIN;
414
415 // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and
416 // never lead to any scrolling). We don't handle inner_width < 0.0f, we could potentially use it to right-align
417 // based on the right side of the child window work rect, which would require knowing ahead if we are going to
418 // have decoration taking horizontal spaces (typically a vertical scrollbar).
419 if ((flags & ImGuiTableFlags_ScrollX) && inner_width > 0.0f)
420 override_content_size.x = inner_width;
421
422 if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX)
423 SetNextWindowContentSize(ImVec2(override_content_size.x != FLT_MAX ? override_content_size.x : 0.0f, override_content_size.y != FLT_MAX ? override_content_size.y : 0.0f));
424
425 // Reset scroll if we are reactivating it
426 if ((previous_flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) == 0)
427 if ((g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasScroll) == 0)
428 SetNextWindowScroll(ImVec2(0.0f, 0.0f));
429
430 // Create scrolling region (without border and zero window padding)
431 ImGuiChildFlags child_child_flags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasChildFlags) ? g.NextWindowData.ChildFlags : ImGuiChildFlags_None;
432 ImGuiWindowFlags child_window_flags = (g.NextWindowData.HasFlags & ImGuiNextWindowDataFlags_HasWindowFlags) ? g.NextWindowData.WindowFlags : ImGuiWindowFlags_None;
433 if (flags & ImGuiTableFlags_ScrollX)
434 child_window_flags |= ImGuiWindowFlags_HorizontalScrollbar;
435 BeginChildEx(name, instance_id, outer_rect.GetSize(), child_child_flags, child_window_flags);
436 table->InnerWindow = g.CurrentWindow;
437 table->WorkRect = table->InnerWindow->WorkRect;
438 table->OuterRect = table->InnerWindow->Rect();
439 table->InnerRect = table->InnerWindow->InnerRect;
440 IM_ASSERT(table->InnerWindow->WindowPadding.x == 0.0f && table->InnerWindow->WindowPadding.y == 0.0f && table->InnerWindow->WindowBorderSize == 0.0f);
441
442 // Allow submitting when host is measuring
443 if (table->InnerWindow->SkipItems && outer_window_is_measuring_size)
444 table->InnerWindow->SkipItems = false;
445
446 // When using multiple instances, ensure they have the same amount of horizontal decorations (aka vertical scrollbar) so stretched columns can be aligned
447 if (instance_no == 0)
448 {
449 table->HasScrollbarYPrev = table->HasScrollbarYCurr;
450 table->HasScrollbarYCurr = false;
451 }
452 table->HasScrollbarYCurr |= table->InnerWindow->ScrollbarY;
453 }
454 else
455 {
456 // For non-scrolling tables, WorkRect == OuterRect == InnerRect.
457 // 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().
458 table->WorkRect = table->OuterRect = table->InnerRect = outer_rect;
459 table->HasScrollbarYPrev = table->HasScrollbarYCurr = false;
460 table->InnerWindow->DC.TreeDepth++; // This is designed to always linking ImGuiTreeNodeFlags_DrawLines linking across a table
461 }
462
463 // Push a standardized ID for both child-using and not-child-using tables
464 PushOverrideID(id);
465 if (instance_no > 0)
466 PushOverrideID(instance_id); // FIXME: Somehow this is not resolved by stack-tool, even tho GetIDWithSeed() submitted the symbol.
467
468 // Backup a copy of host window members we will modify
469 ImGuiWindow* inner_window = table->InnerWindow;
470 table->HostIndentX = inner_window->DC.Indent.x;
471 table->HostClipRect = inner_window->ClipRect;
472 table->HostSkipItems = inner_window->SkipItems;
473 temp_data->WindowID = inner_window->ID;
474 temp_data->HostBackupWorkRect = inner_window->WorkRect;
475 temp_data->HostBackupParentWorkRect = inner_window->ParentWorkRect;
476 temp_data->HostBackupColumnsOffset = outer_window->DC.ColumnsOffset;
477 temp_data->HostBackupPrevLineSize = inner_window->DC.PrevLineSize;
478 temp_data->HostBackupCurrLineSize = inner_window->DC.CurrLineSize;
479 temp_data->HostBackupCursorMaxPos = inner_window->DC.CursorMaxPos;
480 temp_data->HostBackupItemWidth = outer_window->DC.ItemWidth;
481 temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size;
482 inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
483
484 // Make borders not overlap our contents by offsetting HostClipRect (#6765, #7428, #3752)
485 // (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the
486 // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap
487 // problem only affect scrolling tables in this case we can get away with doing it without extra cost).
488 if (inner_window != outer_window)
489 {
490 // FIXME: Because inner_window's Scrollbar doesn't know about border size, since it's not encoded in window->WindowBorderSize,
491 // it already overlaps it and doesn't need an extra offset. Ideally we should be able to pass custom border size with
492 // different x/y values to BeginChild().
493 if (flags & ImGuiTableFlags_BordersOuterV)
494 {
495 table->HostClipRect.Min.x = ImMin(table->HostClipRect.Min.x + TABLE_BORDER_SIZE, table->HostClipRect.Max.x);
496 if (inner_window->DecoOuterSizeX2 == 0.0f)
497 table->HostClipRect.Max.x = ImMax(table->HostClipRect.Max.x - TABLE_BORDER_SIZE, table->HostClipRect.Min.x);
498 }
499 if (flags & ImGuiTableFlags_BordersOuterH)
500 {
501 table->HostClipRect.Min.y = ImMin(table->HostClipRect.Min.y + TABLE_BORDER_SIZE, table->HostClipRect.Max.y);
502 if (inner_window->DecoOuterSizeY2 == 0.0f)
503 table->HostClipRect.Max.y = ImMax(table->HostClipRect.Max.y - TABLE_BORDER_SIZE, table->HostClipRect.Min.y);
504 }
505 }
506
507 // Padding and Spacing
508 // - None ........Content..... Pad .....Content........
509 // - PadOuter | Pad ..Content..... Pad .....Content.. Pad |
510 // - PadInner ........Content.. Pad | Pad ..Content........
511 // - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad |
512 const bool pad_outer_x = (flags & ImGuiTableFlags_NoPadOuterX) ? false : (flags & ImGuiTableFlags_PadOuterX) ? true : (flags & ImGuiTableFlags_BordersOuterV) != 0;
513 const bool pad_inner_x = (flags & ImGuiTableFlags_NoPadInnerX) ? false : true;
514 const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? TABLE_BORDER_SIZE : 0.0f;
515 const float inner_spacing_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) == 0) ? g.Style.CellPadding.x : 0.0f;
516 const float inner_padding_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) != 0) ? g.Style.CellPadding.x : 0.0f;
517 table->CellSpacingX1 = inner_spacing_explicit + inner_spacing_for_border;
518 table->CellSpacingX2 = inner_spacing_explicit;
519 table->CellPaddingX = inner_padding_explicit;
520
521 const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;
522 const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f;
523 table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX;
524
525 table->CurrentColumn = -1;
526 table->CurrentRow = -1;
527 table->RowBgColorCounter = 0;
528 table->LastRowFlags = ImGuiTableRowFlags_None;
529 table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect;
530 table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width
531 table->InnerClipRect.ClipWithFull(table->HostClipRect);
532 table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : table->HostClipRect.Max.y;
533
534 table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow
535 table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow()
536 table->RowCellPaddingY = 0.0f;
537 table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any
538 table->FreezeColumnsRequest = table->FreezeColumnsCount = 0;
539 table->IsUnfrozenRows = true;
540 table->DeclColumnsCount = table->AngledHeadersCount = 0;
541 if (previous_frame_active + 1 < g.FrameCount)
542 table->IsActiveIdInTable = false;
543 table->AngledHeadersHeight = 0.0f;
544 temp_data->AngledHeadersExtraWidth = 0.0f;
545
546 // Using opaque colors facilitate overlapping lines of the grid, otherwise we'd need to improve TableDrawBorders()
547 table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong);
548 table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight);
549
550 // Make table current
551 g.CurrentTable = table;
552 inner_window->DC.NavIsScrollPushableX = false; // Shortcut for NavUpdateCurrentWindowIsScrollPushableX();
553 outer_window->DC.CurrentTableIdx = table_idx;
554 if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly.
555 inner_window->DC.CurrentTableIdx = table_idx;
556
557 if ((previous_flags & ImGuiTableFlags_Reorderable) && (flags & ImGuiTableFlags_Reorderable) == 0)
558 table->IsResetDisplayOrderRequest = true;
559
560 // Mark as used to avoid GC
561 if (table_idx >= g.TablesLastTimeActive.Size)
562 g.TablesLastTimeActive.resize(table_idx + 1, -1.0f);
563 g.TablesLastTimeActive[table_idx] = (float)g.Time;
564 temp_data->LastTimeActive = (float)g.Time;
565 table->MemoryCompacted = false;
566
567 // Setup memory buffer (clear data if columns count changed)
568 const int old_columns_count = table->Columns.size();
569 if (old_columns_count != 0 && old_columns_count != columns_count)
570 {
571 // Attempt to preserve width and other settings on column count/specs change (#4046, #9108)
572 IMGUI_DEBUG_LOG_TABLE("[table] Table 0x%08X column count %d -> %d, recreating storage.\n", table->ID, old_columns_count, columns_count);
573 IM_ASSERT(temp_data->OldColumnsRawData == NULL);
574 temp_data->OldColumnsRawData = table->RawData; // Freed during layout
575 temp_data->OldColumnsData = table->Columns;
576 for (ImGuiTableColumn& src_column : table->TempData->OldColumnsData)
577 src_column.IsNeedReconcileSrc = true;
578 table->RawData = NULL;
579 }
580 if (table->RawData == NULL)
581 {
582 TableBeginInitMemory(table, columns_count);
583 table->IsInitializing = true;
584 }
585 if (table->IsResetAllRequest)
586 TableResetSettings(table);
587 if (table->IsInitializing)
588 {
589 // Initialize
590 if (is_new_table)
591 {
592 table->SettingsOffset = -1;
593 table->IsSettingsRequestLoad = true;
594 }
595 table->IsSortSpecsDirty = true;
596 table->IsSettingsDirty = true; // Records itself into .ini file even when in default state (#7934)
597 table->IsReconcileMode = false;
598 table->InstanceInteracted = -1;
599 table->ContextPopupColumn = -1;
600 table->ReorderColumn = table->ReorderColumnDstOrder = table->ResizedColumn = table->LastResizedColumn = -1;
601 table->AutoFitSingleColumn = -1;
602 table->HoveredColumnBody = table->HoveredColumnBorder = -1;
603 for (int n = 0; n < columns_count; n++)
604 {
605 ImGuiTableColumn* column = &table->Columns[n];
606 if (temp_data->OldColumnsData.Data && n < temp_data->OldColumnsData.size())
607 {
608 *column = temp_data->OldColumnsData[n];
609 }
610 else
611 {
612 float width_auto = column->WidthAuto;
613 *column = ImGuiTableColumn();
614 column->WidthAuto = width_auto;
615 column->IsPreserveWidthAuto = true; // Preserve WidthAuto when reinitializing a live table: not technically necessary but remove a visible flicker
616 column->IsEnabled = column->IsUserEnabled = column->IsUserEnabledNextFrame = true;
617 column->DisplayOrder = (ImGuiTableColumnIdx)n;
618 }
619 table->DisplayOrderToIndex[n] = column->DisplayOrder;
620 }
621 }
622
623 // Load settings
624 if (table->IsSettingsRequestLoad)
625 TableLoadSettings(table);
626
627 // Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call..
628 // This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user.
629 // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option.
630 inner_window->SkipItems = true;
631
632 // Clear names
633 // At this point the ->NameOffset field of each column will be invalid until TableUpdateLayout() or the first call to TableSetupColumn()
634 if (table->ColumnsNames.Buf.Size > 0)
635 table->ColumnsNames.Buf.resize(0);
636
637 return true;
638}
639
640// For reference, the average total _allocation count_ for a table is:
641// + 0 (for ImGuiTable instance, we are pooling allocations in g.Tables[])
642// + 1 (for table->RawData allocated below)
643// + 1 (for table->ColumnsNames, if names are used)
644// Shared allocations for the maximum number of simultaneously nested tables (generally a very small number)
645// + 1 (for table->Splitter._Channels)
646// + 2 * active_channels_count (for ImDrawCmd and ImDrawIdx buffers inside channels)
647// Where active_channels_count is variable but often == columns_count or == columns_count + 1, see TableSetupDrawChannels() for details.
648// Unused channels don't perform their +2 allocations.
649void ImGui::TableBeginInitMemory(ImGuiTable* table, int columns_count)
650{
651 // Allocate single buffer for our arrays
652 const int columns_bit_array_size = (int)ImBitArrayGetStorageSizeInBytes(columns_count);
653 ImSpanAllocator<6> span_allocator;
654 span_allocator.Reserve(0, columns_count * sizeof(ImGuiTableColumn));
655 span_allocator.Reserve(1, columns_count * sizeof(ImGuiTableColumnIdx));
656 span_allocator.Reserve(2, columns_count * sizeof(ImGuiTableCellData), 4);
657 for (int n = 3; n < 6; n++)
658 span_allocator.Reserve(n, columns_bit_array_size);
659 table->RawData = IM_ALLOC(span_allocator.GetArenaSizeInBytes());
660 memset(table->RawData, 0, span_allocator.GetArenaSizeInBytes());
661 span_allocator.SetArenaBasePtr(table->RawData);
662 span_allocator.GetSpan(0, &table->Columns);
663 span_allocator.GetSpan(1, &table->DisplayOrderToIndex);
664 span_allocator.GetSpan(2, &table->RowCellData);
665 table->EnabledMaskByDisplayOrder = (ImU32*)span_allocator.GetSpanPtrBegin(3);
666 table->EnabledMaskByIndex = (ImU32*)span_allocator.GetSpanPtrBegin(4);
667 table->VisibleMaskByIndex = (ImU32*)span_allocator.GetSpanPtrBegin(5);
668}
669
670// Apply queued resizing/reordering/hiding requests
671void ImGui::TableApplyQueuedRequests(ImGuiTable* table)
672{
673 // Handle resizing request
674 // (We process this in the TableBegin() of the first instance of each table)
675 // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling?
676 if (table->InstanceCurrent == 0)
677 {
678 if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX)
679 TableSetColumnWidth(table->ResizedColumn, table->ResizedColumnNextWidth);
680 table->LastResizedColumn = table->ResizedColumn;
681 table->ResizedColumnNextWidth = FLT_MAX;
682 table->ResizedColumn = -1;
683
684 // Process auto-fit for single column, which is a special case for stretch columns and fixed columns with FixedSame policy.
685 // FIXME-TABLE: Would be nice to redistribute available stretch space accordingly to other weights, instead of giving it all to siblings.
686 if (table->AutoFitSingleColumn != -1)
687 {
688 TableSetColumnWidth(table->AutoFitSingleColumn, table->Columns[table->AutoFitSingleColumn].WidthAuto);
689 table->AutoFitSingleColumn = -1;
690 }
691 }
692
693 // Handle reordering request
694 //// Note: we don't clear ReorderColumn after handling the request (FIXME: clarify why or add a test).
695 if (table->InstanceCurrent == 0)
696 {
697 table->LastHeldHeaderColumn = table->HeldHeaderColumn;
698 table->HeldHeaderColumn = -1;
699 if (table->ReorderColumn != -1 && table->ReorderColumnDstOrder != -1)
700 {
701 TableSetColumnDisplayOrder(table, table->ReorderColumn, table->ReorderColumnDstOrder);
702 table->ReorderColumnDstOrder = -1;
703 }
704
705 // Release
706 ImGuiContext& g = *GImGui;
707 if (g.ActiveId == 0) // FIXME: Need to revisit. See 38f5e5a.
708 table->ReorderColumn = -1;
709 //if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1)
710 // table->ReorderColumn = -1;
711 }
712
713 // Handle display order / visibility reset requests
714 if (table->IsResetDisplayOrderRequest)
715 {
716 for (int n = 0; n < table->ColumnsCount; n++)
717 table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n;
718 table->IsResetDisplayOrderRequest = false;
719 table->IsSettingsDirty = true;
720 }
721 if (table->IsResetVisibilityRequest)
722 {
723 for (ImGuiTableColumn& column : table->Columns)
724 column.IsUserEnabled = column.IsUserEnabledNextFrame = (column.Flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1;
725 table->IsResetVisibilityRequest = false;
726 table->IsSettingsDirty = true;
727 }
728}
729
730// Apply immediately. See TableQueueSetColumnDisplayOrder() for additional checks/constraints.
731void ImGui::TableSetColumnDisplayOrder(ImGuiTable* table, int column_n, int dst_order)
732{
733 IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
734 IM_ASSERT(dst_order >= 0 && dst_order < table->ColumnsCount);
735
736 ImGuiTableColumn* src_column = &table->Columns[column_n];
737 const int src_order = src_column->DisplayOrder;
738 if (src_order == dst_order)
739 return;
740 const int reorder_dir = (dst_order < src_order) ? -1 : +1;
741
742 src_column->DisplayOrder = (ImGuiTableColumnIdx)dst_order;
743 for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir)
744 table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImGuiTableColumnIdx)reorder_dir;
745 //IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir);
746
747 // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[]. Rebuild later from the former.
748 // FIXME-OPT: If this is called multiple times we'd effectively have a O(N^2) thing going on.
749 for (int n = 0; n < table->ColumnsCount; n++)
750 table->DisplayOrderToIndex[table->Columns[n].DisplayOrder] = (ImGuiTableColumnIdx)n;
751 table->IsSettingsDirty = true;
752}
753
754static int TableGetMaxDisplayOrderAllowed(ImGuiTable* table, int src_order, int dst_order)
755{
756 dst_order = ImClamp(dst_order, 0, table->ColumnsCount - 1);
757 if (src_order == dst_order)
758 return dst_order;
759
760 // Cannot cross over the frozen column limit when interactively reordering.
761 // TableSetupScrollFreeze() enforce a display order range for frozen columns. Reordering across the frozen column barrier is illegal and will be undone.
762 if (table->FreezeColumnsRequest > 0)
763 dst_order = (src_order < table->FreezeColumnsRequest) ? ImMin(dst_order, (int)table->FreezeColumnsRequest - 1) : ImMax(dst_order, (int)table->FreezeColumnsRequest);
764
765 // Cannot cross over a column with the ImGuiTableColumnFlags_NoReorder flag.
766 int reorder_dir = (src_order < dst_order) ? +1 : -1;
767 for (int order_n = src_order; (src_order < dst_order && order_n <= dst_order) || (dst_order < src_order && order_n >= dst_order); order_n += reorder_dir)
768 if (table->Columns[table->DisplayOrderToIndex[order_n]].Flags & ImGuiTableColumnFlags_NoReorder)
769 {
770 dst_order = (order_n == src_order) ? src_order : order_n - reorder_dir;
771 break;
772 }
773 return dst_order;
774}
775
776// Reorder requested by user interaction.
777void ImGui::TableQueueSetColumnDisplayOrder(ImGuiTable* table, int column_n, int dst_order)
778{
779 const int src_order = table->Columns[column_n].DisplayOrder;
780 table->ReorderColumn = (ImGuiTableColumnIdx)column_n;
781 table->ReorderColumnDstOrder = (ImGuiTableColumnIdx)-1;
782 dst_order = TableGetMaxDisplayOrderAllowed(table, src_order, dst_order);
783 if (table->IsLayoutLocked && dst_order == src_order) // We allow calling the function before layout w/ reconcile so don't early out.
784 return;
785 table->ReorderColumnDstOrder = (ImGuiTableColumnIdx)dst_order;
786}
787
788// Adjust flags: default width mode + stretch columns are not allowed when auto extending
789static void TableSetupColumnFlags(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags flags_in)
790{
791 ImGuiTableColumnFlags flags = flags_in;
792
793 // Sizing Policy
794 if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0)
795 {
796 const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_);
797 if (table_sizing_policy == ImGuiTableFlags_SizingFixedFit || table_sizing_policy == ImGuiTableFlags_SizingFixedSame)
798 flags |= ImGuiTableColumnFlags_WidthFixed;
799 else
800 flags |= ImGuiTableColumnFlags_WidthStretch;
801 }
802 else
803 {
804 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_WidthMask_)); // Check that only 1 of each set is used.
805 }
806
807 // Resize
808 if ((table->Flags & ImGuiTableFlags_Resizable) == 0)
809 flags |= ImGuiTableColumnFlags_NoResize;
810
811 // Sorting
812 if ((flags & ImGuiTableColumnFlags_NoSortAscending) && (flags & ImGuiTableColumnFlags_NoSortDescending))
813 flags |= ImGuiTableColumnFlags_NoSort;
814
815 // Indentation
816 if ((flags & ImGuiTableColumnFlags_IndentMask_) == 0)
817 flags |= (table->Columns.index_from_ptr(column) == 0) ? ImGuiTableColumnFlags_IndentEnable : ImGuiTableColumnFlags_IndentDisable;
818
819 // Alignment
820 //if ((flags & ImGuiTableColumnFlags_AlignMask_) == 0)
821 // flags |= ImGuiTableColumnFlags_AlignCenter;
822 //IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_AlignMask_)); // Check that only 1 of each set is used.
823
824 // Preserve status flags
825 column->Flags = flags | (column->Flags & ImGuiTableColumnFlags_StatusMask_);
826
827 // Build an ordered list of available sort directions
828 column->SortDirectionsAvailCount = column->SortDirectionsAvailMask = column->SortDirectionsAvailList = 0;
829 if (table->Flags & ImGuiTableFlags_Sortable)
830 {
831 int count = 0, mask = 0, list = 0;
832 if ((flags & ImGuiTableColumnFlags_PreferSortAscending) != 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; }
833 if ((flags & ImGuiTableColumnFlags_PreferSortDescending) != 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; }
834 if ((flags & ImGuiTableColumnFlags_PreferSortAscending) == 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; }
835 if ((flags & ImGuiTableColumnFlags_PreferSortDescending) == 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; }
836 if ((table->Flags & ImGuiTableFlags_SortTristate) || count == 0) { mask |= 1 << ImGuiSortDirection_None; count++; }
837 column->SortDirectionsAvailList = (ImU8)list;
838 column->SortDirectionsAvailMask = (ImU8)mask;
839 column->SortDirectionsAvailCount = (ImU8)count;
840 ImGui::TableFixColumnSortDirection(table, column);
841 }
842}
843
844// Layout columns for the frame. This is in essence the followup to BeginTable() and this is our largest function.
845// Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() and other TableSetupXXXXX() functions to be called first.
846// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns.
847// Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns?
848void ImGui::TableUpdateLayout(ImGuiTable* table)
849{
850 ImGuiContext& g = *GImGui;
851 ImGuiTableTempData* temp_data = table->TempData;
852 IM_ASSERT(table->IsLayoutLocked == false);
853 const int columns_count = table->ColumnsCount;
854
855 // Reconcile moved columns
856 if (temp_data->ReconcileColumnsRequests.Size > 0)
857 TableReconcileColumns(table);
858 if (temp_data->OldColumnsRawData)
859 {
860 IM_FREE(temp_data->OldColumnsRawData);
861 temp_data->OldColumnsRawData = NULL;
862 temp_data->OldColumnsData.clear();
863 }
864
865 // Apply columns settings
866 if (table->IsSettingsRequestLoad)
867 TableLoadSettingsForColumns(table);
868 if (table->IsInitializing || table->IsSettingsRequestLoad)
869 {
870 for (ImGuiTableColumn& column : table->Columns)
871 {
872 ImGuiTableFlags init_flags;
873 if (table->IsSettingsRequestLoad)
874 init_flags = column.IsLoadedSettings ? ~table->SettingsLoadedFlags : ~0;
875 else
876 init_flags = column.IsJustCreated ? ~0 : 0;
877 TableInitColumnDefaults(table, &column, init_flags);
878 }
879 TableFixDisplayOrder(table); // Call even for non _Reorderable table as we loaded .ini data.
880 table->IsSettingsRequestLoad = false;
881 }
882
883 // Apply queued resizing/reordering/hiding requests
884 TableApplyQueuedRequests(table);
885
886 // Handle DPI/font resize
887 // This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well.
888 // It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition.
889 // FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory.
890 // This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path.
891 const float new_ref_scale_unit = g.FontSize; // g.Font->GetCharAdvance('A') ?
892 if (table->RefScale != 0.0f && table->RefScale != new_ref_scale_unit)
893 {
894 const float scale_factor = new_ref_scale_unit / table->RefScale;
895 IMGUI_DEBUG_LOG_TABLE("[table] 0x%08X RefScale %.3f -> %.3f, scaling width by %.3f\n", table->ID, table->RefScale, new_ref_scale_unit, scale_factor);
896 for (int n = 0; n < columns_count; n++)
897 table->Columns[n].WidthRequest = table->Columns[n].WidthRequest * scale_factor;
898 }
899 table->RefScale = new_ref_scale_unit;
900
901 const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_);
902 table->IsDefaultDisplayOrder = table->IsDefaultVisibility = true;
903 table->ColumnsEnabledCount = 0;
904 ImBitArrayClearAllBits(table->EnabledMaskByIndex, columns_count);
905 ImBitArrayClearAllBits(table->EnabledMaskByDisplayOrder, columns_count);
906 table->LeftMostEnabledColumn = -1;
907 table->MinColumnWidth = ImMax(1.0f, g.Style.FramePadding.x * 1.0f); // g.Style.ColumnsMinSpacing; // FIXME-TABLE
908
909 // [Part 1] Apply/lock Enabled and Order states. Calculate auto/ideal width for columns. Count fixed/stretch columns.
910 // Process columns in their visible orders as we are building the Prev/Next indices.
911 int count_fixed = 0; // Number of columns that have fixed sizing policies
912 int count_stretch = 0; // Number of columns that have stretch sizing policies
913 int prev_visible_column_idx = -1;
914 bool has_auto_fit_request = false;
915 bool has_resizable = false;
916 float stretch_sum_width_auto = 0.0f;
917 float fixed_max_width_auto = 0.0f;
918 for (int order_n = 0; order_n < columns_count; order_n++)
919 {
920 const int column_n = table->DisplayOrderToIndex[order_n];
921 ImGuiTableColumn* column = &table->Columns[column_n];
922
923 // Clear column setup if not submitted by user. Currently we make it mandatory to call TableSetupColumn() every frame.
924 // It would easily work without but we're not ready to guarantee it since e.g. names need resubmission anyway.
925 // We take a slight shortcut but in theory we could be calling TableSetupColumn() here with dummy values, it should yield the same effect.
926 if (table->DeclColumnsCount <= column_n)
927 {
928 TableSetupColumnFlags(table, column, ImGuiTableColumnFlags_None);
929 column->NameOffset = -1;
930 column->ID = column->UserData = 0;
931 column->InitStretchWeightOrWidth = -1.0f;
932 }
933
934 // Update Enabled state, mark settings and sort specs dirty
935 if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide))
936 column->IsUserEnabledNextFrame = true;
937 if (column->IsUserEnabled != column->IsUserEnabledNextFrame)
938 {
939 column->IsUserEnabled = column->IsUserEnabledNextFrame;
940 table->IsSettingsDirty = true;
941 }
942 column->IsEnabled = column->IsUserEnabled && (column->Flags & ImGuiTableColumnFlags_Disabled) == 0;
943 column->IsJustCreated = false;
944
945 if (column->IsEnabled != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1))
946 table->IsDefaultVisibility = false;
947 if (column_n != order_n)
948 table->IsDefaultDisplayOrder = false;
949
950 if (column->SortOrder != -1 && !column->IsEnabled)
951 table->IsSortSpecsDirty = true;
952 if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_SortMulti))
953 table->IsSortSpecsDirty = true;
954
955 // Auto-fit unsized columns
956 const bool start_auto_fit = (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? (column->WidthRequest < 0.0f) : (column->StretchWeight < 0.0f);
957 if (start_auto_fit)
958 column->AutoFitQueue = column->CannotSkipItemsQueue = (1 << 3) - 1; // Fit for three frames
959
960 if (!column->IsEnabled)
961 {
962 column->IndexWithinEnabledSet = -1;
963 continue;
964 }
965
966 // Mark as enabled and link to previous/next enabled column
967 column->PrevEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx;
968 column->NextEnabledColumn = -1;
969 if (prev_visible_column_idx != -1)
970 table->Columns[prev_visible_column_idx].NextEnabledColumn = (ImGuiTableColumnIdx)column_n;
971 else
972 table->LeftMostEnabledColumn = (ImGuiTableColumnIdx)column_n;
973 column->IndexWithinEnabledSet = table->ColumnsEnabledCount++;
974 ImBitArraySetBit(table->EnabledMaskByIndex, column_n);
975 ImBitArraySetBit(table->EnabledMaskByDisplayOrder, column->DisplayOrder);
976 prev_visible_column_idx = column_n;
977 IM_ASSERT(column->IndexWithinEnabledSet <= column->DisplayOrder);
978
979 // Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping)
980 // Combine width from regular rows + width from headers unless requested not to.
981 if (!column->IsPreserveWidthAuto && table->InstanceCurrent == 0)
982 column->WidthAuto = TableGetColumnWidthAuto(table, column);
983
984 // Non-resizable columns keep their requested width (apply user value regardless of IsPreserveWidthAuto)
985 const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0;
986 if (column_is_resizable)
987 has_resizable = true;
988 if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f && !column_is_resizable)
989 column->WidthAuto = column->InitStretchWeightOrWidth;
990
991 if (column->AutoFitQueue != 0x00)
992 has_auto_fit_request = true;
993 if (column->Flags & ImGuiTableColumnFlags_WidthStretch)
994 {
995 stretch_sum_width_auto += column->WidthAuto;
996 count_stretch++;
997 }
998 else
999 {
1000 fixed_max_width_auto = ImMax(fixed_max_width_auto, column->WidthAuto);
1001 count_fixed++;
1002 }
1003 }
1004 if ((table->Flags & ImGuiTableFlags_Sortable) && table->SortSpecsCount == 0 && !(table->Flags & ImGuiTableFlags_SortTristate))
1005 table->IsSortSpecsDirty = true;
1006 table->RightMostEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx;
1007 IM_ASSERT(table->LeftMostEnabledColumn >= 0 && table->RightMostEnabledColumn >= 0);
1008
1009 // [Part 2] Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid
1010 // 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.
1011 // FIXME-TABLE: for always auto-resizing columns may not want to do that all the time.
1012 if (has_auto_fit_request && table->OuterWindow != table->InnerWindow)
1013 table->InnerWindow->SkipItems = false;
1014 if (has_auto_fit_request)
1015 table->IsSettingsDirty = true;
1016
1017 // [Part 3] Fix column flags and record a few extra information.
1018 float sum_width_requests = 0.0f; // Sum of all width for fixed and auto-resize columns, excluding width contributed by Stretch columns but including spacing/padding.
1019 float stretch_sum_weights = 0.0f; // Sum of all weights for stretch columns.
1020 table->LeftMostStretchedColumn = table->RightMostStretchedColumn = -1;
1021 for (int column_n = 0; column_n < columns_count; column_n++)
1022 {
1023 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n))
1024 continue;
1025 ImGuiTableColumn* column = &table->Columns[column_n];
1026
1027 const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0;
1028 if (column->Flags & ImGuiTableColumnFlags_WidthFixed)
1029 {
1030 // Apply same widths policy
1031 float width_auto = column->WidthAuto;
1032 if (table_sizing_policy == ImGuiTableFlags_SizingFixedSame && (column->AutoFitQueue != 0x00 || !column_is_resizable))
1033 width_auto = fixed_max_width_auto;
1034
1035 // Apply automatic width
1036 // Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!)
1037 if (column->AutoFitQueue != 0x00)
1038 column->WidthRequest = width_auto;
1039 else if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !column_is_resizable && column->IsRequestOutput)
1040 column->WidthRequest = width_auto;
1041
1042 // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets
1043 // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very
1044 // large height (= first frame scrollbar display very off + clipper would skip lots of items).
1045 // This is merely making the side-effect less extreme, but doesn't properly fixes it.
1046 // FIXME: Move this to ->WidthGiven to avoid temporary lossyness?
1047 // FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller.
1048 if (column->AutoFitQueue > 0x01 && table->IsInitializing && !column->IsPreserveWidthAuto)
1049 column->WidthRequest = ImMax(column->WidthRequest, table->MinColumnWidth * 4.0f); // FIXME-TABLE: Another constant/scale?
1050 sum_width_requests += column->WidthRequest;
1051 }
1052 else
1053 {
1054 // Initialize stretch weight
1055 if (column->AutoFitQueue != 0x00 || column->StretchWeight < 0.0f || !column_is_resizable)
1056 {
1057 if (column->InitStretchWeightOrWidth > 0.0f)
1058 column->StretchWeight = column->InitStretchWeightOrWidth;
1059 else if (table_sizing_policy == ImGuiTableFlags_SizingStretchProp)
1060 column->StretchWeight = (column->WidthAuto / stretch_sum_width_auto) * count_stretch;
1061 else
1062 column->StretchWeight = 1.0f;
1063 }
1064
1065 stretch_sum_weights += column->StretchWeight;
1066 if (table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder > column->DisplayOrder)
1067 table->LeftMostStretchedColumn = (ImGuiTableColumnIdx)column_n;
1068 if (table->RightMostStretchedColumn == -1 || table->Columns[table->RightMostStretchedColumn].DisplayOrder < column->DisplayOrder)
1069 table->RightMostStretchedColumn = (ImGuiTableColumnIdx)column_n;
1070 }
1071 column->IsPreserveWidthAuto = false;
1072 sum_width_requests += table->CellPaddingX * 2.0f;
1073 }
1074 table->ColumnsEnabledFixedCount = (ImGuiTableColumnIdx)count_fixed;
1075 table->ColumnsStretchSumWeights = stretch_sum_weights;
1076
1077 // [Part 4] Apply final widths based on requested widths
1078 const ImRect work_rect = table->WorkRect;
1079 const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1);
1080 const float width_removed = (table->HasScrollbarYPrev && !table->InnerWindow->ScrollbarY) ? g.Style.ScrollbarSize : 0.0f; // To synchronize decoration width of synced tables with mismatching scrollbar state (#5920)
1081 const float width_avail = ImMax(1.0f, (((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) ? table->InnerClipRect.GetWidth() : work_rect.GetWidth()) - width_removed);
1082 const float width_avail_for_stretched_columns = width_avail - width_spacings - sum_width_requests;
1083 float width_remaining_for_stretched_columns = width_avail_for_stretched_columns;
1084 table->ColumnsGivenWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount;
1085 for (int column_n = 0; column_n < columns_count; column_n++)
1086 {
1087 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n))
1088 continue;
1089 ImGuiTableColumn* column = &table->Columns[column_n];
1090
1091 // Allocate width for stretched/weighted columns (StretchWeight gets converted into WidthRequest)
1092 if (column->Flags & ImGuiTableColumnFlags_WidthStretch)
1093 {
1094 float weight_ratio = column->StretchWeight / stretch_sum_weights;
1095 column->WidthRequest = IM_TRUNC(ImMax(width_avail_for_stretched_columns * weight_ratio, table->MinColumnWidth) + 0.01f);
1096 width_remaining_for_stretched_columns -= column->WidthRequest;
1097 }
1098
1099 // [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column
1100 // See additional comments in TableSetColumnWidth().
1101 if (column->NextEnabledColumn == -1 && table->LeftMostStretchedColumn != -1)
1102 column->Flags |= ImGuiTableColumnFlags_NoDirectResize_;
1103
1104 // Assign final width, record width in case we will need to shrink
1105 column->WidthGiven = ImTrunc(ImMax(column->WidthRequest, table->MinColumnWidth));
1106 table->ColumnsGivenWidth += column->WidthGiven;
1107 }
1108
1109 // [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0f * number of Stretch column).
1110 // Using right-to-left distribution (more likely to match resizing cursor).
1111 if (width_remaining_for_stretched_columns >= 1.0f && !(table->Flags & ImGuiTableFlags_PreciseWidths))
1112 for (int order_n = columns_count - 1; stretch_sum_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--)
1113 {
1114 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n))
1115 continue;
1116 ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]];
1117 if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch))
1118 continue;
1119 column->WidthRequest += 1.0f;
1120 column->WidthGiven += 1.0f;
1121 width_remaining_for_stretched_columns -= 1.0f;
1122 }
1123
1124 // Determine if table is hovered which will be used to flag columns as hovered.
1125 // - In principle we'd like to use the equivalent of IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
1126 // but because our item is partially submitted at this point we use ItemHoverable() and a workaround (temporarily
1127 // clear ActiveId, which is equivalent to the change provided by _AllowWhenBLockedByActiveItem).
1128 // - This allows columns to be marked as hovered when e.g. clicking a button inside the column, or using drag and drop.
1129 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent);
1130 table_instance->HoveredRowLast = table_instance->HoveredRowNext;
1131 table_instance->HoveredRowNext = -1;
1132 table->HoveredColumnBody = table->HoveredColumnBorder = -1;
1133 const ImRect mouse_hit_rect(table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.Max.x, ImMax(table->OuterRect.Max.y, table->OuterRect.Min.y + table_instance->LastOuterHeight));
1134 const ImGuiID backup_active_id = g.ActiveId;
1135 g.ActiveId = 0;
1136 const bool is_hovering_table = ItemHoverable(mouse_hit_rect, 0, ImGuiItemFlags_None);
1137 g.ActiveId = backup_active_id;
1138
1139 // Determine skewed MousePos.x to support angled headers.
1140 float mouse_skewed_x = g.IO.MousePos.x;
1141 if (table->AngledHeadersHeight > 0.0f)
1142 if (g.IO.MousePos.y >= table->OuterRect.Min.y && g.IO.MousePos.y <= table->OuterRect.Min.y + table->AngledHeadersHeight)
1143 mouse_skewed_x += ImTrunc((table->OuterRect.Min.y + table->AngledHeadersHeight - g.IO.MousePos.y) * table->AngledHeadersSlope);
1144
1145 // [Part 6] Setup final position, offset, skip/clip states and clipping rectangles, detect hovered column
1146 // Process columns in their visible orders as we are comparing the visible order and adjusting host_clip_rect while looping.
1147 bool has_at_least_one_column_requesting_output = false;
1148 bool offset_x_frozen = (table->FreezeColumnsCount > 0);
1149 float offset_x = ((table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x) + table->OuterPaddingX - table->CellSpacingX1;
1150 ImRect host_clip_rect = table->InnerClipRect;
1151 //host_clip_rect.Max.x += table->CellPaddingX + table->CellSpacingX2;
1152 ImBitArrayClearAllBits(table->VisibleMaskByIndex, columns_count);
1153 for (int order_n = 0; order_n < columns_count; order_n++)
1154 {
1155 const int column_n = table->DisplayOrderToIndex[order_n];
1156 ImGuiTableColumn* column = &table->Columns[column_n];
1157
1158 // Initial nav layer: using FreezeRowsCount, NOT FreezeRowsRequest, so Header line changes layer when frozen
1159 column->NavLayerCurrent = (ImS8)(table->FreezeRowsCount > 0 ? ImGuiNavLayer_Menu : (ImGuiNavLayer)table->NavLayer);
1160
1161 if (offset_x_frozen && table->FreezeColumnsCount == order_n)
1162 {
1163 offset_x += work_rect.Min.x - table->OuterRect.Min.x;
1164 offset_x_frozen = false;
1165 }
1166
1167 // Clear status flags
1168 column->Flags &= ~ImGuiTableColumnFlags_StatusMask_;
1169
1170 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n))
1171 {
1172 // Hidden column: clear a few fields and we are done with it for the remainder of the function.
1173 // We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper.
1174 column->MinX = column->MaxX = column->WorkMinX = column->ClipRect.Min.x = column->ClipRect.Max.x = offset_x;
1175 column->WidthGiven = 0.0f;
1176 column->ClipRect.Min.y = work_rect.Min.y;
1177 column->ClipRect.Max.y = FLT_MAX;
1178 column->ClipRect.ClipWithFull(host_clip_rect);
1179 column->IsVisibleX = column->IsVisibleY = column->IsRequestOutput = false;
1180 column->IsSkipItems = true;
1181 column->ItemWidth = 1.0f;
1182 continue;
1183 }
1184
1185 // Lock start position
1186 column->MinX = offset_x;
1187
1188 // Lock width based on start position and minimum/maximum width for this position
1189 column->WidthMax = TableCalcMaxColumnWidth(table, column_n);
1190 column->WidthGiven = ImMin(column->WidthGiven, column->WidthMax);
1191 column->WidthGiven = ImMax(column->WidthGiven, ImMin(column->WidthRequest, table->MinColumnWidth));
1192 column->MaxX = offset_x + column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f;
1193
1194 // Lock other positions
1195 // - 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.
1196 // - 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.
1197 // - ClipRect.Max.x: using MaxX makes it easier for header to receive hover highlight with no discontinuity and display sorting arrow.
1198 // - 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.
1199 const float previous_instance_work_min_x = column->WorkMinX;
1200 column->WorkMinX = column->MinX + table->CellPaddingX + table->CellSpacingX1;
1201 column->WorkMaxX = column->MaxX - table->CellPaddingX - table->CellSpacingX2; // Expected max
1202 column->ItemWidth = ImTrunc(column->WidthGiven * 0.65f);
1203 column->ClipRect.Min.x = column->MinX;
1204 column->ClipRect.Min.y = work_rect.Min.y;
1205 column->ClipRect.Max.x = column->MaxX; //column->WorkMaxX;
1206 column->ClipRect.Max.y = FLT_MAX;
1207 column->ClipRect.ClipWithFull(host_clip_rect);
1208
1209 // Mark column as Clipped (not in sight)
1210 // Note that scrolling tables (where inner_window != outer_window) handle Y clipped earlier in BeginTable() so IsVisibleY really only applies to non-scrolling tables.
1211 // 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.
1212 // Taking advantage of LastOuterHeight would yield good results there...
1213 // 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,
1214 // and this may be used (e.g. typically by outer_window using AlwaysAutoResize or outer_window's horizontal scrollbar, but could be something else).
1215 // 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.
1216 column->IsVisibleX = (column->ClipRect.Max.x > column->ClipRect.Min.x);
1217 column->IsVisibleY = true; // (column->ClipRect.Max.y > column->ClipRect.Min.y);
1218 const bool is_visible = column->IsVisibleX; //&& column->IsVisibleY;
1219 if (is_visible)
1220 ImBitArraySetBit(table->VisibleMaskByIndex, column_n);
1221
1222 // Mark column as requesting output from user. Note that fixed + non-resizable sets are auto-fitting at all times and therefore always request output.
1223 column->IsRequestOutput = is_visible || column->AutoFitQueue != 0 || column->CannotSkipItemsQueue != 0;
1224
1225 // Mark column as SkipItems (ignoring all items/layout)
1226 // (table->HostSkipItems is a copy of inner_window->SkipItems before we cleared it above in Part 2)
1227 column->IsSkipItems = !column->IsEnabled || table->HostSkipItems;
1228 if (column->IsSkipItems)
1229 IM_ASSERT(!is_visible);
1230 if (column->IsRequestOutput && !column->IsSkipItems)
1231 has_at_least_one_column_requesting_output = true;
1232
1233 // Update status flags
1234 column->Flags |= ImGuiTableColumnFlags_IsEnabled;
1235 if (is_visible)
1236 column->Flags |= ImGuiTableColumnFlags_IsVisible;
1237 if (column->SortOrder != -1)
1238 column->Flags |= ImGuiTableColumnFlags_IsSorted;
1239
1240 // Detect hovered column
1241 if (is_hovering_table && mouse_skewed_x >= column->ClipRect.Min.x && mouse_skewed_x < column->ClipRect.Max.x)
1242 {
1243 column->Flags |= ImGuiTableColumnFlags_IsHovered;
1244 table->HoveredColumnBody = (ImGuiTableColumnIdx)column_n;
1245 }
1246
1247 // Alignment
1248 // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in
1249 // many cases (to be able to honor this we might be able to store a log of cells width, per row, for
1250 // visible rows, but nav/programmatic scroll would have visible artifacts.)
1251 //if (column->Flags & ImGuiTableColumnFlags_AlignRight)
1252 // column->WorkMinX = ImMax(column->WorkMinX, column->MaxX - column->ContentWidthRowsUnfrozen);
1253 //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter)
1254 // column->WorkMinX = ImLerp(column->WorkMinX, ImMax(column->StartX, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f);
1255
1256 // Reset content width variables
1257 if (table->InstanceCurrent == 0)
1258 {
1259 column->ContentMaxXFrozen = column->WorkMinX;
1260 column->ContentMaxXUnfrozen = column->WorkMinX;
1261 column->ContentMaxXHeadersUsed = column->WorkMinX;
1262 column->ContentMaxXHeadersIdeal = column->WorkMinX;
1263 }
1264 else
1265 {
1266 // As we store an absolute value to make per-cell updates faster, we need to offset values used for width computation.
1267 const float offset_from_previous_instance = column->WorkMinX - previous_instance_work_min_x;
1268 column->ContentMaxXFrozen += offset_from_previous_instance;
1269 column->ContentMaxXUnfrozen += offset_from_previous_instance;
1270 column->ContentMaxXHeadersUsed += offset_from_previous_instance;
1271 column->ContentMaxXHeadersIdeal += offset_from_previous_instance;
1272 }
1273
1274 // Don't decrement auto-fit counters until container window got a chance to submit its items
1275 if (table->HostSkipItems == false && table->InstanceCurrent == 0)
1276 {
1277 column->AutoFitQueue >>= 1;
1278 column->CannotSkipItemsQueue >>= 1;
1279 }
1280
1281 if (order_n < table->FreezeColumnsCount)
1282 host_clip_rect.Min.x = ImClamp(column->MaxX + TABLE_BORDER_SIZE, host_clip_rect.Min.x, host_clip_rect.Max.x);
1283
1284 offset_x += column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f;
1285 }
1286
1287 // In case the table is visible (e.g. decorations) but all columns clipped, we keep a column visible.
1288 // Else if give no chance to a clipper-savvy user to submit rows and therefore total contents height used by scrollbar.
1289 if (has_at_least_one_column_requesting_output == false)
1290 {
1291 table->Columns[table->LeftMostEnabledColumn].IsRequestOutput = true;
1292 table->Columns[table->LeftMostEnabledColumn].IsSkipItems = false;
1293 }
1294
1295 // [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)
1296 // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either
1297 // because of using _WidthAuto/_WidthStretch). This will hide the resizing option from the context menu.
1298 const float unused_x1 = ImMax(table->WorkRect.Min.x, table->Columns[table->RightMostEnabledColumn].ClipRect.Max.x);
1299 if (is_hovering_table && table->HoveredColumnBody == -1)
1300 if (mouse_skewed_x >= unused_x1)
1301 table->HoveredColumnBody = (ImGuiTableColumnIdx)columns_count;
1302 if (has_resizable == false && (table->Flags & ImGuiTableFlags_Resizable))
1303 table->Flags &= ~ImGuiTableFlags_Resizable;
1304
1305 table->IsActiveIdAliveBeforeTable = (g.ActiveIdIsAlive != 0);
1306
1307 // [Part 8] Lock actual OuterRect/WorkRect right-most position.
1308 // This is done late to handle the case of fixed-columns tables not claiming more widths that they need.
1309 // Because of this we are careful with uses of WorkRect and InnerClipRect before this point.
1310 if (table->RightMostStretchedColumn != -1)
1311 table->Flags &= ~ImGuiTableFlags_NoHostExtendX;
1312 if (table->Flags & ImGuiTableFlags_NoHostExtendX)
1313 {
1314 table->OuterRect.Max.x = table->WorkRect.Max.x = unused_x1;
1315 table->InnerClipRect.Max.x = ImMin(table->InnerClipRect.Max.x, unused_x1);
1316 }
1317 table->InnerWindow->ParentWorkRect = table->WorkRect;
1318 table->BorderX1 = table->InnerClipRect.Min.x;
1319 table->BorderX2 = table->InnerClipRect.Max.x;
1320
1321 // Setup window's WorkRect.Max.y for GetContentRegionAvail(). Other values will be updated in each TableBeginCell() call.
1322 float window_content_max_y;
1323 if (table->Flags & ImGuiTableFlags_NoHostExtendY)
1324 window_content_max_y = table->OuterRect.Max.y;
1325 else
1326 window_content_max_y = ImMax(table->InnerWindow->ContentRegionRect.Max.y, (table->Flags & ImGuiTableFlags_ScrollY) ? 0.0f : table->OuterRect.Max.y);
1327 table->InnerWindow->WorkRect.Max.y = ImClamp(window_content_max_y - g.Style.CellPadding.y, table->InnerWindow->WorkRect.Min.y, table->InnerWindow->WorkRect.Max.y);
1328
1329 // [Part 9] Allocate draw channels and setup background cliprect
1330 TableSetupDrawChannels(table);
1331
1332 // [Part 10] Hit testing on borders
1333 if (table->Flags & ImGuiTableFlags_Resizable)
1334 TableUpdateBorders(table);
1335 table_instance->LastTopHeadersRowHeight = 0.0f;
1336 table->IsLayoutLocked = true;
1337 table->IsUsingHeaders = false;
1338
1339 // Highlight header
1340 table->HighlightColumnHeader = -1;
1341 if (table->IsContextPopupOpen && table->ContextPopupColumn != -1 && table->InstanceInteracted == table->InstanceCurrent)
1342 table->HighlightColumnHeader = table->ContextPopupColumn;
1343 else if ((table->Flags & ImGuiTableFlags_HighlightHoveredColumn) && table->HoveredColumnBody != -1 && table->HoveredColumnBody != columns_count && table->HoveredColumnBorder == -1)
1344 if (g.ActiveId == 0 || (table->IsActiveIdInTable || g.DragDropActive))
1345 table->HighlightColumnHeader = table->HoveredColumnBody;
1346
1347 // [Part 11] Default context menu
1348 // - To append to this menu: you can call TableBeginContextMenuPopup()/.../EndPopup().
1349 // - To modify or replace this: set table->DisableDefaultContextMenu = true, then call TableBeginContextMenuPopup()/.../EndPopup().
1350 // - You may call TableDrawDefaultContextMenu() with selected flags to display specific sections of the default menu,
1351 // e.g. TableDrawDefaultContextMenu(table, table->Flags & ~ImGuiTableFlags_Hideable) will display everything EXCEPT columns visibility options.
1352 if (table->DisableDefaultContextMenu == false && TableBeginContextMenuPopup(table))
1353 {
1354 TableDrawDefaultContextMenu(table, table->Flags);
1355 EndPopup();
1356 }
1357
1358 // [Part 12] Sanitize and build sort specs before we have a chance to use them for display.
1359 // This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change)
1360 if (table->IsSortSpecsDirty && (table->Flags & ImGuiTableFlags_Sortable))
1361 TableSortSpecsBuild(table);
1362
1363 // [Part 13] Setup inner window decoration size (for scrolling / nav tracking to properly take account of frozen rows/columns)
1364 if (table->FreezeColumnsRequest > 0)
1365 table->InnerWindow->DecoInnerSizeX1 = table->Columns[table->DisplayOrderToIndex[table->FreezeColumnsRequest - 1]].MaxX - table->OuterRect.Min.x; // FIXME-FROZEN
1366 if (table->FreezeRowsRequest > 0)
1367 table->InnerWindow->DecoInnerSizeY1 = table_instance->LastFrozenHeight;
1368 table_instance->LastFrozenHeight = 0.0f;
1369
1370 ImGuiWindow* inner_window = table->InnerWindow;
1371 ImGuiBoxSelectState* bs = &g.BoxSelectState;
1372 if (bs->Window == inner_window && bs->UnclipMode)
1373 TableApplyExternalUnclipRect(table, bs->UnclipRect);
1374
1375 // Initial state
1376 if (table->Flags & ImGuiTableFlags_NoClip)
1377 table->DrawSplitter->SetCurrentChannel(inner_window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP);
1378 else
1379 inner_window->DrawList->PushClipRect(inner_window->InnerClipRect.Min, inner_window->InnerClipRect.Max, false); // FIXME: use table->InnerClipRect?
1380}
1381
1382// When starting a BeginMultiSelect() after table has been layout we update IsRequestOutput fields.
1383void ImGui::TableApplyExternalUnclipRect(ImGuiTable* table, ImRect& rect)
1384{
1385 if (rect.IsInverted())
1386 return;
1387 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
1388 {
1389 ImGuiTableColumn* column = &table->Columns[column_n];
1390 if (!column->IsRequestOutput)
1391 if (rect.Overlaps(ImRect(column->MinX, table->WorkRect.Min.y, column->MaxX, FLT_MAX)))
1392 column->IsRequestOutput = true;
1393 }
1394}
1395
1396// Process hit-testing on resizing borders. Actual size change will be applied in EndTable()
1397// - Set table->HoveredColumnBorder with a short delay/timer to reduce visual feedback noise.
1398void ImGui::TableUpdateBorders(ImGuiTable* table)
1399{
1400 ImGuiContext& g = *GImGui;
1401 IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable);
1402
1403 // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and
1404 // use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not
1405 // really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height).
1406 // Actual columns highlight/render will be performed in EndTable() and not be affected.
1407 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent);
1408 const float hit_half_width = ImTrunc(TABLE_RESIZE_SEPARATOR_HALF_THICKNESS * g.CurrentDpiScale);
1409 const float hit_y1 = (table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight;
1410 const float hit_y2_body = ImMax(table->OuterRect.Max.y, hit_y1 + table_instance->LastOuterHeight - table->AngledHeadersHeight);
1411 const float hit_y2_head = hit_y1 + table_instance->LastTopHeadersRowHeight;
1412
1413 for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
1414 {
1415 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n))
1416 continue;
1417
1418 const int column_n = table->DisplayOrderToIndex[order_n];
1419 ImGuiTableColumn* column = &table->Columns[column_n];
1420 if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_))
1421 continue;
1422
1423 // ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders()
1424 const float border_y2_hit = (table->Flags & ImGuiTableFlags_NoBordersInBody) ? hit_y2_head : hit_y2_body;
1425 if ((table->Flags & ImGuiTableFlags_NoBordersInBody) && table->IsUsingHeaders == false)
1426 continue;
1427
1428 if (!column->IsVisibleX && table->LastResizedColumn != column_n)
1429 continue;
1430
1431 ImGuiID column_id = TableGetColumnResizeID(table, column_n, table->InstanceCurrent);
1432 ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, border_y2_hit);
1433 ItemAdd(hit_rect, column_id, NULL, ImGuiItemFlags_NoNav);
1434 //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100));
1435
1436 bool hovered = false, held = false;
1437 bool pressed = ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_NoNavFocus);
1438 if (pressed && IsMouseDoubleClicked(0))
1439 {
1440 TableSetColumnWidthAutoSingle(table, column_n);
1441 ClearActiveID();
1442 held = false;
1443 }
1444 if (held)
1445 {
1446 if (table->LastResizedColumn == -1)
1447 table->ResizeLockMinContentsX2 = table->RightMostEnabledColumn != -1 ? table->Columns[table->RightMostEnabledColumn].MaxX : -FLT_MAX;
1448 table->ResizedColumn = (ImGuiTableColumnIdx)column_n;
1449 table->InstanceInteracted = table->InstanceCurrent;
1450 }
1451 if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held)
1452 {
1453 table->HoveredColumnBorder = (ImGuiTableColumnIdx)column_n;
1454 SetMouseCursor(ImGuiMouseCursor_ResizeEW);
1455 }
1456 }
1457}
1458
1459void ImGui::EndTable()
1460{
1461 ImGuiContext& g = *GImGui;
1462 ImGuiTable* table = g.CurrentTable;
1463 IM_ASSERT_USER_ERROR_RET(table != NULL, "EndTable() call should only be done while in BeginTable() scope!");
1464
1465 // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some
1466 // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border)
1467 //IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?");
1468
1469 // If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our
1470 // code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc.
1471 if (!table->IsLayoutLocked)
1472 TableUpdateLayout(table);
1473
1474 const ImGuiTableFlags flags = table->Flags;
1475 ImGuiWindow* inner_window = table->InnerWindow;
1476 ImGuiWindow* outer_window = table->OuterWindow;
1477 ImGuiTableTempData* temp_data = table->TempData;
1478 IM_ASSERT(inner_window == g.CurrentWindow && inner_window->ID == temp_data->WindowID);
1479 IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow);
1480
1481 if (table->IsInsideRow)
1482 TableEndRow(table);
1483
1484 // Context menu in columns body
1485 if (flags & ImGuiTableFlags_ContextMenuInBody)
1486 if (table->HoveredColumnBody != -1 && !IsAnyItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
1487 TableOpenContextMenu((int)table->HoveredColumnBody);
1488
1489 // Finalize table height
1490 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent);
1491 inner_window->DC.PrevLineSize = temp_data->HostBackupPrevLineSize;
1492 inner_window->DC.CurrLineSize = temp_data->HostBackupCurrLineSize;
1493 inner_window->DC.CursorMaxPos = temp_data->HostBackupCursorMaxPos;
1494 const float 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)
1495 IM_ASSERT(table->RowPosY2 == inner_window->DC.CursorPos.y);
1496 if (inner_window != outer_window)
1497 inner_window->DC.CursorMaxPos.y = inner_content_max_y;
1498 else if (!(flags & ImGuiTableFlags_NoHostExtendY))
1499 table->OuterRect.Max.y = table->InnerRect.Max.y = ImMax(table->OuterRect.Max.y, inner_content_max_y); // Patch OuterRect/InnerRect height
1500 table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y);
1501 table_instance->LastOuterHeight = table->OuterRect.GetHeight();
1502
1503 // Setup inner scrolling range
1504 // FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window->DC.CursorMaxPos.y,
1505 // but since the later is likely to be impossible to do we'd rather update both axes together.
1506 if (table->Flags & ImGuiTableFlags_ScrollX)
1507 {
1508 const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;
1509 float max_pos_x = inner_window->DC.CursorMaxPos.x;
1510 if (table->RightMostEnabledColumn != -1)
1511 max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border);
1512 if (table->ResizedColumn != -1)
1513 max_pos_x = ImMax(max_pos_x, table->ResizeLockMinContentsX2);
1514 inner_window->DC.CursorMaxPos.x = max_pos_x + table->TempData->AngledHeadersExtraWidth;
1515 }
1516
1517 // Pop clipping rect
1518 if (!(flags & ImGuiTableFlags_NoClip))
1519 inner_window->DrawList->PopClipRect();
1520 inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back();
1521
1522 // Draw borders
1523 if ((flags & ImGuiTableFlags_Borders) != 0)
1524 TableDrawBorders(table);
1525
1526#if 0
1527 // Strip out dummy channel draw calls
1528 // We have no way to prevent user submitting direct ImDrawList calls into a hidden column (but ImGui:: calls will be clipped out)
1529 // Pros: remove draw calls which will have no effect. since they'll have zero-size cliprect they may be early out anyway.
1530 // Cons: making it harder for users watching metrics/debugger to spot the wasted vertices.
1531 if (table->DummyDrawChannel != (ImGuiTableColumnIdx)-1)
1532 {
1533 ImDrawChannel* dummy_channel = &table->DrawSplitter._Channels[table->DummyDrawChannel];
1534 dummy_channel->_CmdBuffer.resize(0);
1535 dummy_channel->_IdxBuffer.resize(0);
1536 }
1537#endif
1538
1539 // Flatten channels and merge draw calls
1540 ImDrawListSplitter* splitter = table->DrawSplitter;
1541 splitter->SetCurrentChannel(inner_window->DrawList, 0);
1542 if ((table->Flags & ImGuiTableFlags_NoClip) == 0)
1543 TableMergeDrawChannels(table);
1544 splitter->Merge(inner_window->DrawList);
1545
1546 // Update ColumnsAutoFitWidth to get us ahead for host using our size to auto-resize without waiting for next BeginTable()
1547 float auto_fit_width_for_fixed = 0.0f;
1548 float auto_fit_width_for_stretched = 0.0f;
1549 float auto_fit_width_for_stretched_min = 0.0f;
1550 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
1551 if (IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n))
1552 {
1553 ImGuiTableColumn* column = &table->Columns[column_n];
1554 float column_width_request = ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !(column->Flags & ImGuiTableColumnFlags_NoResize)) ? column->WidthRequest : TableGetColumnWidthAuto(table, column);
1555 if (column->Flags & ImGuiTableColumnFlags_WidthFixed)
1556 auto_fit_width_for_fixed += column_width_request;
1557 else
1558 auto_fit_width_for_stretched += column_width_request;
1559 if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) && (column->Flags & ImGuiTableColumnFlags_NoResize) != 0)
1560 auto_fit_width_for_stretched_min = ImMax(auto_fit_width_for_stretched_min, column_width_request / (column->StretchWeight / table->ColumnsStretchSumWeights));
1561 }
1562 const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1);
1563 table->ColumnsAutoFitWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount + auto_fit_width_for_fixed + ImMax(auto_fit_width_for_stretched, auto_fit_width_for_stretched_min);
1564
1565 // Update scroll
1566 if ((table->Flags & ImGuiTableFlags_ScrollX) == 0 && inner_window != outer_window)
1567 {
1568 inner_window->Scroll.x = 0.0f;
1569 }
1570 else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceCurrent)
1571 {
1572 // When releasing a column being resized, scroll to keep the resulting column in sight
1573 const float neighbor_width_to_keep_visible = table->MinColumnWidth + table->CellPaddingX * 2.0f;
1574 ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn];
1575 if (column->MaxX < table->InnerClipRect.Min.x)
1576 SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x - neighbor_width_to_keep_visible, 1.0f);
1577 else if (column->MaxX > table->InnerClipRect.Max.x)
1578 SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x + neighbor_width_to_keep_visible, 1.0f);
1579 }
1580
1581 // Apply resizing/dragging at the end of the frame
1582 if (table->ResizedColumn != -1 && table->InstanceCurrent == table->InstanceInteracted)
1583 {
1584 ImGuiTableColumn* column = &table->Columns[table->ResizedColumn];
1585 const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + ImTrunc(TABLE_RESIZE_SEPARATOR_HALF_THICKNESS * g.CurrentDpiScale));
1586 const float new_width = ImTrunc(new_x2 - column->MinX - table->CellSpacingX1 - table->CellPaddingX * 2.0f);
1587 table->ResizedColumnNextWidth = new_width;
1588 }
1589
1590 table->IsActiveIdInTable = (g.ActiveIdIsAlive != 0 && table->IsActiveIdAliveBeforeTable == false);
1591
1592 // Pop from id stack
1593 IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table_instance->TableInstanceID, "Mismatching PushID/PopID!");
1594 IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, "Too many PopItemWidth!");
1595 if (table->InstanceCurrent > 0)
1596 PopID();
1597 PopID();
1598
1599 // Restore window data that we modified
1600 const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;
1601 inner_window->WorkRect = temp_data->HostBackupWorkRect;
1602 inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect;
1603 inner_window->SkipItems = table->HostSkipItems;
1604 outer_window->DC.CursorPos = table->OuterRect.Min;
1605 outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth;
1606 outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize;
1607 outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset;
1608
1609 // Layout in outer window
1610 // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding
1611 // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)
1612 if (inner_window != outer_window)
1613 {
1614 short backup_nav_layers_active_mask = inner_window->DC.NavLayersActiveMask;
1615 inner_window->DC.NavLayersActiveMask |= 1 << table->NavLayer; // So empty table don't appear to navigate differently.
1616 g.CurrentTable = NULL; // To avoid error recovery recursing
1617 EndChild();
1618 g.CurrentTable = table;
1619 inner_window->DC.NavLayersActiveMask = backup_nav_layers_active_mask;
1620 }
1621 else
1622 {
1623 inner_window->DC.TreeDepth--;
1624 ItemSize(table->OuterRect.GetSize());
1625 ItemAdd(table->OuterRect, 0);
1626 }
1627
1628 // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar
1629 if (table->Flags & ImGuiTableFlags_NoHostExtendX)
1630 {
1631 // FIXME-TABLE: Could we remove this section?
1632 // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents
1633 IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);
1634 outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth);
1635 }
1636 else if (temp_data->UserOuterSize.x <= 0.0f)
1637 {
1638 // Some references for this: #7651 + tests "table_reported_size", "table_reported_size_outer" equivalent Y block, #9352
1639 // - 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'
1640 const float outer_content_max_x = table->OuterRect.Min.x + table->ColumnsAutoFitWidth;
1641 const float decoration_size = table->TempData->AngledHeadersExtraWidth + ((inner_window != outer_window) ? inner_window->ScrollbarSizes.x : 0.0f);
1642 outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, outer_content_max_x + decoration_size - temp_data->UserOuterSize.x);
1643 outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, outer_content_max_x + decoration_size));
1644 }
1645 else
1646 {
1647 outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x);
1648 }
1649 if (temp_data->UserOuterSize.y <= 0.0f)
1650 {
1651 // (same comment as above)
1652 const float outer_content_size_y = (inner_window == outer_window) ? (inner_content_max_y - table->InnerRect.Min.y) : (inner_content_max_y - inner_window->DC.CursorStartPos.y);
1653 const float outer_content_max_y = table->OuterRect.Min.y + outer_content_size_y;
1654 const float decoration_size = (inner_window != outer_window ? inner_window->ScrollbarSizes.y : 0.0f);
1655 outer_window->DC.IdealMaxPos.y = ImMax(outer_window->DC.IdealMaxPos.y, outer_content_max_y + decoration_size - temp_data->UserOuterSize.y);
1656 outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, ImMin(table->OuterRect.Max.y, outer_content_max_y + decoration_size));
1657 }
1658 else
1659 {
1660 // OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set)
1661 outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, table->OuterRect.Max.y);
1662 }
1663
1664 // Save settings
1665 if (table->IsSettingsDirty)
1666 TableSaveSettings(table);
1667 table->IsInitializing = false;
1668
1669 // Clear or restore current table, if any
1670 IM_ASSERT(g.CurrentWindow == outer_window && g.CurrentTable == table);
1671 IM_ASSERT(g.TablesTempDataStacked > 0);
1672 temp_data = (--g.TablesTempDataStacked > 0) ? &g.TablesTempData[g.TablesTempDataStacked - 1] : NULL;
1673 g.CurrentTable = temp_data && (temp_data->WindowID == outer_window->ID) ? g.Tables.GetByIndex(temp_data->TableIndex) : NULL;
1674 if (g.CurrentTable)
1675 {
1676 g.CurrentTable->TempData = temp_data;
1677 g.CurrentTable->DrawSplitter = &temp_data->DrawSplitter;
1678 }
1679 outer_window->DC.CurrentTableIdx = g.CurrentTable ? g.Tables.GetIndex(g.CurrentTable) : -1;
1680 NavUpdateCurrentWindowIsScrollPushableX();
1681}
1682
1683// Called in TableUpdateLayout() when initializing/after loading settings.
1684// 'init_mask' specify which fields to initialize.
1685void ImGui::TableInitColumnDefaults(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags init_mask)
1686{
1687 ImGuiTableColumnFlags flags = column->Flags;
1688 if (init_mask & ImGuiTableFlags_Resizable)
1689 {
1690 float init_width_or_weight = column->InitStretchWeightOrWidth;
1691 column->WidthRequest = ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f;
1692 column->StretchWeight = (init_width_or_weight > 0.0f && (flags & ImGuiTableColumnFlags_WidthStretch)) ? init_width_or_weight : -1.0f;
1693 if (init_width_or_weight > 0.0f) // Disable auto-fit if an explicit width/weight has been specified
1694 column->AutoFitQueue = 0x00;
1695 }
1696 if (init_mask & ImGuiTableFlags_Reorderable)
1697 column->DisplayOrder = (ImGuiTableColumnIdx)((table->Flags & ImGuiTableFlags_Reorderable) ? -1 : table->Columns.index_from_ptr(column));
1698 if (init_mask & ImGuiTableFlags_Hideable)
1699 column->IsUserEnabled = column->IsUserEnabledNextFrame = (flags & ImGuiTableColumnFlags_DefaultHide) ? 0 : 1;
1700 if (init_mask & ImGuiTableFlags_Sortable)
1701 {
1702 // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs.
1703 column->SortOrder = (flags & ImGuiTableColumnFlags_DefaultSort) ? 0 : -1;
1704 column->SortDirection = (flags & ImGuiTableColumnFlags_DefaultSort) ? ((flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending)) : (ImS8)ImGuiSortDirection_None;
1705 }
1706}
1707
1708// See "COLUMNS SIZING POLICIES" comments at the top of this file
1709// If (init_width_or_weight <= 0.0f) it is ignored
1710static void TableSetupColumnApply(ImGuiTable* table, int idx, ImGuiID id, ImS16 name_offset, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_data)
1711{
1712 ImGuiTableColumn* column = &table->Columns[idx];
1713
1714 // Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa.
1715 // Give a grace to users of ImGuiTableFlags_ScrollX.
1716 if (table->IsDefaultSizingPolicy && (flags & ImGuiTableColumnFlags_WidthMask_) == 0 && (flags & ImGuiTableFlags_ScrollX) == 0)
1717 IM_ASSERT_USER_ERROR_RET(init_width_or_weight <= 0.0f, "TableSetupColumn(): can only specify width/weight if sizing policy is set explicitly in either Table or Column.");
1718
1719 // When passing a width automatically enforce WidthFixed policy
1720 // (whereas TableSetupColumnFlags would default to WidthAuto if table is not resizable)
1721 if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0 && init_width_or_weight > 0.0f)
1722 if ((table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedFit || (table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame)
1723 flags |= ImGuiTableColumnFlags_WidthFixed;
1724 if (flags & ImGuiTableColumnFlags_AngledHeader)
1725 {
1726 flags |= ImGuiTableColumnFlags_NoHeaderLabel;
1727 table->AngledHeadersCount++;
1728 }
1729
1730 TableSetupColumnFlags(table, column, flags);
1731 column->ID = id;
1732 column->UserData = user_data;
1733 column->NameOffset = name_offset;
1734 column->InitStretchWeightOrWidth = init_width_or_weight;
1735}
1736
1737void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_data)
1738{
1739 ImGuiContext& g = *GImGui;
1740 ImGuiTable* table = g.CurrentTable;
1741 IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!");
1742 IM_ASSERT_USER_ERROR_RET(table->DeclColumnsCount < table->ColumnsCount, "TableSetupColumn(): called too many times!");
1743 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.
1744 IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && "Illegal to pass StatusMask values to TableSetupColumn()");
1745
1746 // Store name (append with zero-terminator in contiguous buffer)
1747 // FIXME: If we recorded the number of \n in names we could compute header row height
1748 ImS16 name_offset = -1;
1749 if (label != NULL && label[0] != 0)
1750 {
1751 name_offset = (ImS16)table->ColumnsNames.size();
1752 table->ColumnsNames.append(label, label + ImStrlen(label) + 1);
1753 }
1754 const ImGuiID column_id = (label != NULL && label[0] != 0) ? ImHashStr(label) : 0;
1755
1756 // When ID changed or a column moved: defer the request until layout where we will process full reconcile.
1757 const int column_idx = table->DeclColumnsCount++;
1758 ImGuiTableColumn* column = &table->Columns[column_idx];
1759
1760 // If topology change goes into reconcile mode
1761 if (table->IsReconcileMode == false && column->ID != column_id)
1762 {
1763 table->IsReconcileMode = true;
1764 table->TempData->ReconcileColumnsRequests.reserve(table->ColumnsCount - column_idx);
1765 }
1766
1767 // Fast/common path
1768 if (table->IsReconcileMode == false)
1769 {
1770 TableSetupColumnApply(table, column_idx, column_id, name_offset, flags, init_width_or_weight, user_data);
1771 column->IsNeedReconcileSrc = column->IsNeedReconcileDst = false;
1772 if (column_idx < table->TempData->OldColumnsData.size())
1773 table->TempData->OldColumnsData[column_idx].IsNeedReconcileSrc = false;
1774 return;
1775 }
1776
1777 // Reconcile path: defer applying data to TableUpdateLayout() -> TableReconcileMovedColumns() -> TableSetupColumnApply().
1778 // On column count change: search the previous columns:
1779 // - the live Columns[] array is truncated on shrink, so a moved column may only exist in old data.
1780 // - the live Columns[] array may already be partially reset.
1781 table->TempData->ReconcileColumnsRequests.push_back(ImGuiTableReconcileColumnData());
1782 ImGuiTableReconcileColumnData& reconcile_data = table->TempData->ReconcileColumnsRequests.back();
1783 reconcile_data.ID = column_id;
1784 reconcile_data.NameOffset = name_offset;
1785 reconcile_data.Flags = flags;
1786 reconcile_data.InitWidthOrWeight = init_width_or_weight;
1787 reconcile_data.UserData = user_data;
1788 reconcile_data.ColumnNewIdx = (ImGuiTableColumnIdx)column_idx;
1789 reconcile_data.ColumnOldIdx = (ImGuiTableColumnIdx)-1;
1790 column->NameOffset = name_offset; // Allow TableGetColumnName() to work before layout
1791 column->IsNeedReconcileSrc = column->IsNeedReconcileDst = true;
1792}
1793
1794// NB: This was written to be similar to the logic in TableLoadSettingsForColumns().
1795void ImGui::TableReconcileColumns(ImGuiTable* table)
1796{
1797 ImGuiContext& g = *GImGui;
1798 ImGuiTableTempData* temp_data = table->TempData;
1799 IM_UNUSED(g);
1800 IMGUI_DEBUG_LOG_TABLE("[table] Reconcile columns for table 0x%08X\n", table->ID);
1801
1802 ImSpan<ImGuiTableColumn>& dst_columns = table->Columns;
1803 ImSpan<ImGuiTableColumn>& src_columns = table->TempData->OldColumnsData.empty() ? table->Columns : table->TempData->OldColumnsData;
1804
1805 // Find matches for named columns.
1806 int matches = 0;
1807 ImVector<ImGuiTableReconcileColumnData>& reconcile_requests = temp_data->ReconcileColumnsRequests;
1808 for (ImGuiTableReconcileColumnData& reconcile_data : reconcile_requests)
1809 if (reconcile_data.ID != 0)
1810 for (ImGuiTableColumn& src_column : src_columns)
1811 if (src_column.ID == reconcile_data.ID && src_column.IsNeedReconcileSrc)
1812 {
1813 ImGuiTableColumn& dst_column = dst_columns[reconcile_data.ColumnNewIdx];
1814 IM_ASSERT(src_column.IsNeedReconcileSrc && dst_column.IsNeedReconcileDst);
1815 src_column.IsNeedReconcileSrc = dst_column.IsNeedReconcileDst = false;
1816 reconcile_data.ColumnOldIdx = (ImGuiTableColumnIdx)src_columns.index_from_ptr(&src_column);
1817 reconcile_data.ColumnOldData = src_column;
1818 matches++;
1819 break;
1820 }
1821
1822 // Remaining entries are matched sequentially.
1823 int dst_idx = 0; // index in reconcile array
1824 if (matches != reconcile_requests.Size)
1825 for (ImGuiTableColumn& src_column : src_columns)
1826 {
1827 if (!src_column.IsNeedReconcileSrc)
1828 continue;
1829 while (dst_idx < reconcile_requests.Size && reconcile_requests[dst_idx].ColumnOldIdx != (ImGuiTableColumnIdx)-1)
1830 dst_idx++;
1831 if (dst_idx == reconcile_requests.Size)
1832 break;
1833 ImGuiTableReconcileColumnData& reconcile_data = reconcile_requests[dst_idx];
1834 ImGuiTableColumn& dst_column = dst_columns[reconcile_data.ColumnNewIdx];
1835 IM_ASSERT(src_column.IsNeedReconcileSrc && dst_column.IsNeedReconcileDst);
1836 src_column.IsNeedReconcileSrc = dst_column.IsNeedReconcileDst = false;
1837 reconcile_data.ColumnOldIdx = (ImGuiTableColumnIdx)src_columns.index_from_ptr(&src_column);
1838 reconcile_data.ColumnOldData = src_column;
1839 }
1840
1841 // Apply in the final pass. Because it is possible that src_columns == table->Columns we went through a temporary copy.
1842 for (ImGuiTableReconcileColumnData& reconcile_data : reconcile_requests)
1843 {
1844 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)
1845 TableSetupColumnApply(table, reconcile_data.ColumnNewIdx, reconcile_data.ID, reconcile_data.NameOffset, reconcile_data.Flags, reconcile_data.InitWidthOrWeight, reconcile_data.UserData);
1846 IMGUI_DEBUG_LOG_TABLE("[table] - old %d -> new %d \"%s\"\n", reconcile_data.ColumnOldIdx, reconcile_data.ColumnNewIdx, TableGetColumnName(table, reconcile_data.ColumnNewIdx)); // Log at the end so NameOffset was copied.
1847 }
1848 TableFixDisplayOrder(table);
1849 table->IsSettingsDirty = true; // FIXME-RECONCILE: Necessary?
1850 table->IsReconcileMode = false;
1851 reconcile_requests.resize(0); // GC-ed once in NewFrame()
1852}
1853
1854// [Public]
1855void ImGui::TableSetupScrollFreeze(int columns, int rows)
1856{
1857 ImGuiContext& g = *GImGui;
1858 ImGuiTable* table = g.CurrentTable;
1859 IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!");
1860 IM_ASSERT(table->IsLayoutLocked == false && "TableSetupColumn(): need to call before first row!");
1861 IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS);
1862 IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit
1863
1864 table->FreezeColumnsRequest = (table->Flags & ImGuiTableFlags_ScrollX) ? (ImGuiTableColumnIdx)ImMin(columns, table->ColumnsCount) : 0;
1865 table->FreezeColumnsCount = (table->InnerWindow->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0;
1866 table->FreezeRowsRequest = (table->Flags & ImGuiTableFlags_ScrollY) ? (ImGuiTableColumnIdx)rows : 0;
1867 table->FreezeRowsCount = (table->InnerWindow->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0;
1868 table->IsUnfrozenRows = (table->FreezeRowsCount == 0); // Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it.b
1869}
1870
1871//-----------------------------------------------------------------------------
1872// [SECTION] Tables: Simple accessors
1873//-----------------------------------------------------------------------------
1874// - TableGetColumnCount()
1875// - TableGetColumnName()
1876// - TableGetColumnName() [Internal]
1877// - TableSetColumnEnabled()
1878// - TableGetColumnFlags()
1879// - TableGetCellBgRect() [Internal]
1880// - TableGetColumnResizeID() [Internal]
1881// - TableGetHoveredColumn() [Internal]
1882// - TableGetHoveredRow() [Internal]
1883// - TableSetBgColor()
1884//-----------------------------------------------------------------------------
1885
1886int ImGui::TableGetColumnCount()
1887{
1888 ImGuiContext& g = *GImGui;
1889 ImGuiTable* table = g.CurrentTable;
1890 return table ? table->ColumnsCount : 0;
1891}
1892
1893const char* ImGui::TableGetColumnName(int column_n)
1894{
1895 ImGuiContext& g = *GImGui;
1896 ImGuiTable* table = g.CurrentTable;
1897 if (!table)
1898 return NULL;
1899 if (column_n < 0)
1900 column_n = table->CurrentColumn;
1901 return TableGetColumnName(table, column_n);
1902}
1903
1904const char* ImGui::TableGetColumnName(const ImGuiTable* table, int column_n)
1905{
1906 if (table->IsLayoutLocked == false && column_n >= table->DeclColumnsCount)
1907 return ""; // NameOffset is invalid at this point
1908 const ImGuiTableColumn* column = &table->Columns[column_n];
1909 if (column->NameOffset == -1)
1910 return "";
1911 return &table->ColumnsNames.Buf[column->NameOffset];
1912}
1913
1914// Change user accessible enabled/disabled state of a column (often perceived as "showing/hiding" from users point of view)
1915// 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)
1916// - Require table to have the ImGuiTableFlags_Hideable flag because we are manipulating user accessible state.
1917// - Request will be applied during next layout, which happens on the first call to TableNextRow() after BeginTable().
1918// - For the getter you can test (TableGetColumnFlags() & ImGuiTableColumnFlags_IsEnabled) != 0.
1919// - Alternative: the ImGuiTableColumnFlags_Disabled is an overriding/master disable flag which will also hide the column from context menu.
1920void ImGui::TableSetColumnEnabled(int column_n, bool enabled)
1921{
1922 ImGuiContext& g = *GImGui;
1923 ImGuiTable* table = g.CurrentTable;
1924 IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!");
1925 IM_ASSERT(table->Flags & ImGuiTableFlags_Hideable); // See comments above
1926 if (column_n < 0)
1927 column_n = table->CurrentColumn;
1928 IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
1929 ImGuiTableColumn* column = &table->Columns[column_n];
1930 column->IsUserEnabledNextFrame = enabled;
1931}
1932
1933// We allow querying for an extra column in order to poll the IsHovered state of the right-most section
1934ImGuiTableColumnFlags ImGui::TableGetColumnFlags(int column_n)
1935{
1936 ImGuiContext& g = *GImGui;
1937 ImGuiTable* table = g.CurrentTable;
1938 if (!table)
1939 return ImGuiTableColumnFlags_None;
1940 if (column_n < 0)
1941 column_n = table->CurrentColumn;
1942 if (column_n == table->ColumnsCount)
1943 return (table->HoveredColumnBody == column_n) ? ImGuiTableColumnFlags_IsHovered : ImGuiTableColumnFlags_None;
1944 return table->Columns[column_n].Flags;
1945}
1946
1947// Return the cell rectangle based on currently known height.
1948// - Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations.
1949// 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.
1950// - Important: if ImGuiTableFlags_PadOuterX is set but ImGuiTableFlags_PadInnerX is not set, the outer-most left and right
1951// columns report a small offset so their CellBgRect can extend up to the outer border.
1952// FIXME: But the rendering code in TableEndRow() nullifies that with clamping required for scrolling.
1953ImRect ImGui::TableGetCellBgRect(const ImGuiTable* table, int column_n)
1954{
1955 const ImGuiTableColumn* column = &table->Columns[column_n];
1956 float x1 = column->MinX;
1957 float x2 = column->MaxX;
1958 //if (column->PrevEnabledColumn == -1)
1959 // x1 -= table->OuterPaddingX;
1960 //if (column->NextEnabledColumn == -1)
1961 // x2 += table->OuterPaddingX;
1962 x1 = ImMax(x1, table->WorkRect.Min.x);
1963 x2 = ImMin(x2, table->WorkRect.Max.x);
1964 return ImRect(x1, table->RowPosY1, x2, table->RowPosY2);
1965}
1966
1967// Return the resizing ID for the right-side of the given column.
1968ImGuiID ImGui::TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no)
1969{
1970 IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
1971 ImGuiID instance_id = TableGetInstanceID(table, instance_no);
1972 return instance_id + 1 + column_n; // FIXME: #6140: still not ideal
1973}
1974
1975// Return -1 when table is not hovered. return columns_count if hovering the unused space at the right of the right-most visible column.
1976int ImGui::TableGetHoveredColumn()
1977{
1978 ImGuiContext& g = *GImGui;
1979 ImGuiTable* table = g.CurrentTable;
1980 if (!table)
1981 return -1;
1982 return (int)table->HoveredColumnBody;
1983}
1984
1985// Return -1 when table is not hovered. Return maxrow+1 if in table but below last submitted row.
1986// *IMPORTANT* Unlike TableGetHoveredColumn(), this has a one frame latency in updating the value.
1987// This difference with is the reason why this is not public yet.
1988int ImGui::TableGetHoveredRow()
1989{
1990 ImGuiContext& g = *GImGui;
1991 ImGuiTable* table = g.CurrentTable;
1992 if (!table)
1993 return -1;
1994 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent);
1995 return (int)table_instance->HoveredRowLast;
1996}
1997
1998void ImGui::TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n)
1999{
2000 ImGuiContext& g = *GImGui;
2001 ImGuiTable* table = g.CurrentTable;
2002 IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!");
2003 IM_ASSERT(target != ImGuiTableBgTarget_None);
2004
2005 if (color == IM_COL32_DISABLE)
2006 color = 0;
2007
2008 // We cannot draw neither the cell or row background immediately as we don't know the row height at this point in time.
2009 switch (target)
2010 {
2011 case ImGuiTableBgTarget_CellBg:
2012 {
2013 if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard
2014 return;
2015 if (column_n == -1)
2016 column_n = table->CurrentColumn;
2017 if (!IM_BITARRAY_TESTBIT(table->VisibleMaskByIndex, column_n))
2018 return;
2019 if (table->RowCellDataCurrent < 0 || table->RowCellData[table->RowCellDataCurrent].Column != column_n)
2020 table->RowCellDataCurrent++;
2021 ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCurrent];
2022 cell_data->BgColor = color;
2023 cell_data->Column = (ImGuiTableColumnIdx)column_n;
2024 break;
2025 }
2026 case ImGuiTableBgTarget_RowBg0:
2027 case ImGuiTableBgTarget_RowBg1:
2028 {
2029 if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard
2030 return;
2031 IM_ASSERT(column_n == -1);
2032 int bg_idx = (target == ImGuiTableBgTarget_RowBg1) ? 1 : 0;
2033 table->RowBgColor[bg_idx] = color;
2034 break;
2035 }
2036 default:
2037 IM_ASSERT(0);
2038 }
2039}
2040
2041//-------------------------------------------------------------------------
2042// [SECTION] Tables: Row changes
2043//-------------------------------------------------------------------------
2044// - TableGetRowIndex()
2045// - TableNextRow()
2046// - TableBeginRow() [Internal]
2047// - TableEndRow() [Internal]
2048//-------------------------------------------------------------------------
2049
2050// [Public] Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows
2051int ImGui::TableGetRowIndex()
2052{
2053 ImGuiContext& g = *GImGui;
2054 ImGuiTable* table = g.CurrentTable;
2055 if (!table)
2056 return 0;
2057 return table->CurrentRow;
2058}
2059
2060// [Public] Starts into the first cell of a new row
2061void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float row_min_height)
2062{
2063 ImGuiContext& g = *GImGui;
2064 ImGuiTable* table = g.CurrentTable;
2065
2066 if (!table->IsLayoutLocked)
2067 TableUpdateLayout(table);
2068 if (table->IsInsideRow)
2069 TableEndRow(table);
2070
2071 table->LastRowFlags = table->RowFlags;
2072 table->RowFlags = row_flags;
2073 table->RowCellPaddingY = g.Style.CellPadding.y;
2074 table->RowMinHeight = row_min_height;
2075 TableBeginRow(table);
2076
2077 // We honor min_row_height requested by user, but cannot guarantee per-row maximum height,
2078 // because that would essentially require a unique clipping rectangle per-cell.
2079 table->RowPosY2 += table->RowCellPaddingY * 2.0f;
2080 table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + row_min_height);
2081
2082 // Disable output until user calls TableNextColumn()
2083 table->InnerWindow->SkipItems = true;
2084}
2085
2086// [Internal] Only called by TableNextRow()
2087void ImGui::TableBeginRow(ImGuiTable* table)
2088{
2089 ImGuiWindow* window = table->InnerWindow;
2090 IM_ASSERT(!table->IsInsideRow);
2091
2092 // New row
2093 table->CurrentRow++;
2094 table->CurrentColumn = -1;
2095 table->RowBgColor[0] = table->RowBgColor[1] = IM_COL32_DISABLE;
2096 table->RowCellDataCurrent = -1;
2097 table->IsInsideRow = true;
2098
2099 // Begin frozen rows
2100 float next_y1 = table->RowPosY2;
2101 if (table->CurrentRow == 0 && table->FreezeRowsCount > 0)
2102 next_y1 = window->DC.CursorPos.y = table->OuterRect.Min.y;
2103
2104 table->RowPosY1 = table->RowPosY2 = next_y1;
2105 table->RowTextBaseline = 0.0f;
2106 table->RowIndentOffsetX = window->DC.Indent.x - table->HostIndentX; // Lock indent
2107
2108 window->DC.PrevLineTextBaseOffset = 0.0f;
2109 window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + table->RowCellPaddingY); // This allows users to call SameLine() to share LineSize between columns.
2110 window->DC.PrevLineSize = window->DC.CurrLineSize = ImVec2(0.0f, 0.0f); // This allows users to call SameLine() to share LineSize between columns, and to call it from first column too.
2111 window->DC.IsSameLine = window->DC.IsSetPos = false;
2112 window->DC.CursorMaxPos.y = next_y1;
2113
2114 // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging.
2115 if (table->RowFlags & ImGuiTableRowFlags_Headers)
2116 {
2117 TableSetBgColor(ImGuiTableBgTarget_RowBg0, GetColorU32(ImGuiCol_TableHeaderBg));
2118 if (table->CurrentRow == 0)
2119 table->IsUsingHeaders = true;
2120 }
2121}
2122
2123// [Internal] Called by TableNextRow()
2124void ImGui::TableEndRow(ImGuiTable* table)
2125{
2126 ImGuiContext& g = *GImGui;
2127 ImGuiWindow* window = g.CurrentWindow;
2128 IM_ASSERT(window == table->InnerWindow);
2129 IM_ASSERT(table->IsInsideRow);
2130
2131 if (table->CurrentColumn != -1)
2132 {
2133 TableEndCell(table);
2134 table->CurrentColumn = -1;
2135 }
2136
2137 // Logging
2138 if (g.LogEnabled)
2139 LogRenderedText(NULL, "|");
2140
2141 // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is
2142 // likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding.
2143 window->DC.CursorPos.y = table->RowPosY2;
2144
2145 // Row background fill
2146 const float bg_y1 = table->RowPosY1;
2147 const float bg_y2 = table->RowPosY2;
2148 const bool unfreeze_rows_actual = (table->CurrentRow + 1 == table->FreezeRowsCount);
2149 const bool unfreeze_rows_request = (table->CurrentRow + 1 == table->FreezeRowsRequest);
2150 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent);
2151 if ((table->RowFlags & ImGuiTableRowFlags_Headers) && (table->CurrentRow == 0 || (table->LastRowFlags & ImGuiTableRowFlags_Headers)))
2152 table_instance->LastTopHeadersRowHeight += bg_y2 - bg_y1;
2153
2154 const bool is_visible = (bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y);
2155 if (is_visible)
2156 {
2157 // Update data for TableGetHoveredRow()
2158 if (table->HoveredColumnBody != -1 && g.IO.MousePos.y >= bg_y1 && g.IO.MousePos.y < bg_y2 && table_instance->HoveredRowNext < 0)
2159 table_instance->HoveredRowNext = table->CurrentRow;
2160
2161 // Decide of background color for the row
2162 ImU32 bg_col0 = 0;
2163 ImU32 bg_col1 = 0;
2164 if (table->RowBgColor[0] != IM_COL32_DISABLE)
2165 bg_col0 = table->RowBgColor[0];
2166 else if (table->Flags & ImGuiTableFlags_RowBg)
2167 bg_col0 = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg);
2168 if (table->RowBgColor[1] != IM_COL32_DISABLE)
2169 bg_col1 = table->RowBgColor[1];
2170
2171 // Decide of top border color
2172 ImU32 top_border_col = 0;
2173 const float border_size = TABLE_BORDER_SIZE;
2174 if (table->CurrentRow > 0 && (table->Flags & ImGuiTableFlags_BordersInnerH))
2175 top_border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight;
2176
2177 const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0;
2178 const bool draw_strong_bottom_border = unfreeze_rows_actual;
2179 if ((bg_col0 | bg_col1 | top_border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color)
2180 {
2181 // In theory we could call SetWindowClipRectBeforeSetChannel() but since we know TableEndRow() is
2182 // always followed by a change of clipping rectangle we perform the smallest overwrite possible here.
2183 if ((table->Flags & ImGuiTableFlags_NoClip) == 0)
2184 window->DrawList->_CmdHeader.ClipRect = table->Bg0ClipRectForDrawCmd.ToVec4();
2185 table->DrawSplitter->SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_BG0);
2186 }
2187
2188 // Draw row background
2189 // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle
2190 if (bg_col0 || bg_col1)
2191 {
2192 ImRect row_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2);
2193 row_rect.ClipWith(table->BgClipRect);
2194 if (bg_col0 != 0 && row_rect.Min.y < row_rect.Max.y)
2195 window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col0);
2196 if (bg_col1 != 0 && row_rect.Min.y < row_rect.Max.y)
2197 window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col1);
2198 }
2199
2200 // Draw cell background color
2201 if (draw_cell_bg_color)
2202 {
2203 ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCurrent];
2204 for (ImGuiTableCellData* cell_data = &table->RowCellData[0]; cell_data <= cell_data_end; cell_data++)
2205 {
2206 // As we render the BG here we need to clip things (for layout we would not)
2207 // FIXME: This cancels the OuterPadding addition done by TableGetCellBgRect(), need to keep it while rendering correctly while scrolling.
2208 const ImGuiTableColumn* column = &table->Columns[cell_data->Column];
2209 ImRect cell_bg_rect = TableGetCellBgRect(table, cell_data->Column);
2210 cell_bg_rect.ClipWith(table->BgClipRect);
2211 cell_bg_rect.Min.x = ImMax(cell_bg_rect.Min.x, column->ClipRect.Min.x); // So that first column after frozen one gets clipped when scrolling
2212 cell_bg_rect.Max.x = ImMin(cell_bg_rect.Max.x, column->MaxX);
2213 if (cell_bg_rect.Min.y < cell_bg_rect.Max.y)
2214 window->DrawList->AddRectFilled(cell_bg_rect.Min, cell_bg_rect.Max, cell_data->BgColor);
2215 }
2216 }
2217
2218 // Draw top border
2219 if (top_border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y)
2220 window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y1, top_border_col, border_size);
2221
2222 // Draw bottom border at the row unfreezing mark (always strong)
2223 if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y)
2224 window->DrawList->AddLineH(table->BorderX1, table->BorderX2, bg_y2, table->BorderColorStrong, border_size);
2225 }
2226
2227 // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle)
2228 // - We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark
2229 // end of row and get the new cursor position.
2230 if (unfreeze_rows_request)
2231 {
2232 IM_ASSERT(table->FreezeRowsRequest > 0);
2233 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2234 table->Columns[column_n].NavLayerCurrent = table->NavLayer;
2235 const float y0 = ImMax(table->RowPosY2 + 1, table->InnerClipRect.Min.y);
2236 table_instance->LastFrozenHeight = y0 - table->OuterRect.Min.y;
2237
2238 if (unfreeze_rows_actual)
2239 {
2240 IM_ASSERT(table->IsUnfrozenRows == false);
2241 table->IsUnfrozenRows = true;
2242
2243 // BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect
2244 table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(y0, table->InnerClipRect.Max.y);
2245 table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = table->InnerClipRect.Max.y;
2246 table->Bg2DrawChannelCurrent = table->Bg2DrawChannelUnfrozen;
2247 IM_ASSERT(table->Bg2ClipRectForDrawCmd.Min.y <= table->Bg2ClipRectForDrawCmd.Max.y);
2248
2249 float row_height = table->RowPosY2 - table->RowPosY1;
2250 table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y;
2251 table->RowPosY1 = table->RowPosY2 - row_height;
2252 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2253 {
2254 ImGuiTableColumn* column = &table->Columns[column_n];
2255 column->DrawChannelCurrent = column->DrawChannelUnfrozen;
2256 column->ClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y;
2257 }
2258
2259 // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y
2260 SetWindowClipRectBeforeSetChannel(window, table->Columns[0].ClipRect);
2261 table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[0].DrawChannelCurrent);
2262 }
2263 }
2264
2265 if (!(table->RowFlags & ImGuiTableRowFlags_Headers))
2266 table->RowBgColorCounter++;
2267 table->IsInsideRow = false;
2268}
2269
2270//-------------------------------------------------------------------------
2271// [SECTION] Tables: Columns changes
2272//-------------------------------------------------------------------------
2273// - TableGetColumnIndex()
2274// - TableSetColumnIndex()
2275// - TableNextColumn()
2276// - TableBeginCell() [Internal]
2277// - TableEndCell() [Internal]
2278//-------------------------------------------------------------------------
2279
2280int ImGui::TableGetColumnIndex()
2281{
2282 ImGuiContext& g = *GImGui;
2283 ImGuiTable* table = g.CurrentTable;
2284 if (!table)
2285 return 0;
2286 return table->CurrentColumn;
2287}
2288
2289// [Public] Append into a specific column
2290bool ImGui::TableSetColumnIndex(int column_n)
2291{
2292 ImGuiContext& g = *GImGui;
2293 ImGuiTable* table = g.CurrentTable;
2294 if (!table)
2295 return false;
2296
2297 if (table->CurrentColumn != column_n)
2298 {
2299 if (table->CurrentColumn != -1)
2300 TableEndCell(table);
2301 IM_ASSERT_USER_ERROR_RETV(column_n >= 0 && column_n < table->ColumnsCount, false, "TableSetColumnIndex() invalid column index!");
2302 TableBeginCell(table, column_n);
2303 }
2304
2305 // Return whether the column is visible. User may choose to skip submitting items based on this return value,
2306 // however they shouldn't skip submitting for columns that may have the tallest contribution to row height.
2307 return table->Columns[column_n].IsRequestOutput;
2308}
2309
2310// [Public] Append into the next column, wrap and create a new row when already on last column
2311bool ImGui::TableNextColumn()
2312{
2313 ImGuiContext& g = *GImGui;
2314 ImGuiTable* table = g.CurrentTable;
2315 if (!table)
2316 return false;
2317
2318 if (table->IsInsideRow && table->CurrentColumn + 1 < table->ColumnsCount)
2319 {
2320 if (table->CurrentColumn != -1)
2321 TableEndCell(table);
2322 TableBeginCell(table, table->CurrentColumn + 1);
2323 }
2324 else
2325 {
2326 TableNextRow();
2327 TableBeginCell(table, 0);
2328 }
2329
2330 // Return whether the column is visible. User may choose to skip submitting items based on this return value,
2331 // however they shouldn't skip submitting for columns that may have the tallest contribution to row height.
2332 return table->Columns[table->CurrentColumn].IsRequestOutput;
2333}
2334
2335
2336// [Internal] Called by TableSetColumnIndex()/TableNextColumn()
2337// This is called very frequently, so we need to be mindful of unnecessary overhead.
2338// FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns.
2339void ImGui::TableBeginCell(ImGuiTable* table, int column_n)
2340{
2341 ImGuiContext& g = *GImGui;
2342 ImGuiTableColumn* column = &table->Columns[column_n];
2343 ImGuiWindow* window = table->InnerWindow;
2344 table->CurrentColumn = column_n;
2345
2346 // Start position is roughly ~~ CellRect.Min + CellPadding + Indent
2347 float start_x = column->WorkMinX;
2348 if (column->Flags & ImGuiTableColumnFlags_IndentEnable)
2349 start_x += table->RowIndentOffsetX; // ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row.
2350
2351 window->DC.CursorPos.x = start_x;
2352 window->DC.CursorPos.y = table->RowPosY1 + table->RowCellPaddingY;
2353 window->DC.CursorMaxPos.x = window->DC.CursorPos.x;
2354 window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT
2355 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x; // PrevLine.y is preserved. This allows users to call SameLine() to share LineSize between columns.
2356 window->DC.CurrLineTextBaseOffset = table->RowTextBaseline;
2357 window->DC.NavLayerCurrent = (ImGuiNavLayer)column->NavLayerCurrent;
2358
2359 // Note how WorkRect.Max.y is only set once during layout
2360 window->WorkRect.Min.y = window->DC.CursorPos.y;
2361 window->WorkRect.Min.x = column->WorkMinX;
2362 window->WorkRect.Max.x = column->WorkMaxX;
2363 window->DC.ItemWidth = column->ItemWidth;
2364
2365 window->SkipItems = column->IsSkipItems;
2366 if (column->IsSkipItems)
2367 {
2368 g.LastItemData.ID = 0;
2369 g.LastItemData.StatusFlags = 0;
2370 }
2371
2372 // Also see TablePushColumnChannel()
2373 if (table->Flags & ImGuiTableFlags_NoClip)
2374 {
2375 // FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed.
2376 table->DrawSplitter->SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP);
2377 //IM_ASSERT(table->DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP);
2378 }
2379 else
2380 {
2381 // FIXME-TABLE: Could avoid this if draw channel is dummy channel?
2382 SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
2383 table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
2384 }
2385
2386 // Logging
2387 if (g.LogEnabled && !column->IsSkipItems)
2388 {
2389 LogRenderedText(&window->DC.CursorPos, "|");
2390 g.LogLinePosY = FLT_MAX;
2391 }
2392}
2393
2394// [Internal] Called by TableNextRow()/TableSetColumnIndex()/TableNextColumn()
2395void ImGui::TableEndCell(ImGuiTable* table)
2396{
2397 ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
2398 ImGuiWindow* window = table->InnerWindow;
2399
2400 if (window->DC.IsSetPos)
2401 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
2402
2403 // Report maximum position so we can infer content size per column.
2404 float* p_max_pos_x;
2405 if (table->RowFlags & ImGuiTableRowFlags_Headers)
2406 p_max_pos_x = &column->ContentMaxXHeadersUsed; // Useful in case user submit contents in header row that is not a TableHeader() call
2407 else
2408 p_max_pos_x = table->IsUnfrozenRows ? &column->ContentMaxXUnfrozen : &column->ContentMaxXFrozen;
2409 *p_max_pos_x = ImMax(*p_max_pos_x, window->DC.CursorMaxPos.x);
2410 if (column->IsEnabled)
2411 table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y + table->RowCellPaddingY);
2412 column->ItemWidth = window->DC.ItemWidth;
2413
2414 // Propagate text baseline for the entire row
2415 // FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one.
2416 table->RowTextBaseline = ImMax(table->RowTextBaseline, window->DC.PrevLineTextBaseOffset);
2417}
2418
2419//-------------------------------------------------------------------------
2420// [SECTION] Tables: Columns width management
2421//-------------------------------------------------------------------------
2422// - TableGetMaxColumnWidth() [Internal]
2423// - TableGetColumnWidthAuto() [Internal]
2424// - TableSetColumnWidth()
2425// - TableSetColumnWidthAutoSingle() [Internal]
2426// - TableSetColumnWidthAutoAll() [Internal]
2427// - TableUpdateColumnsWeightFromWidth() [Internal]
2428//-------------------------------------------------------------------------
2429// Note that actual columns widths are computed in TableUpdateLayout().
2430//-------------------------------------------------------------------------
2431
2432// Maximum column content width given current layout. Use column->MinX so this value differs on a per-column basis.
2433float ImGui::TableCalcMaxColumnWidth(const ImGuiTable* table, int column_n)
2434{
2435 const ImGuiTableColumn* column = &table->Columns[column_n];
2436 float max_width = FLT_MAX;
2437 const float min_column_distance = table->MinColumnWidth + table->CellPaddingX * 2.0f + table->CellSpacingX1 + table->CellSpacingX2;
2438 if (table->Flags & ImGuiTableFlags_ScrollX)
2439 {
2440 // Frozen columns can't reach beyond visible width else scrolling will naturally break.
2441 // (we use DisplayOrder as within a set of multiple frozen column reordering is possible)
2442 if (column->DisplayOrder < table->FreezeColumnsRequest)
2443 {
2444 max_width = (table->InnerClipRect.Max.x - (table->FreezeColumnsRequest - column->DisplayOrder) * min_column_distance) - column->MinX;
2445 max_width = max_width - table->OuterPaddingX - table->CellPaddingX - table->CellSpacingX2;
2446 }
2447 }
2448 else if ((table->Flags & ImGuiTableFlags_NoKeepColumnsVisible) == 0)
2449 {
2450 // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make
2451 // sure they are all visible. Because of this we also know that all of the columns will always fit in
2452 // table->WorkRect and therefore in table->InnerRect (because ScrollX is off)
2453 // FIXME-TABLE: This is solved incorrectly but also quite a difficult problem to fix as we also want ClipRect width to match.
2454 // See "table_width_distrib" and "table_width_keep_visible" tests
2455 max_width = table->WorkRect.Max.x - (table->ColumnsEnabledCount - column->IndexWithinEnabledSet - 1) * min_column_distance - column->MinX;
2456 //max_width -= table->CellSpacingX1;
2457 max_width -= table->CellSpacingX2;
2458 max_width -= table->CellPaddingX * 2.0f;
2459 max_width -= table->OuterPaddingX;
2460 }
2461 return max_width;
2462}
2463
2464// Note this is meant to be stored in column->WidthAuto, please generally use the WidthAuto field
2465float ImGui::TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column)
2466{
2467 const float content_width_body = ImMax(column->ContentMaxXFrozen, column->ContentMaxXUnfrozen) - column->WorkMinX;
2468 const float content_width_headers = column->ContentMaxXHeadersIdeal - column->WorkMinX;
2469 float width_auto = content_width_body;
2470 if (!(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth))
2471 width_auto = ImMax(width_auto, content_width_headers);
2472
2473 // Non-resizable fixed columns preserve their requested width
2474 if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f)
2475 if (!(table->Flags & ImGuiTableFlags_Resizable) || (column->Flags & ImGuiTableColumnFlags_NoResize))
2476 width_auto = column->InitStretchWeightOrWidth;
2477
2478 return ImMax(width_auto, table->MinColumnWidth);
2479}
2480
2481// 'width' = inner column width, without padding
2482void ImGui::TableSetColumnWidth(int column_n, float width)
2483{
2484 ImGuiContext& g = *GImGui;
2485 ImGuiTable* table = g.CurrentTable;
2486 IM_ASSERT(table != NULL && table->IsLayoutLocked == false);
2487 IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
2488 ImGuiTableColumn* column_0 = &table->Columns[column_n];
2489 float column_0_width = width;
2490
2491 // Apply constraints early
2492 // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded)
2493 IM_ASSERT(table->MinColumnWidth > 0.0f);
2494 const float min_width = table->MinColumnWidth;
2495 const float max_width = ImMax(min_width, column_0->WidthMax); // Don't use TableCalcMaxColumnWidth() here as it would rely on MinX from last instance (#7933)
2496 column_0_width = ImClamp(column_0_width, min_width, max_width);
2497 if (column_0->WidthGiven == column_0_width || column_0->WidthRequest == column_0_width)
2498 return;
2499
2500 //IMGUI_DEBUG_PRINT("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthGiven, column_0_width);
2501 ImGuiTableColumn* column_1 = (column_0->NextEnabledColumn != -1) ? &table->Columns[column_0->NextEnabledColumn] : NULL;
2502
2503 // In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns.
2504 // - All fixed: easy.
2505 // - All stretch: easy.
2506 // - One or more fixed + one stretch: easy.
2507 // - One or more fixed + more than one stretch: tricky.
2508 // Qt when manual resize is enabled only supports a single _trailing_ stretch column, we support more cases here.
2509
2510 // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1.
2511 // FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user.
2512 // Scenarios:
2513 // - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset.
2514 // - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered.
2515 // - 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.
2516 // - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
2517 // - W1 W2 W3 resize from W1| or W2| --> ok
2518 // - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
2519 // - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1)
2520 // - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1)
2521 // - W1 W2 F3 resize from W1| or W2| --> ok
2522 // - W1 F2 W3 resize from W1| or F2| --> ok
2523 // - F1 W2 F3 resize from W2| --> ok
2524 // - F1 W3 F2 resize from W3| --> ok
2525 // - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move.
2526 // - W1 F2 F3 resize from F2| --> ok
2527 // All resizes from a Wx columns are locking other columns.
2528
2529 // Possible improvements:
2530 // - 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.
2531 // - 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.
2532
2533 // [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout().
2534
2535 // 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.
2536 // This is the preferred resize path
2537 if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed)
2538 if (!column_1 || table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder >= column_0->DisplayOrder)
2539 {
2540 column_0->WidthRequest = column_0_width;
2541 table->IsSettingsDirty = true;
2542 return;
2543 }
2544
2545 // We can also use previous column if there's no next one (this is used when doing an auto-fit on the right-most stretch column)
2546 if (column_1 == NULL)
2547 column_1 = (column_0->PrevEnabledColumn != -1) ? &table->Columns[column_0->PrevEnabledColumn] : NULL;
2548 if (column_1 == NULL)
2549 return;
2550
2551 // Resizing from right-side of a Stretch column before a Fixed column forward sizing to left-side of fixed column.
2552 // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b)
2553 float column_1_width = ImMax(column_1->WidthRequest - (column_0_width - column_0->WidthRequest), min_width);
2554 column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width;
2555 IM_ASSERT(column_0_width > 0.0f && column_1_width > 0.0f);
2556 column_0->WidthRequest = column_0_width;
2557 column_1->WidthRequest = column_1_width;
2558 if ((column_0->Flags | column_1->Flags) & ImGuiTableColumnFlags_WidthStretch)
2559 TableUpdateColumnsWeightFromWidth(table);
2560 table->IsSettingsDirty = true;
2561}
2562
2563// Disable clipping then auto-fit, will take 2 frames
2564// (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns)
2565void ImGui::TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n)
2566{
2567 // Single auto width uses auto-fit
2568 ImGuiTableColumn* column = &table->Columns[column_n];
2569 if (!column->IsEnabled)
2570 return;
2571 column->CannotSkipItemsQueue = (1 << 0);
2572 table->AutoFitSingleColumn = (ImGuiTableColumnIdx)column_n;
2573}
2574
2575void ImGui::TableSetColumnWidthAutoAll(ImGuiTable* table)
2576{
2577 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2578 {
2579 ImGuiTableColumn* column = &table->Columns[column_n];
2580 if (!column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) // Cannot reset weight of hidden stretch column
2581 continue;
2582 column->CannotSkipItemsQueue = (1 << 0);
2583 column->AutoFitQueue = (1 << 1);
2584 }
2585}
2586
2587void ImGui::TableUpdateColumnsWeightFromWidth(ImGuiTable* table)
2588{
2589 IM_ASSERT(table->LeftMostStretchedColumn != -1 && table->RightMostStretchedColumn != -1);
2590
2591 // Measure existing quantities
2592 float visible_weight = 0.0f;
2593 float visible_width = 0.0f;
2594 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2595 {
2596 ImGuiTableColumn* column = &table->Columns[column_n];
2597 if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
2598 continue;
2599 IM_ASSERT(column->StretchWeight > 0.0f);
2600 visible_weight += column->StretchWeight;
2601 visible_width += column->WidthRequest;
2602 }
2603 IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f);
2604
2605 // Apply new weights
2606 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2607 {
2608 ImGuiTableColumn* column = &table->Columns[column_n];
2609 if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
2610 continue;
2611 column->StretchWeight = (column->WidthRequest / visible_width) * visible_weight;
2612 IM_ASSERT(column->StretchWeight > 0.0f);
2613 }
2614}
2615
2616//-------------------------------------------------------------------------
2617// [SECTION] Tables: Drawing
2618//-------------------------------------------------------------------------
2619// - TablePushBackgroundChannel() [Internal]
2620// - TablePopBackgroundChannel() [Internal]
2621// - TableSetupDrawChannels() [Internal]
2622// - TableMergeDrawChannels() [Internal]
2623// - TableGetColumnBorderCol() [Internal]
2624// - TableDrawBorders() [Internal]
2625//-------------------------------------------------------------------------
2626
2627
2628// FIXME: This could be abstracted and merged with PushColumnsBackground(), by creating a generic struct
2629// with storage for backup cliprect + backup channel + storage for splitter pointer, new clip rect.
2630// This would slightly simplify caller code.
2631
2632// Bg2 is used by Selectable (and possibly other widgets) to render to the background.
2633// 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.
2634void ImGui::TablePushBackgroundChannel()
2635{
2636 ImGuiContext& g = *GImGui;
2637 ImGuiWindow* window = g.CurrentWindow;
2638 ImGuiTable* table = g.CurrentTable;
2639
2640 // Optimization: avoid SetCurrentChannel() + PushClipRect()
2641 table->HostBackupInnerClipRect = window->ClipRect;
2642 SetWindowClipRectBeforeSetChannel(window, table->Bg2ClipRectForDrawCmd);
2643 table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Bg2DrawChannelCurrent);
2644}
2645
2646void ImGui::TablePopBackgroundChannel()
2647{
2648 ImGuiContext& g = *GImGui;
2649 ImGuiWindow* window = g.CurrentWindow;
2650 ImGuiTable* table = g.CurrentTable;
2651
2652 // Optimization: avoid PopClipRect() + SetCurrentChannel()
2653 SetWindowClipRectBeforeSetChannel(window, table->HostBackupInnerClipRect);
2654 table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[table->CurrentColumn].DrawChannelCurrent);
2655}
2656
2657// Also see TableBeginCell()
2658void ImGui::TablePushColumnChannel(int column_n)
2659{
2660 ImGuiContext& g = *GImGui;
2661 ImGuiTable* table = g.CurrentTable;
2662
2663 // Optimization: avoid SetCurrentChannel() + PushClipRect()
2664 if (table->Flags & ImGuiTableFlags_NoClip)
2665 return;
2666 ImGuiWindow* window = g.CurrentWindow;
2667 const ImGuiTableColumn* column = &table->Columns[column_n];
2668 SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
2669 table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
2670}
2671
2672void ImGui::TablePopColumnChannel()
2673{
2674 ImGuiContext& g = *GImGui;
2675 ImGuiTable* table = g.CurrentTable;
2676
2677 // Optimization: avoid PopClipRect() + SetCurrentChannel()
2678 if ((table->Flags & ImGuiTableFlags_NoClip) || (table->CurrentColumn == -1)) // Calling TreePop() after TableNextRow() is supported.
2679 return;
2680 ImGuiWindow* window = g.CurrentWindow;
2681 const ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
2682 SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
2683 table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
2684}
2685
2686// Allocate draw channels. Called by TableUpdateLayout()
2687// - We allocate them following storage order instead of display order so reordering columns won't needlessly
2688// increase overall dormant memory cost.
2689// - We isolate headers draw commands in their own channels instead of just altering clip rects.
2690// This is in order to facilitate merging of draw commands.
2691// - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels.
2692// - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other
2693// channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged.
2694// - We allocate 1 or 2 background draw channels. This is because we know TablePushBackgroundChannel() is only used for
2695// horizontal spanning. If we allowed vertical spanning we'd need one background draw channel per merge group (1-4).
2696// Draw channel allocation (before merging):
2697// - NoClip --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call)
2698// - Clip --> 2+D+N channels
2699// - FreezeRows --> 2+D+N*2 (unless scrolling value is zero)
2700// - FreezeRows || FreezeColumns --> 3+D+N*2 (unless scrolling value is zero)
2701// Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0.
2702void ImGui::TableSetupDrawChannels(ImGuiTable* table)
2703{
2704 const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1;
2705 const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClip) ? 1 : table->ColumnsEnabledCount;
2706 const int channels_for_bg = 1 + 1 * freeze_row_multiplier;
2707 const int channels_for_dummy = (table->ColumnsEnabledCount < table->ColumnsCount || (memcmp(table->VisibleMaskByIndex, table->EnabledMaskByIndex, ImBitArrayGetStorageSizeInBytes(table->ColumnsCount)) != 0)) ? +1 : 0;
2708 const int channels_total = channels_for_bg + (channels_for_row * freeze_row_multiplier) + channels_for_dummy;
2709 table->DrawSplitter->Split(table->InnerWindow->DrawList, channels_total);
2710 table->DummyDrawChannel = (ImGuiTableDrawChannelIdx)((channels_for_dummy > 0) ? channels_total - 1 : -1);
2711 table->Bg2DrawChannelCurrent = TABLE_DRAW_CHANNEL_BG2_FROZEN;
2712 table->Bg2DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)((table->FreezeRowsCount > 0) ? 2 + channels_for_row : TABLE_DRAW_CHANNEL_BG2_FROZEN);
2713
2714 int draw_channel_current = 2;
2715 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2716 {
2717 ImGuiTableColumn* column = &table->Columns[column_n];
2718 if (column->IsVisibleX && column->IsVisibleY)
2719 {
2720 column->DrawChannelFrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current);
2721 column->DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row + 1 : 0));
2722 if (!(table->Flags & ImGuiTableFlags_NoClip))
2723 draw_channel_current++;
2724 }
2725 else
2726 {
2727 column->DrawChannelFrozen = column->DrawChannelUnfrozen = table->DummyDrawChannel;
2728 }
2729 column->DrawChannelCurrent = column->DrawChannelFrozen;
2730 }
2731
2732 // Initial draw cmd starts with a BgClipRect that matches the one of its host, to facilitate merge draw commands by default.
2733 // All our cell highlight are manually clipped with BgClipRect. When unfreezing it will be made smaller to fit scrolling rect.
2734 // (This technically isn't part of setting up draw channels, but is reasonably related to be done here)
2735 table->BgClipRect = table->InnerClipRect;
2736 table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect;
2737 table->Bg2ClipRectForDrawCmd = table->HostClipRect;
2738 IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y);
2739}
2740
2741// This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable().
2742// For simplicity we call it TableMergeDrawChannels() but in fact it only reorder channels + overwrite ClipRect,
2743// actual merging is done by table->DrawSplitter.Merge() which is called right after TableMergeDrawChannels().
2744//
2745// Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve
2746// this we merge their clip rect and make them contiguous in the channel list, so they can be merged
2747// by the call to DrawSplitter.Merge() following to the call to this function.
2748// We reorder draw commands by arranging them into a maximum of 4 distinct groups:
2749//
2750// 1 group: 2 groups: 2 groups: 4 groups:
2751// [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze
2752// [ .. ] or no scroll [ 2. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll
2753//
2754// Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled).
2755// When the contents of a column didn't stray off its limit, we move its channels into the corresponding group
2756// based on its position (within frozen rows/columns groups or not).
2757// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect.
2758// This function assume that each column are pointing to a distinct draw channel,
2759// otherwise merge_group->ChannelsCount will not match set bit count of merge_group->ChannelsMask.
2760//
2761// Column channels will not be merged into one of the 1-4 groups in the following cases:
2762// - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value).
2763// Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds
2764// matches, by e.g. calling SetCursorScreenPos().
2765// - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here..
2766// we could do better but it's going to be rare and probably not worth the hassle.
2767// Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd.
2768//
2769// This function is particularly tricky to understand.. take a breath.
2770void ImGui::TableMergeDrawChannels(ImGuiTable* table)
2771{
2772 ImGuiContext& g = *GImGui;
2773 ImDrawListSplitter* splitter = table->DrawSplitter;
2774 const bool has_freeze_v = (table->FreezeRowsCount > 0);
2775 const bool has_freeze_h = (table->FreezeColumnsCount > 0);
2776 IM_ASSERT(splitter->_Current == 0);
2777
2778 // Track which groups we are going to attempt to merge, and which channels goes into each group.
2779 struct MergeGroup
2780 {
2781 ImRect ClipRect;
2782 int ChannelsCount = 0;
2783 ImBitArrayPtr ChannelsMask = NULL;
2784 };
2785 int merge_group_mask = 0x00;
2786 MergeGroup merge_groups[4];
2787
2788 // Use a reusable temp buffer for the merge masks as they are dynamically sized.
2789 const int max_draw_channels = (4 + table->ColumnsCount * 2);
2790 const int size_for_masks_bitarrays_one = (int)ImBitArrayGetStorageSizeInBytes(max_draw_channels);
2791 g.TempBuffer.reserve(size_for_masks_bitarrays_one * 5);
2792 memset(g.TempBuffer.Data, 0, size_for_masks_bitarrays_one * 5);
2793 for (int n = 0; n < IM_COUNTOF(merge_groups); n++)
2794 merge_groups[n].ChannelsMask = (ImBitArrayPtr)(void*)(g.TempBuffer.Data + (size_for_masks_bitarrays_one * n));
2795 ImBitArrayPtr remaining_mask = (ImBitArrayPtr)(void*)(g.TempBuffer.Data + (size_for_masks_bitarrays_one * 4));
2796
2797 // 1. Scan channels and take note of those which can be merged
2798 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2799 {
2800 if (!IM_BITARRAY_TESTBIT(table->VisibleMaskByIndex, column_n))
2801 continue;
2802 ImGuiTableColumn* column = &table->Columns[column_n];
2803
2804 const int merge_group_sub_count = has_freeze_v ? 2 : 1;
2805 for (int merge_group_sub_n = 0; merge_group_sub_n < merge_group_sub_count; merge_group_sub_n++)
2806 {
2807 const int channel_no = (merge_group_sub_n == 0) ? column->DrawChannelFrozen : column->DrawChannelUnfrozen;
2808
2809 // Don't attempt to merge if there are multiple draw calls within the column
2810 ImDrawChannel* src_channel = &splitter->_Channels[channel_no];
2811 if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0 && src_channel->_CmdBuffer.back().UserCallback == NULL) // Equivalent of PopUnusedDrawCmd()
2812 src_channel->_CmdBuffer.pop_back();
2813 if (src_channel->_CmdBuffer.Size != 1)
2814 continue;
2815
2816 // Find out the width of this merge group and check if it will fit in our column
2817 // (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it)
2818 if (!(column->Flags & ImGuiTableColumnFlags_NoClip))
2819 {
2820 float content_max_x;
2821 if (!has_freeze_v)
2822 content_max_x = ImMax(column->ContentMaxXUnfrozen, column->ContentMaxXHeadersUsed); // No row freeze
2823 else if (merge_group_sub_n == 0)
2824 content_max_x = ImMax(column->ContentMaxXFrozen, column->ContentMaxXHeadersUsed); // Row freeze: use width before freeze
2825 else
2826 content_max_x = column->ContentMaxXUnfrozen; // Row freeze: use width after freeze
2827 if (content_max_x > column->ClipRect.Max.x)
2828 continue;
2829 }
2830
2831 const int merge_group_n = (has_freeze_h && column_n < table->FreezeColumnsCount ? 0 : 1) + (has_freeze_v && merge_group_sub_n == 0 ? 0 : 2);
2832 IM_ASSERT(channel_no < max_draw_channels);
2833 MergeGroup* merge_group = &merge_groups[merge_group_n];
2834 if (merge_group->ChannelsCount == 0)
2835 merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
2836 ImBitArraySetBit(merge_group->ChannelsMask, channel_no);
2837 merge_group->ChannelsCount++;
2838 merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect);
2839 merge_group_mask |= (1 << merge_group_n);
2840 }
2841
2842 // Invalidate current draw channel
2843 // (we don't clear DrawChannelFrozen/DrawChannelUnfrozen solely to facilitate debugging/later inspection of data)
2844 column->DrawChannelCurrent = (ImGuiTableDrawChannelIdx)-1;
2845 }
2846
2847 // [DEBUG] Display merge groups
2848#if 0
2849 if (g.IO.KeyShift)
2850 for (int merge_group_n = 0; merge_group_n < IM_COUNTOF(merge_groups); merge_group_n++)
2851 {
2852 MergeGroup* merge_group = &merge_groups[merge_group_n];
2853 if (merge_group->ChannelsCount == 0)
2854 continue;
2855 char buf[32];
2856 ImFormatString(buf, 32, "MG%d:%d", merge_group_n, merge_group->ChannelsCount);
2857 ImVec2 text_pos = merge_group->ClipRect.Min + ImVec2(4, 4);
2858 ImVec2 text_size = CalcTextSize(buf, NULL);
2859 GetForegroundDrawList()->AddRectFilled(text_pos, text_pos + text_size, IM_COL32(0, 0, 0, 255));
2860 GetForegroundDrawList()->AddText(text_pos, IM_COL32(255, 255, 0, 255), buf, NULL);
2861 GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 255, 0, 255));
2862 }
2863#endif
2864
2865 // 2. Rewrite channel list in our preferred order
2866 if (merge_group_mask != 0)
2867 {
2868 // We skip channel 0 (Bg0/Bg1) and 1 (Bg2 frozen) from the shuffling since they won't move - see channels allocation in TableSetupDrawChannels().
2869 const int LEADING_DRAW_CHANNELS = 2;
2870 g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - LEADING_DRAW_CHANNELS); // Use shared temporary storage so the allocation gets amortized
2871 ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data;
2872 ImBitArraySetBitRange(remaining_mask, LEADING_DRAW_CHANNELS, splitter->_Count);
2873 ImBitArrayClearBit(remaining_mask, table->Bg2DrawChannelUnfrozen);
2874 IM_ASSERT(has_freeze_v == false || table->Bg2DrawChannelUnfrozen != TABLE_DRAW_CHANNEL_BG2_FROZEN);
2875 int remaining_count = splitter->_Count - (has_freeze_v ? LEADING_DRAW_CHANNELS + 1 : LEADING_DRAW_CHANNELS);
2876 //ImRect host_rect = (table->InnerWindow == table->OuterWindow) ? table->InnerClipRect : table->HostClipRect;
2877 ImRect host_rect = table->HostClipRect;
2878 for (int merge_group_n = 0; merge_group_n < IM_COUNTOF(merge_groups); merge_group_n++)
2879 {
2880 if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount)
2881 {
2882 MergeGroup* merge_group = &merge_groups[merge_group_n];
2883 ImRect merge_clip_rect = merge_group->ClipRect;
2884
2885 // Extend outer-most clip limits to match those of host, so draw calls can be merged even if
2886 // outer-most columns have some outer padding offsetting them from their parent ClipRect.
2887 // The principal cases this is dealing with are:
2888 // - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge
2889 // - 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
2890 // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit
2891 // within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect.
2892 if ((merge_group_n & 1) == 0 || !has_freeze_h)
2893 merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x);
2894 if ((merge_group_n & 2) == 0 || !has_freeze_v)
2895 merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, host_rect.Min.y);
2896 if ((merge_group_n & 1) != 0)
2897 merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, host_rect.Max.x);
2898 if ((merge_group_n & 2) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0)
2899 merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y);
2900 //GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, 0, 1.0f); // [DEBUG]
2901 //GetForegroundDrawList()->AddLine(merge_group->ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200));
2902 //GetForegroundDrawList()->AddLine(merge_group->ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200));
2903 remaining_count -= merge_group->ChannelsCount;
2904 for (int n = 0; n < (size_for_masks_bitarrays_one >> 2); n++)
2905 remaining_mask[n] &= ~merge_group->ChannelsMask[n];
2906 for (int n = 0; n < splitter->_Count && merge_channels_count != 0; n++)
2907 {
2908 // Copy + overwrite new clip rect
2909 if (!IM_BITARRAY_TESTBIT(merge_group->ChannelsMask, n))
2910 continue;
2911 IM_BITARRAY_CLEARBIT(merge_group->ChannelsMask, n);
2912 merge_channels_count--;
2913
2914 ImDrawChannel* channel = &splitter->_Channels[n];
2915 IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect)));
2916 channel->_CmdBuffer[0].ClipRect = merge_clip_rect.ToVec4();
2917 memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));
2918 }
2919 }
2920
2921 // Make sure Bg2DrawChannelUnfrozen appears in the middle of our groups (whereas Bg0/Bg1 and Bg2 frozen are fixed to 0 and 1)
2922 if (merge_group_n == 1 && has_freeze_v)
2923 memcpy(dst_tmp++, &splitter->_Channels[table->Bg2DrawChannelUnfrozen], sizeof(ImDrawChannel));
2924 }
2925
2926 // Append unmergeable channels that we didn't reorder at the end of the list
2927 for (int n = 0; n < splitter->_Count && remaining_count != 0; n++)
2928 {
2929 if (!IM_BITARRAY_TESTBIT(remaining_mask, n))
2930 continue;
2931 ImDrawChannel* channel = &splitter->_Channels[n];
2932 memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));
2933 remaining_count--;
2934 }
2935 IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size);
2936 memcpy(splitter->_Channels.Data + LEADING_DRAW_CHANNELS, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - LEADING_DRAW_CHANNELS) * sizeof(ImDrawChannel));
2937 }
2938}
2939
2940static ImU32 TableGetColumnBorderCol(ImGuiTable* table, int order_n, int column_n)
2941{
2942 const bool is_hovered = (table->HoveredColumnBorder == column_n);
2943 const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent);
2944 const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1);
2945 if (is_resized || is_hovered)
2946 return ImGui::GetColorU32(is_resized ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
2947 if (is_frozen_separator || (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)))
2948 return table->BorderColorStrong;
2949 return table->BorderColorLight;
2950}
2951
2952// FIXME-TABLE: This is a mess, need to redesign how we render borders (as some are also done in TableEndRow)
2953void ImGui::TableDrawBorders(ImGuiTable* table)
2954{
2955 ImGuiWindow* inner_window = table->InnerWindow;
2956 if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect))
2957 return;
2958
2959 ImDrawList* inner_drawlist = inner_window->DrawList;
2960 table->DrawSplitter->SetCurrentChannel(inner_drawlist, TABLE_DRAW_CHANNEL_BG0);
2961 inner_drawlist->PushClipRect(table->Bg0ClipRectForDrawCmd.Min, table->Bg0ClipRectForDrawCmd.Max, false);
2962
2963 // Draw inner border and resizing feedback
2964 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent);
2965 const float border_size = TABLE_BORDER_SIZE;
2966 const float draw_y1 = ImMax(table->InnerRect.Min.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? 1.0f : 0.0f);
2967 const float draw_y2_body = table->InnerRect.Max.y;
2968 const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1;
2969 if (table->Flags & ImGuiTableFlags_BordersInnerV)
2970 {
2971 for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
2972 {
2973 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n))
2974 continue;
2975
2976 const int column_n = table->DisplayOrderToIndex[order_n];
2977 ImGuiTableColumn* column = &table->Columns[column_n];
2978 const bool is_hovered = (table->HoveredColumnBorder == column_n);
2979 const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent);
2980 const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0;
2981 const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1);
2982 if (column->MaxX > table->InnerClipRect.Max.x && !is_resized)
2983 continue;
2984
2985 // Decide whether right-most column is visible
2986 if (column->NextEnabledColumn == -1 && !is_resizable)
2987 if ((table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame || (table->Flags & ImGuiTableFlags_NoHostExtendX))
2988 continue;
2989 if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size..
2990 continue;
2991
2992 // Draw in outer window so right-most column won't be clipped
2993 float draw_y2 = draw_y2_head;
2994 if (is_frozen_separator)
2995 draw_y2 = draw_y2_body;
2996 else if ((table->Flags & ImGuiTableFlags_NoBordersInBodyUntilResize) != 0 && (is_hovered || is_resized))
2997 draw_y2 = draw_y2_body;
2998 else if ((table->Flags & (ImGuiTableFlags_NoBordersInBodyUntilResize | ImGuiTableFlags_NoBordersInBody)) == 0)
2999 draw_y2 = draw_y2_body;
3000 if (draw_y2 > draw_y1)
3001 inner_drawlist->AddLineV(column->MaxX, draw_y1, draw_y2, TableGetColumnBorderCol(table, order_n, column_n), border_size);
3002 }
3003 }
3004
3005 // Draw outer border
3006 // FIXME: could use AddRect or explicit VLine/HLine helper?
3007 if (table->Flags & ImGuiTableFlags_BordersOuter)
3008 {
3009 // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call
3010 // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their
3011 // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part
3012 // of it in inner window, and the part that's over scrollbars in the outer window..)
3013 // Either solution currently won't allow us to use a larger border size: the border would clipped.
3014 const ImRect outer_border = table->OuterRect;
3015 const ImU32 outer_col = table->BorderColorStrong;
3016 if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter)
3017 {
3018 inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, border_size);
3019 }
3020 else if (table->Flags & ImGuiTableFlags_BordersOuterV)
3021 {
3022 inner_drawlist->AddLineV(outer_border.Min.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size);
3023 inner_drawlist->AddLineV(outer_border.Max.x, outer_border.Min.y, outer_border.Max.y, outer_col, border_size);
3024 }
3025 else if (table->Flags & ImGuiTableFlags_BordersOuterH)
3026 {
3027 inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Min.y, outer_col, border_size);
3028 inner_drawlist->AddLineH(outer_border.Min.x, outer_border.Max.x, outer_border.Max.y, outer_col, border_size);
3029 }
3030 }
3031 if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y)
3032 {
3033 // Draw bottom-most row border between it is above outer border.
3034 const float border_y = table->RowPosY2;
3035 if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y)
3036 inner_drawlist->AddLineH(table->BorderX1, table->BorderX2, border_y, table->BorderColorLight, border_size);
3037 }
3038
3039 inner_drawlist->PopClipRect();
3040}
3041
3042//-------------------------------------------------------------------------
3043// [SECTION] Tables: Sorting
3044//-------------------------------------------------------------------------
3045// - TableGetSortSpecs()
3046// - TableFixColumnSortDirection() [Internal]
3047// - TableGetColumnNextSortDirection() [Internal]
3048// - TableSetColumnSortDirection() [Internal]
3049// - TableSortSpecsSanitize() [Internal]
3050// - TableSortSpecsBuild() [Internal]
3051//-------------------------------------------------------------------------
3052
3053// Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set)
3054// When 'sort_specs->SpecsDirty == true' you should sort your data. It will be true when sorting specs have
3055// changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting,
3056// else you may wastefully sort your data every frame!
3057// Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()!
3058ImGuiTableSortSpecs* ImGui::TableGetSortSpecs()
3059{
3060 ImGuiContext& g = *GImGui;
3061 ImGuiTable* table = g.CurrentTable;
3062 if (table == NULL || !(table->Flags & ImGuiTableFlags_Sortable))
3063 return NULL;
3064
3065 // Require layout (in case TableHeadersRow() hasn't been called) as it may alter IsSortSpecsDirty in some paths.
3066 if (!table->IsLayoutLocked)
3067 TableUpdateLayout(table);
3068
3069 TableSortSpecsBuild(table);
3070 return &table->SortSpecs;
3071}
3072
3073static inline ImGuiSortDirection TableGetColumnAvailSortDirection(ImGuiTableColumn* column, int n)
3074{
3075 IM_ASSERT(n < column->SortDirectionsAvailCount);
3076 return (ImGuiSortDirection)((column->SortDirectionsAvailList >> (n << 1)) & 0x03);
3077}
3078
3079// Fix sort direction if currently set on a value which is unavailable (e.g. activating NoSortAscending/NoSortDescending)
3080void ImGui::TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column)
3081{
3082 if (column->SortOrder == -1 || (column->SortDirectionsAvailMask & (1 << column->SortDirection)) != 0)
3083 return;
3084 column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0);
3085 table->IsSortSpecsDirty = true;
3086}
3087
3088// Calculate next sort direction that would be set after clicking the column
3089// - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click.
3090// - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op.
3091IM_STATIC_ASSERT(ImGuiSortDirection_None == 0 && ImGuiSortDirection_Ascending == 1 && ImGuiSortDirection_Descending == 2);
3092ImGuiSortDirection ImGui::TableGetColumnNextSortDirection(ImGuiTableColumn* column)
3093{
3094 IM_ASSERT(column->SortDirectionsAvailCount > 0);
3095 if (column->SortOrder == -1)
3096 return TableGetColumnAvailSortDirection(column, 0);
3097 for (int n = 0; n < 3; n++)
3098 if (column->SortDirection == TableGetColumnAvailSortDirection(column, n))
3099 return TableGetColumnAvailSortDirection(column, (n + 1) % column->SortDirectionsAvailCount);
3100 IM_ASSERT(0);
3101 return ImGuiSortDirection_None;
3102}
3103
3104// Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert
3105// the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code.
3106void ImGui::TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs)
3107{
3108 ImGuiContext& g = *GImGui;
3109 ImGuiTable* table = g.CurrentTable;
3110
3111 if (!(table->Flags & ImGuiTableFlags_SortMulti))
3112 append_to_sort_specs = false;
3113 if (!(table->Flags & ImGuiTableFlags_SortTristate))
3114 IM_ASSERT(sort_direction != ImGuiSortDirection_None);
3115
3116 ImGuiTableColumnIdx sort_order_max = 0;
3117 if (append_to_sort_specs)
3118 for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
3119 sort_order_max = ImMax(sort_order_max, table->Columns[other_column_n].SortOrder);
3120
3121 ImGuiTableColumn* column = &table->Columns[column_n];
3122 column->SortDirection = (ImU8)sort_direction;
3123 if (column->SortDirection == ImGuiSortDirection_None)
3124 column->SortOrder = -1;
3125 else if (column->SortOrder == -1 || !append_to_sort_specs)
3126 column->SortOrder = append_to_sort_specs ? sort_order_max + 1 : 0;
3127
3128 for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
3129 {
3130 ImGuiTableColumn* other_column = &table->Columns[other_column_n];
3131 if (other_column != column && !append_to_sort_specs)
3132 other_column->SortOrder = -1;
3133 TableFixColumnSortDirection(table, other_column);
3134 }
3135 table->IsSettingsDirty = true;
3136 table->IsSortSpecsDirty = true;
3137}
3138
3139void ImGui::TableSortSpecsSanitize(ImGuiTable* table)
3140{
3141 IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable);
3142
3143 // Clear SortOrder from hidden column and verify that there's no gap or duplicate.
3144 int sort_order_count = 0;
3145 ImU64 sort_order_mask = 0x00;
3146 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
3147 {
3148 ImGuiTableColumn* column = &table->Columns[column_n];
3149 if (column->SortOrder != -1 && !column->IsEnabled)
3150 column->SortOrder = -1;
3151 if (column->SortOrder == -1)
3152 continue;
3153 sort_order_count++;
3154 sort_order_mask |= ((ImU64)1 << column->SortOrder);
3155 IM_ASSERT(sort_order_count < (int)sizeof(sort_order_mask) * 8);
3156 }
3157
3158 const bool need_fix_linearize = ((ImU64)1 << sort_order_count) != (sort_order_mask + 1);
3159 const bool need_fix_single_sort_order = (sort_order_count > 1) && !(table->Flags & ImGuiTableFlags_SortMulti);
3160 if (need_fix_linearize || need_fix_single_sort_order)
3161 {
3162 ImU64 fixed_mask = 0x00;
3163 for (int sort_n = 0; sort_n < sort_order_count; sort_n++)
3164 {
3165 // Fix: Rewrite sort order fields if needed so they have no gap or duplicate.
3166 // (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1)
3167 int column_with_smallest_sort_order = -1;
3168 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
3169 if ((fixed_mask & ((ImU64)1 << (ImU64)column_n)) == 0 && table->Columns[column_n].SortOrder != -1)
3170 if (column_with_smallest_sort_order == -1 || table->Columns[column_n].SortOrder < table->Columns[column_with_smallest_sort_order].SortOrder)
3171 column_with_smallest_sort_order = column_n;
3172 IM_ASSERT(column_with_smallest_sort_order != -1);
3173 fixed_mask |= ((ImU64)1 << column_with_smallest_sort_order);
3174 table->Columns[column_with_smallest_sort_order].SortOrder = (ImGuiTableColumnIdx)sort_n;
3175
3176 // Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set.
3177 if (need_fix_single_sort_order)
3178 {
3179 sort_order_count = 1;
3180 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
3181 if (column_n != column_with_smallest_sort_order)
3182 table->Columns[column_n].SortOrder = -1;
3183 break;
3184 }
3185 }
3186 }
3187
3188 // Fallback default sort order (if no column with the ImGuiTableColumnFlags_DefaultSort flag)
3189 if (sort_order_count == 0 && !(table->Flags & ImGuiTableFlags_SortTristate))
3190 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
3191 {
3192 ImGuiTableColumn* column = &table->Columns[column_n];
3193 if (column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_NoSort))
3194 {
3195 sort_order_count = 1;
3196 column->SortOrder = 0;
3197 column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0);
3198 break;
3199 }
3200 }
3201
3202 table->SortSpecsCount = (ImGuiTableColumnIdx)sort_order_count;
3203}
3204
3205void ImGui::TableSortSpecsBuild(ImGuiTable* table)
3206{
3207 bool dirty = table->IsSortSpecsDirty;
3208 if (dirty)
3209 {
3210 TableSortSpecsSanitize(table);
3211 table->SortSpecsMulti.resize(table->SortSpecsCount <= 1 ? 0 : table->SortSpecsCount);
3212 table->SortSpecs.SpecsDirty = true; // Mark as dirty for user
3213 table->IsSortSpecsDirty = false; // Mark as not dirty for us
3214 }
3215
3216 // Write output
3217 // May be able to move all SortSpecs data from table (48 bytes) to ImGuiTableTempData if we decide to write it back on every BeginTable()
3218 ImGuiTableColumnSortSpecs* sort_specs = (table->SortSpecsCount == 0) ? NULL : (table->SortSpecsCount == 1) ? &table->SortSpecsSingle : table->SortSpecsMulti.Data;
3219 if (dirty && sort_specs != NULL)
3220 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
3221 {
3222 ImGuiTableColumn* column = &table->Columns[column_n];
3223 if (column->SortOrder == -1)
3224 continue;
3225 IM_ASSERT(column->SortOrder < table->SortSpecsCount);
3226 ImGuiTableColumnSortSpecs* sort_spec = &sort_specs[column->SortOrder];
3227 sort_spec->ColumnUserID = column->UserData;
3228 sort_spec->ColumnIndex = (ImGuiTableColumnIdx)column_n;
3229 sort_spec->SortOrder = (ImGuiTableColumnIdx)column->SortOrder;
3230 sort_spec->SortDirection = (ImGuiSortDirection)column->SortDirection;
3231 }
3232
3233 table->SortSpecs.Specs = sort_specs;
3234 table->SortSpecs.SpecsCount = table->SortSpecsCount;
3235}
3236
3237//-------------------------------------------------------------------------
3238// [SECTION] Tables: Headers
3239//-------------------------------------------------------------------------
3240// - TableGetHeaderRowHeight() [Internal]
3241// - TableGetHeaderAngledMaxLabelWidth() [Internal]
3242// - TableHeadersRow()
3243// - TableHeader()
3244// - TableAngledHeadersRow()
3245// - TableAngledHeadersRowEx() [Internal]
3246//-------------------------------------------------------------------------
3247
3248float ImGui::TableGetHeaderRowHeight()
3249{
3250 // Caring for a minor edge case:
3251 // Calculate row height, for the unlikely case that some labels may be taller than others.
3252 // If we didn't do that, uneven header height would highlight but smaller one before the tallest wouldn't catch input for all height.
3253 // In your custom header row you may omit this all together and just call TableNextRow() without a height...
3254 ImGuiContext& g = *GImGui;
3255 ImGuiTable* table = g.CurrentTable;
3256 float row_height = g.FontSize;
3257 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
3258 if (IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n))
3259 if ((table->Columns[column_n].Flags & ImGuiTableColumnFlags_NoHeaderLabel) == 0)
3260 row_height = ImMax(row_height, CalcTextSize(TableGetColumnName(table, column_n)).y);
3261 return row_height + g.Style.CellPadding.y * 2.0f;
3262}
3263
3264float ImGui::TableGetHeaderAngledMaxLabelWidth()
3265{
3266 ImGuiContext& g = *GImGui;
3267 ImGuiTable* table = g.CurrentTable;
3268 float width = 0.0f;
3269 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
3270 if (IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n))
3271 if (table->Columns[column_n].Flags & ImGuiTableColumnFlags_AngledHeader)
3272 width = ImMax(width, CalcTextSize(TableGetColumnName(table, column_n), NULL, true).x);
3273 return width + g.Style.CellPadding.y * 2.0f; // Swap padding
3274}
3275
3276// [Public] This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn().
3277// The intent is that advanced users willing to create customized headers would not need to use this helper
3278// and can create their own! For example: TableHeader() may be preceded by Checkbox() or other custom widgets.
3279// See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this.
3280// This code is intentionally written to not make much use of internal functions, to give you better direction
3281// if you need to write your own.
3282// FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public.
3283void ImGui::TableHeadersRow()
3284{
3285 ImGuiContext& g = *GImGui;
3286 ImGuiTable* table = g.CurrentTable;
3287 IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!");
3288
3289 // Call layout if not already done. This is automatically done by TableNextRow: we do it here _only_ to make
3290 // it easier to debug-step in TableUpdateLayout(). Your own version of this function doesn't need this.
3291 if (!table->IsLayoutLocked)
3292 TableUpdateLayout(table);
3293
3294 // Open row
3295 const float row_height = TableGetHeaderRowHeight();
3296 TableNextRow(ImGuiTableRowFlags_Headers, row_height);
3297 const float row_y1 = GetCursorScreenPos().y;
3298 if (table->HostSkipItems) // Merely an optimization, you may skip in your own code.
3299 return;
3300
3301 const int columns_count = TableGetColumnCount();
3302 for (int column_n = 0; column_n < columns_count; column_n++)
3303 {
3304 if (!TableSetColumnIndex(column_n) && table->LastHeldHeaderColumn != column_n)
3305 continue;
3306
3307 // Push an id to allow empty/unnamed headers. This is also idiomatic as it ensure there is a consistent ID path to access columns (for e.g. automation)
3308 const char* name = (TableGetColumnFlags(column_n) & ImGuiTableColumnFlags_NoHeaderLabel) ? "" : TableGetColumnName(column_n);
3309 PushID(column_n);
3310 TableHeader(name);
3311 PopID();
3312 }
3313
3314 // Allow opening popup from the right-most section after the last column.
3315 ImVec2 mouse_pos = ImGui::GetMousePos();
3316 if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count)
3317 if (mouse_pos.y >= row_y1 && mouse_pos.y < row_y1 + row_height)
3318 TableOpenContextMenu(columns_count); // Will open a non-column-specific popup.
3319}
3320
3321// Emit a column header (text + optional sort order)
3322// We cpu-clip text here so that all columns headers can be merged into a same draw call.
3323// Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader()
3324void ImGui::TableHeader(const char* label)
3325{
3326 ImGuiContext& g = *GImGui;
3327 ImGuiWindow* window = g.CurrentWindow;
3328 if (window->SkipItems)
3329 return;
3330
3331 ImGuiTable* table = g.CurrentTable;
3332 IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!");
3333 IM_ASSERT(table->CurrentColumn != -1);
3334 const int column_n = table->CurrentColumn;
3335 ImGuiTableColumn* column = &table->Columns[column_n];
3336
3337 // Label
3338 if (label == NULL)
3339 label = "";
3340 const char* label_end = FindRenderedTextEnd(label);
3341 ImVec2 label_size = CalcTextSize(label, label_end, false);
3342 ImVec2 label_pos = window->DC.CursorPos;
3343
3344 // If we already got a row height, there's use that.
3345 // FIXME-TABLE: Padding problem if the correct outer-padding CellBgRect strays off our ClipRect?
3346 ImRect cell_r = TableGetCellBgRect(table, column_n);
3347 float label_height = ImMax(label_size.y, table->RowMinHeight - table->RowCellPaddingY * 2.0f);
3348
3349 // Calculate ideal size for sort order arrow
3350 float w_arrow = 0.0f;
3351 float w_sort_text = 0.0f;
3352 bool sort_arrow = false;
3353 char sort_order_suf[4] = "";
3354 const float ARROW_SCALE = 0.65f;
3355 if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort))
3356 {
3357 w_arrow = ImTrunc(g.FontSize * ARROW_SCALE + g.Style.FramePadding.x);
3358 if (column->SortOrder != -1)
3359 sort_arrow = true;
3360 if (column->SortOrder > 0)
3361 {
3362 ImFormatString(sort_order_suf, IM_COUNTOF(sort_order_suf), "%d", column->SortOrder + 1);
3363 w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x;
3364 }
3365 }
3366
3367 // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considered for merging.
3368 float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow;
3369 column->ContentMaxXHeadersUsed = ImMax(column->ContentMaxXHeadersUsed, sort_arrow ? cell_r.Max.x : ImMin(max_pos_x, cell_r.Max.x));
3370 column->ContentMaxXHeadersIdeal = ImMax(column->ContentMaxXHeadersIdeal, max_pos_x);
3371
3372 // Keep header highlighted when context menu is open.
3373 ImGuiID id = window->GetID(label);
3374 ImRect bb(cell_r.Min.x, cell_r.Min.y, cell_r.Max.x, ImMax(cell_r.Max.y, cell_r.Min.y + label_height + g.Style.CellPadding.y * 2.0f));
3375 ItemSize(ImVec2(0.0f, label_height)); // Don't declare unclipped width, it'll be fed ContentMaxPosHeadersIdeal
3376 if (!ItemAdd(bb, id))
3377 return;
3378
3379 //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]
3380 //GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]
3381
3382 // Using AllowOverlap mode because we cover the whole cell, and we want user to be able to submit subsequent items.
3383 const bool highlight = (table->HighlightColumnHeader == column_n);
3384 bool hovered, held;
3385 bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_AllowOverlap);
3386 if (held || hovered || highlight)
3387 {
3388 const ImU32 col = GetColorU32(held ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
3389 //RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
3390 TableSetBgColor(ImGuiTableBgTarget_CellBg, col, table->CurrentColumn);
3391 }
3392 else
3393 {
3394 // Submit single cell bg color in the case we didn't submit a full header row
3395 if ((table->RowFlags & ImGuiTableRowFlags_Headers) == 0)
3396 TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_TableHeaderBg), table->CurrentColumn);
3397 }
3398 RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact, 0.0f);
3399 if (held)
3400 table->HeldHeaderColumn = (ImGuiTableColumnIdx)column_n;
3401 window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f;
3402
3403 // Drag and drop to re-order columns.
3404 // FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone.
3405 if (held && (table->Flags & ImGuiTableFlags_Reorderable) && IsMouseDragging(0) && !g.DragDropActive)
3406 {
3407 // - While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x
3408 // - We need to handle reordering across hidden columns.
3409 // In the configuration below, moving C to the right of E will lead to:
3410 // ... C [D] E ---> ... [D] E C (Column name/index)
3411 // ... 2 3 4 ... 2 3 4 (Display order)
3412 // - The other constraints are enforced by TableQueueSetColumnDisplayOrder() which might early out.
3413 table->InstanceInteracted = table->InstanceCurrent;
3414 if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x)
3415 if (ImGuiTableColumn* prev_column = (column->PrevEnabledColumn != -1) ? &table->Columns[column->PrevEnabledColumn] : NULL)
3416 TableQueueSetColumnDisplayOrder(table, column_n, prev_column->DisplayOrder);
3417 if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x)
3418 if (ImGuiTableColumn* next_column = (column->NextEnabledColumn != -1) ? &table->Columns[column->NextEnabledColumn] : NULL)
3419 TableQueueSetColumnDisplayOrder(table, column_n, next_column->DisplayOrder);
3420 }
3421
3422 // Sort order arrow
3423 // - Only clip label for a visible arrow. Auto-fit still accounts for a possible arrow, but when
3424 // manually sized smaller we don't clip the label for the sake of an arrow that isn't displayed.
3425 const float ellipsis_max = ImMax(cell_r.Max.x - (sort_arrow ? w_arrow + w_sort_text : 0.0f), label_pos.x);
3426 if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort))
3427 {
3428 if (column->SortOrder != -1)
3429 {
3430 float x = ImMax(cell_r.Min.x, cell_r.Max.x - w_arrow - w_sort_text);
3431 float y = label_pos.y;
3432 if (column->SortOrder > 0)
3433 {
3434 PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text, 0.70f));
3435 RenderText(ImVec2(x + g.Style.ItemInnerSpacing.x, y), sort_order_suf);
3436 PopStyleColor();
3437 x += w_sort_text;
3438 }
3439 RenderArrow(window->DrawList, ImVec2(x, y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE);
3440 }
3441
3442 // Handle clicking on column header to adjust Sort Order
3443 if (pressed && table->ReorderColumn != column_n)
3444 {
3445 ImGuiSortDirection sort_direction = TableGetColumnNextSortDirection(column);
3446 TableSetColumnSortDirection(column_n, sort_direction, g.IO.KeyShift);
3447 }
3448 }
3449
3450 // Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will
3451 // be merged into a single draw call.
3452 //window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE);
3453 RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, bb.Max.y), ellipsis_max, label, label_end, &label_size);
3454
3455 const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x);
3456 if (text_clipped && hovered && g.ActiveId == 0)
3457 SetItemTooltip("%.*s", (int)(label_end - label), label);
3458
3459 // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden
3460 if (IsPopupOpenRequestForItem(ImGuiPopupFlags_None, id))
3461 TableOpenContextMenu(column_n);
3462
3463 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
3464}
3465
3466// Unlike TableHeadersRow() it is not expected that you can reimplement or customize this with custom widgets.
3467// FIXME: No hit-testing/button on the angled header.
3468void ImGui::TableAngledHeadersRow()
3469{
3470 ImGuiContext& g = *GImGui;
3471 ImGuiTable* table = g.CurrentTable;
3472 ImGuiTableTempData* temp_data = table->TempData;
3473 temp_data->AngledHeadersRequests.resize(0);
3474 temp_data->AngledHeadersRequests.reserve(table->ColumnsEnabledCount);
3475
3476 // Which column needs highlight?
3477 const ImGuiID row_id = GetID("##AngledHeaders");
3478 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent);
3479 int highlight_column_n = (table->LastHeldHeaderColumn != -1) ? table->LastHeldHeaderColumn : table->HighlightColumnHeader;
3480 if (highlight_column_n == -1 && table->HoveredColumnBody != -1)
3481 if (table_instance->HoveredRowLast == 0 && table->HoveredColumnBorder == -1 && (g.ActiveId == 0 || g.ActiveId == row_id || (table->IsActiveIdInTable || g.DragDropActive)))
3482 highlight_column_n = table->HoveredColumnBody;
3483
3484 // Build up request
3485 ImU32 col_header_bg = GetColorU32(ImGuiCol_TableHeaderBg);
3486 ImU32 col_text = GetColorU32(ImGuiCol_Text);
3487 for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
3488 if (IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n))
3489 {
3490 const int column_n = table->DisplayOrderToIndex[order_n];
3491 ImGuiTableColumn* column = &table->Columns[column_n];
3492 if ((column->Flags & ImGuiTableColumnFlags_AngledHeader) == 0) // Note: can't rely on ImGuiTableColumnFlags_IsVisible test here.
3493 continue;
3494 ImGuiTableHeaderData request = { (ImGuiTableColumnIdx)column_n, col_text, col_header_bg, (column_n == highlight_column_n) ? GetColorU32(ImGuiCol_Header) : 0 };
3495 temp_data->AngledHeadersRequests.push_back(request);
3496 }
3497
3498 // Render row
3499 TableAngledHeadersRowEx(row_id, g.Style.TableAngledHeadersAngle, 0.0f, temp_data->AngledHeadersRequests.Data, temp_data->AngledHeadersRequests.Size);
3500}
3501
3502// Important: data must be fed left to right
3503void ImGui::TableAngledHeadersRowEx(ImGuiID row_id, float angle, float max_label_width, const ImGuiTableHeaderData* data, int data_count)
3504{
3505 ImGuiContext& g = *GImGui;
3506 ImGuiTable* table = g.CurrentTable;
3507 ImGuiWindow* window = g.CurrentWindow;
3508 ImDrawList* draw_list = window->DrawList;
3509 IM_ASSERT_USER_ERROR_RET(table != NULL, "Call should only be done while in BeginTable() scope!");
3510 IM_ASSERT(table->CurrentRow == -1 && "Must be first row");
3511
3512 if (max_label_width == 0.0f)
3513 max_label_width = TableGetHeaderAngledMaxLabelWidth();
3514
3515 // Angle argument expressed in (-IM_PI/2 .. +IM_PI/2) as it is easier to think about for user.
3516 const bool flip_label = (angle < 0.0f);
3517 angle -= IM_PI * 0.5f;
3518 const float cos_a = ImCos(angle);
3519 const float sin_a = ImSin(angle);
3520 const float label_cos_a = flip_label ? ImCos(angle + IM_PI) : cos_a;
3521 const float label_sin_a = flip_label ? ImSin(angle + IM_PI) : sin_a;
3522 const ImVec2 unit_right = ImVec2(cos_a, sin_a);
3523
3524 // Calculate our base metrics and set angled headers data _before_ the first call to TableNextRow()
3525 // FIXME-STYLE: Would it be better for user to submit 'max_label_width' or 'row_height' ? One can be derived from the other.
3526 const float header_height = g.FontSize + g.Style.CellPadding.x * 2.0f;
3527 const float row_height = ImTrunc(ImFabs(ImRotate(ImVec2(max_label_width, flip_label ? +header_height : -header_height), cos_a, sin_a).y));
3528 table->AngledHeadersHeight = row_height;
3529 table->AngledHeadersSlope = (sin_a != 0.0f) ? (cos_a / sin_a) : 0.0f;
3530 const ImVec2 header_angled_vector = unit_right * (row_height / -sin_a); // vector from bottom-left to top-left, and from bottom-right to top-right
3531
3532 // Declare row, override and draw our own background
3533 // FIXME-TABLE: Generally broken when overlapping frozen columns limit.
3534 TableNextRow(ImGuiTableRowFlags_Headers, row_height);
3535 TableNextColumn();
3536 const ImRect row_r(table->WorkRect.Min.x, table->BgClipRect.Min.y, table->WorkRect.Max.x, table->RowPosY2);
3537 table->DrawSplitter->SetCurrentChannel(draw_list, TABLE_DRAW_CHANNEL_BG0);
3538 float clip_rect_min_x = table->BgClipRect.Min.x;
3539 if (table->FreezeColumnsCount > 0)
3540 clip_rect_min_x = ImMax(clip_rect_min_x, table->Columns[table->DisplayOrderToIndex[table->FreezeColumnsCount - 1]].MaxX);
3541 TableSetBgColor(ImGuiTableBgTarget_RowBg0, 0); // Cancel
3542 PushClipRect(table->BgClipRect.Min, table->BgClipRect.Max, false); // Span all columns
3543 draw_list->AddRectFilled(ImVec2(table->BgClipRect.Min.x, row_r.Min.y), ImVec2(table->BgClipRect.Max.x, row_r.Max.y), GetColorU32(ImGuiCol_TableHeaderBg, 0.25f)); // FIXME-STYLE: Change row background with an arbitrary color.
3544 PushClipRect(ImVec2(clip_rect_min_x, table->BgClipRect.Min.y), table->BgClipRect.Max, true); // Span all columns
3545
3546 ButtonBehavior(row_r, row_id, NULL, NULL);
3547 KeepAliveID(row_id);
3548
3549 const float ascent_scaled = g.FontBaked->Ascent * g.FontBakedScale; // FIXME: Standardize those scaling factors better
3550 const float line_off_for_ascent_x = (ImMax((g.FontSize - ascent_scaled) * 0.5f, 0.0f) / -sin_a) * (flip_label ? -1.0f : 1.0f);
3551 const ImVec2 padding = g.Style.CellPadding; // We will always use swapped component
3552 const ImVec2 align = g.Style.TableAngledHeadersTextAlign;
3553
3554 // Draw background and labels in first pass, then all borders.
3555 float max_x = -FLT_MAX;
3556 for (int pass = 0; pass < 2; pass++)
3557 for (int order_n = 0; order_n < data_count; order_n++)
3558 {
3559 const ImGuiTableHeaderData* request = &data[order_n];
3560 const int column_n = request->Index;
3561 ImGuiTableColumn* column = &table->Columns[column_n];
3562
3563 ImVec2 bg_shape[4];
3564 bg_shape[0] = ImVec2(column->MaxX, row_r.Max.y);
3565 bg_shape[1] = ImVec2(column->MinX, row_r.Max.y);
3566 bg_shape[2] = bg_shape[1] + header_angled_vector;
3567 bg_shape[3] = bg_shape[0] + header_angled_vector;
3568 if (pass == 0)
3569 {
3570 // Draw shape
3571 draw_list->AddQuadFilled(bg_shape[0], bg_shape[1], bg_shape[2], bg_shape[3], request->BgColor0);
3572 draw_list->AddQuadFilled(bg_shape[0], bg_shape[1], bg_shape[2], bg_shape[3], request->BgColor1); // Optional highlight
3573 max_x = ImMax(max_x, bg_shape[3].x);
3574
3575 // Draw label
3576 // - First draw at an offset where RenderTextXXX() function won't meddle with applying current ClipRect, then transform to final offset.
3577 // - Handle multiple lines manually, as we want each lines to follow on the horizontal border, rather than see a whole block rotated.
3578 const char* label_name = TableGetColumnName(table, column_n);
3579 const char* label_name_end = FindRenderedTextEnd(label_name);
3580 const float line_off_step_x = (g.FontSize / -sin_a);
3581 const int label_lines = ImTextCountLines(label_name, label_name_end);
3582
3583 // Left<>Right alignment
3584 float line_off_curr_x = flip_label ? (label_lines - 1) * line_off_step_x : 0.0f;
3585 float line_off_for_align_x = ImFloor(ImMax((((column->MaxX - column->MinX) - padding.x * 2.0f) - (label_lines * line_off_step_x)), 0.0f) * align.x);
3586 line_off_curr_x += line_off_for_align_x - line_off_for_ascent_x;
3587
3588 // Register header width
3589 column->ContentMaxXHeadersUsed = column->ContentMaxXHeadersIdeal = column->WorkMinX + ImCeil(label_lines * line_off_step_x - line_off_for_align_x);
3590
3591 while (label_name < label_name_end)
3592 {
3593 const char* label_name_eol = strchr(label_name, '\n');
3594 if (label_name_eol == NULL)
3595 label_name_eol = label_name_end;
3596
3597 // FIXME: Individual line clipping for right-most column is broken for negative angles.
3598 ImVec2 label_size = CalcTextSize(label_name, label_name_eol);
3599 float clip_width = max_label_width - padding.y; // Using padding.y*2.0f would be symmetrical but hide more text.
3600 float clip_height = ImMin(label_size.y, column->ClipRect.Max.x - column->WorkMinX - line_off_curr_x);
3601 ImRect clip_r(window->ClipRect.Min, window->ClipRect.Min + ImVec2(clip_width, clip_height));
3602 int vtx_idx_begin = draw_list->_VtxCurrentIdx;
3603 PushStyleColor(ImGuiCol_Text, request->TextColor);
3604 RenderTextEllipsis(draw_list, clip_r.Min, clip_r.Max, clip_r.Max.x, label_name, label_name_eol, &label_size);
3605 PopStyleColor();
3606 int vtx_idx_end = draw_list->_VtxCurrentIdx;
3607
3608 // Up<>Down alignment
3609 const float available_space = ImMax(clip_width - label_size.x + ImAbs(padding.x * cos_a) * 2.0f - ImAbs(padding.y * sin_a) * 2.0f, 0.0f);
3610 const float vertical_offset = available_space * align.y * (flip_label ? -1.0f : 1.0f);
3611
3612 // Rotate and offset label
3613 ImVec2 pivot_in = ImVec2(window->ClipRect.Min.x - vertical_offset, window->ClipRect.Min.y + label_size.y);
3614 ImVec2 pivot_out = ImVec2(column->WorkMinX, row_r.Max.y);
3615 line_off_curr_x += flip_label ? -line_off_step_x : line_off_step_x;
3616 pivot_out += unit_right * padding.y;
3617 if (flip_label)
3618 pivot_out += unit_right * (clip_width - ImMax(0.0f, clip_width - label_size.x));
3619 pivot_out.x += flip_label ? line_off_curr_x + line_off_step_x : line_off_curr_x;
3620 ShadeVertsTransformPos(draw_list, vtx_idx_begin, vtx_idx_end, pivot_in, label_cos_a, label_sin_a, pivot_out); // Rotate and offset
3621 //if (g.IO.KeyShift) { ImDrawList* 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.0f, 0, 1.0f); ShadeVertsTransformPos(fg_dl, vtx_idx_begin, fg_dl->_VtxCurrentIdx, pivot_in, label_cos_a, label_sin_a, pivot_out); }
3622
3623 label_name = label_name_eol + 1;
3624 }
3625 }
3626 if (pass == 1)
3627 {
3628 // Draw border
3629 draw_list->AddLine(bg_shape[0], bg_shape[3], TableGetColumnBorderCol(table, order_n, column_n));
3630 }
3631 }
3632 PopClipRect();
3633 PopClipRect();
3634 table->TempData->AngledHeadersExtraWidth = ImMax(0.0f, max_x - table->Columns[table->RightMostEnabledColumn].MaxX);
3635}
3636
3637//-------------------------------------------------------------------------
3638// [SECTION] Tables: Context Menu
3639//-------------------------------------------------------------------------
3640// - TableOpenContextMenu() [Internal]
3641// - TableBeginContextMenuPopup() [Internal]
3642// - TableDrawDefaultContextMenu() [Internal]
3643//-------------------------------------------------------------------------
3644
3645// Use -1 to open menu not specific to a given column.
3646void ImGui::TableOpenContextMenu(int column_n)
3647{
3648 ImGuiContext& g = *GImGui;
3649 ImGuiTable* table = g.CurrentTable;
3650 if (column_n == -1 && table->CurrentColumn != -1) // When called within a column automatically use this one (for consistency)
3651 column_n = table->CurrentColumn;
3652 if (column_n == table->ColumnsCount) // To facilitate using with TableGetHoveredColumn()
3653 column_n = -1;
3654 IM_ASSERT(column_n >= -1 && column_n < table->ColumnsCount);
3655 if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
3656 {
3657 table->IsContextPopupOpen = true;
3658 table->ContextPopupColumn = (ImGuiTableColumnIdx)column_n;
3659 table->InstanceInteracted = table->InstanceCurrent;
3660 const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID);
3661 OpenPopupEx(context_menu_id, ImGuiPopupFlags_None);
3662 }
3663}
3664
3665bool ImGui::TableBeginContextMenuPopup(ImGuiTable* table)
3666{
3667 if (!table->IsContextPopupOpen || table->InstanceCurrent != table->InstanceInteracted)
3668 return false;
3669 const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID);
3670 if (BeginPopupEx(context_menu_id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings))
3671 return true;
3672 table->IsContextPopupOpen = false;
3673 return false;
3674}
3675
3676// FIXME: Copied from MenuItem() for the purpose of being able to pass _SelectOnRelease (#9312)
3677static bool MenuItemForColumnReorder(const char* label, bool selected, bool enabled)
3678{
3679 using namespace ImGui;
3680 ImGuiContext& g = *GImGui;
3681 ImGuiWindow* window = g.CurrentWindow;
3682
3683 ImVec2 label_size = CalcTextSize(label, NULL, true);
3684 ImGuiMenuColumns* offsets = &window->DC.MenuColumns;
3685 float checkmark_w = IM_TRUNC(g.FontSize * 1.20f);
3686 float min_w = offsets->DeclColumns(0.0f, label_size.x, 0.0f, checkmark_w); // Feedback for next frame
3687 float stretch_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
3688 ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
3689
3690 ImGuiID id = GetID(label);
3691 ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_SelectOnRelease | ImGuiSelectableFlags_SpanAvailWidth;
3692 if (g.ActiveId == id)
3693 selectable_flags |= ImGuiSelectableFlags_Highlight; // Stays highlighted while dragging.
3694 const bool has_been_moved = (g.ActiveId == id) && g.ActiveIdHasBeenEditedBefore; // But disable toggling once moved.
3695
3696 BeginDisabled(!enabled); // Don't use ImGuiSelectableFlags_Disabled so that Check mark is also affected.
3697 bool ret = Selectable(label, false, selectable_flags, ImVec2(min_w, label_size.y)) && !has_been_moved; // Can't use IsMouseDragging(0) as button is released already.
3698 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) && selected)
3699 RenderCheckMark(window->DrawList, text_pos + ImVec2(offsets->OffsetMark + stretch_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(ImGuiCol_Text), g.FontSize * 0.866f);
3700 EndDisabled();
3701
3702 IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0));
3703 return ret;
3704}
3705
3706// Output context menu into current window (generally a popup)
3707// FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data?
3708// Sections to display are pulled from 'flags_for_section_to_display', which is typically == table->Flags.
3709// - ImGuiTableFlags_Resizable -> display Sizing menu items
3710// - ImGuiTableFlags_Reorderable -> display "Reset Order"
3711////- ImGuiTableFlags_Sortable -> display sorting options (disabled)
3712// - ImGuiTableFlags_Hideable -> display columns visibility menu items
3713// It means if you have a custom context menus you can call this section and omit some sections, and add your own.
3714void ImGui::TableDrawDefaultContextMenu(ImGuiTable* table, ImGuiTableFlags flags_for_section_to_display)
3715{
3716 ImGuiContext& g = *GImGui;
3717 ImGuiWindow* window = g.CurrentWindow;
3718 if (window->SkipItems)
3719 return;
3720
3721 bool want_separator = false;
3722 const int context_column_n = (table->ContextPopupColumn >= 0 && table->ContextPopupColumn < table->ColumnsCount) ? table->ContextPopupColumn : -1;
3723 ImGuiTableColumn* context_column = (context_column_n != -1) ? &table->Columns[context_column_n] : NULL;
3724
3725 // Sizing
3726 if (flags_for_section_to_display & ImGuiTableFlags_Resizable)
3727 {
3728 if (context_column != NULL)
3729 {
3730 const bool can_resize = !(context_column->Flags & ImGuiTableColumnFlags_NoResize) && context_column->IsEnabled;
3731 if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableSizeOne), NULL, false, can_resize)) // "###SizeOne"
3732 TableSetColumnWidthAutoSingle(table, context_column_n);
3733 }
3734
3735 const char* size_all_desc;
3736 if (table->ColumnsEnabledFixedCount == table->ColumnsEnabledCount && (table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame)
3737 size_all_desc = LocalizeGetMsg(ImGuiLocKey_TableSizeAllFit); // "###SizeAll" All fixed
3738 else
3739 size_all_desc = LocalizeGetMsg(ImGuiLocKey_TableSizeAllDefault); // "###SizeAll" All stretch or mixed
3740 if (MenuItem(size_all_desc, NULL))
3741 TableSetColumnWidthAutoAll(table);
3742 want_separator = true;
3743 }
3744
3745 // Reset Order/Visibility etc.
3746 if (flags_for_section_to_display & (ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
3747 if (BeginMenu(LocalizeGetMsg(ImGuiLocKey_TableReset)))
3748 {
3749 //if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetAll))) // FIXME: Hiding because altering Sort Order + requesting auto-fit simultaneously has a tendency to exhibit a sizing glitch.
3750 // table->IsResetAllRequest = true;
3751 if (flags_for_section_to_display & ImGuiTableFlags_Reorderable)
3752 if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetOrder), NULL, false, !table->IsDefaultDisplayOrder)) // PS: cannot be hidden because it would mess with drag reordering.
3753 table->IsResetDisplayOrderRequest = true;
3754 if (flags_for_section_to_display & ImGuiTableFlags_Hideable)
3755 if (MenuItem(LocalizeGetMsg(ImGuiLocKey_TableResetVisibility), NULL, false, !table->IsDefaultVisibility))
3756 table->IsResetVisibilityRequest = true;
3757 EndMenu();
3758 }
3759
3760 // Sorting
3761 // (modify TableOpenContextMenu() to add _Sortable flag if enabling this)
3762#if 0
3763 if ((flags_for_section_to_display & ImGuiTableFlags_Sortable) && column != NULL && (column->Flags & ImGuiTableColumnFlags_NoSort) == 0)
3764 {
3765 if (want_separator)
3766 Separator();
3767 want_separator = true;
3768
3769 bool append_to_sort_specs = g.IO.KeyShift;
3770 if (MenuItem("Sort in Ascending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Ascending, (column->Flags & ImGuiTableColumnFlags_NoSortAscending) == 0))
3771 TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Ascending, append_to_sort_specs);
3772 if (MenuItem("Sort in Descending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Descending, (column->Flags & ImGuiTableColumnFlags_NoSortDescending) == 0))
3773 TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Descending, append_to_sort_specs);
3774 }
3775#endif
3776
3777 // Hiding / Visibility
3778 if (flags_for_section_to_display & ImGuiTableFlags_Hideable)
3779 {
3780 if (want_separator)
3781 Separator();
3782 want_separator = true;
3783
3784 // 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).
3785 // 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.
3786 const bool is_reordering = (g.ActiveId != 0 && g.ActiveIdWindow == g.CurrentWindow && table->ReorderColumn != -1 && g.ActiveIdHasBeenEditedBefore); // FIXME: This is a bit of a hack.
3787 const int reorder_src_order = is_reordering ? table->Columns[table->ReorderColumn].DisplayOrder : -1;
3788 const int reorder_min_order = is_reordering ? TableGetMaxDisplayOrderAllowed(table, reorder_src_order, 0) : 0;
3789 const int reorder_max_order = is_reordering ? TableGetMaxDisplayOrderAllowed(table, reorder_src_order, table->ColumnsCount - 1) : table->ColumnsCount - 1;
3790 PushItemFlag(ImGuiItemFlags_AutoClosePopups, false);
3791 for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
3792 {
3793 const int column_n = table->DisplayOrderToIndex[order_n];
3794 ImGuiTableColumn* column = &table->Columns[column_n];
3795 if (column->Flags & ImGuiTableColumnFlags_Disabled)
3796 continue;
3797
3798 const char* name = TableGetColumnName(table, column_n);
3799 if (name == NULL || name[0] == 0)
3800 name = "<Unknown>";
3801
3802 // Make sure we can't hide the last active column
3803 bool menu_item_enabled = (column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true;
3804 if (column->IsUserEnabled && table->ColumnsEnabledCount <= 1)
3805 menu_item_enabled = false;
3806 if (is_reordering && (column->DisplayOrder < reorder_min_order || column->DisplayOrder > reorder_max_order))
3807 menu_item_enabled = false;
3808 if (MenuItemForColumnReorder(name, column->IsUserEnabled, menu_item_enabled))
3809 column->IsUserEnabledNextFrame = !column->IsUserEnabled;
3810
3811 // Drag to reorder
3812 // FIXME: It is currently not possible to reorder columns marked with ImGuiTableColumnFlags_NoHide.
3813 if (IsItemActive() && IsMouseDragging(0) && g.ActiveIdSource == ImGuiInputSource_Mouse && (table->Flags & ImGuiTableFlags_Reorderable))
3814 {
3815 g.ActiveIdHasBeenEditedBefore = true; // Disable toggle in MenuItemForColumnReorder() + start dimming to display allowed reorder targets.
3816 table->ReorderColumn = (ImGuiTableColumnIdx)column_n;
3817 if (!IsItemHovered())
3818 {
3819 int reorder_dir = (g.IO.MousePos.y < (g.LastItemData.Rect.Min.y + g.LastItemData.Rect.Max.y) * 0.5f) ? -1 : +1;
3820 float reorder_amount = (reorder_dir < 0 ? g.LastItemData.Rect.Min.y - g.IO.MousePos.y : g.IO.MousePos.y - g.LastItemData.Rect.Max.y) / g.LastItemData.Rect.GetHeight();
3821 int dst_order = column->DisplayOrder + (int)ImCeil(reorder_amount) * reorder_dir; // Estimated target order, will be validated and clamped.
3822 TableQueueSetColumnDisplayOrder(table, column_n, dst_order);
3823 }
3824 }
3825 }
3826 PopItemFlag();
3827 }
3828}
3829
3830//-------------------------------------------------------------------------
3831// [SECTION] Tables: Settings (.ini data)
3832//-------------------------------------------------------------------------
3833// FIXME: The binding/finding/creating flow are too confusing.
3834//-------------------------------------------------------------------------
3835// - TableSettingsInit() [Internal]
3836// - TableSettingsCalcChunkSize() [Internal]
3837// - TableSettingsCreate() [Internal]
3838// - TableSettingsFindByID() [Internal]
3839// - TableGetBoundSettings() [Internal]
3840// - TableResetSettings()
3841// - TableSaveSettings() [Internal]
3842// - TableLoadSettings() [Internal]
3843// - TableLoadSettingsForColumns() [Internal]
3844// - TableSettingsHandler_ClearAll() [Internal]
3845// - TableSettingsHandler_ApplyAll() [Internal]
3846// - TableSettingsHandler_ReadOpen() [Internal]
3847// - TableSettingsHandler_ReadLine() [Internal]
3848// - TableSettingsHandler_WriteAll() [Internal]
3849// - TableSettingsInstallHandler() [Internal]
3850//-------------------------------------------------------------------------
3851// [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings.
3852// [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table.
3853// [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty.
3854// [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file.
3855//-------------------------------------------------------------------------
3856
3857// Clear and initialize empty settings instance
3858static void TableSettingsInit(ImGuiTableSettings* settings, ImGuiID id, int columns_count, int columns_count_max)
3859{
3860 IM_PLACEMENT_NEW(settings) ImGuiTableSettings();
3861 ImGuiTableColumnSettings* settings_column = settings->GetColumnSettings();
3862 for (int n = 0; n < columns_count_max; n++, settings_column++)
3863 IM_PLACEMENT_NEW(settings_column) ImGuiTableColumnSettings();
3864 settings->ID = id;
3865 settings->ColumnsCount = (ImGuiTableColumnIdx)columns_count;
3866 settings->ColumnsCountMax = (ImGuiTableColumnIdx)columns_count_max;
3867 settings->WantApply = true;
3868}
3869
3870static size_t TableSettingsCalcChunkSize(int columns_count)
3871{
3872 return sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings);
3873}
3874
3875ImGuiTableSettings* ImGui::TableSettingsCreate(ImGuiID id, int columns_count)
3876{
3877 ImGuiContext& g = *GImGui;
3878 if (ImGuiTableSettings* settings = TableSettingsFindByID(id))
3879 {
3880 if (settings->ColumnsCountMax >= columns_count)
3881 {
3882 TableSettingsInit(settings, id, columns_count, settings->ColumnsCountMax); // Recycle
3883 return settings;
3884 }
3885 settings->ID = 0; // Invalidate storage, we won't fit because of a count change
3886 }
3887 ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(TableSettingsCalcChunkSize(columns_count));
3888 TableSettingsInit(settings, id, columns_count, columns_count);
3889 return settings;
3890}
3891
3892// Find existing settings
3893ImGuiTableSettings* ImGui::TableSettingsFindByID(ImGuiID id)
3894{
3895 // FIXME-OPT: Might want to store a lookup map for this?
3896 ImGuiContext& g = *GImGui;
3897 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
3898 if (settings->ID == id)
3899 return settings;
3900 return NULL;
3901}
3902
3903// Get settings for a given table, NULL if none
3904ImGuiTableSettings* ImGui::TableGetBoundSettings(ImGuiTable* table)
3905{
3906 if (table->SettingsOffset == -1)
3907 return NULL;
3908 ImGuiContext& g = *GImGui;
3909 ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset);
3910 IM_ASSERT(settings->ID == table->ID);
3911 return settings;
3912}
3913
3914// Restore initial state of table (with or without saved settings)
3915void ImGui::TableResetSettings(ImGuiTable* table)
3916{
3917 table->IsInitializing = table->IsSettingsDirty = true;
3918 table->IsResetAllRequest = false;
3919 table->IsSettingsRequestLoad = false; // Don't reload from ini
3920 table->SettingsLoadedFlags = ImGuiTableFlags_None; // Mark as nothing loaded so our initialized data becomes authoritative
3921}
3922
3923void ImGui::TableSaveSettings(ImGuiTable* table)
3924{
3925 table->IsSettingsDirty = false;
3926 if (table->Flags & ImGuiTableFlags_NoSavedSettings)
3927 return;
3928
3929 // Bind or create settings data
3930 ImGuiContext& g = *GImGui;
3931 ImGuiTableSettings* settings = TableGetBoundSettings(table);
3932 if (settings != NULL && table->ColumnsCount > settings->ColumnsCountMax)
3933 {
3934 settings->ID = 0; // Invalidate storage, we won't fit because of a count change
3935 settings = NULL;
3936 }
3937 if (settings == NULL)
3938 {
3939 settings = TableSettingsCreate(table->ID, table->ColumnsCount);
3940 table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);
3941 }
3942 settings->ColumnsCount = (ImGuiTableColumnIdx)table->ColumnsCount;
3943 settings->LastUsedDate = g.SessionDate;
3944
3945 // Serialize ImGuiTable/ImGuiTableColumn into ImGuiTableSettings/ImGuiTableColumnSettings
3946 IM_ASSERT(settings->ID == table->ID);
3947 IM_ASSERT(settings->ColumnsCount == table->ColumnsCount && settings->ColumnsCountMax >= settings->ColumnsCount);
3948 ImGuiTableColumn* column = table->Columns.Data;
3949 ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
3950
3951 bool save_ref_scale = false;
3952 settings->SaveFlags = ImGuiTableFlags_None;
3953 for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++)
3954 {
3955 const float width_or_weight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? column->StretchWeight : column->WidthRequest;
3956 column_settings->ID = column->ID;
3957 column_settings->WidthOrWeight = width_or_weight;
3958 column_settings->Index = (ImGuiTableColumnIdx)n;
3959 column_settings->DisplayOrder = column->DisplayOrder;
3960 column_settings->SortOrder = column->SortOrder;
3961 column_settings->SortDirection = column->SortDirection;
3962 column_settings->IsEnabled = column->IsUserEnabled;
3963 column_settings->IsStretch = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0;
3964 if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) == 0)
3965 save_ref_scale = true;
3966
3967 // We skip saving some data in the .ini file when they are unnecessary to restore our state.
3968 // Note that fixed width where initial width was derived from auto-fit will always be saved as InitStretchWeightOrWidth will be 0.0f.
3969 // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present.
3970 if (width_or_weight != column->InitStretchWeightOrWidth)
3971 settings->SaveFlags |= ImGuiTableFlags_Resizable;
3972 if (column->DisplayOrder != n)
3973 settings->SaveFlags |= ImGuiTableFlags_Reorderable;
3974 if (column->SortOrder != -1)
3975 settings->SaveFlags |= ImGuiTableFlags_Sortable;
3976 if (column->IsUserEnabled != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0))
3977 settings->SaveFlags |= ImGuiTableFlags_Hideable;
3978 }
3979 settings->SaveFlags &= table->Flags;
3980 settings->RefScale = save_ref_scale ? table->RefScale : 0.0f;
3981
3982 MarkIniSettingsDirty();
3983}
3984
3985void ImGui::TableLoadSettings(ImGuiTable* table)
3986{
3987 ImGuiContext& g = *GImGui;
3988 if (table->Flags & ImGuiTableFlags_NoSavedSettings)
3989 {
3990 table->IsSettingsRequestLoad = false; // Done
3991 return;
3992 }
3993
3994 // Bind settings
3995 ImGuiTableSettings* settings;
3996 if (table->SettingsOffset == -1)
3997 {
3998 settings = TableSettingsFindByID(table->ID);
3999 if (settings == NULL)
4000 return;
4001 if (settings->ColumnsCount != table->ColumnsCount) // Allow settings if columns count changed. We could otherwise decide to return...
4002 table->IsSettingsDirty = true;
4003 table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);
4004 }
4005 else
4006 {
4007 settings = TableGetBoundSettings(table);
4008 }
4009
4010 table->SettingsLoadedFlags = settings->SaveFlags;
4011 table->RefScale = settings->RefScale;
4012 settings->LastUsedDate = g.SessionDate;
4013 // TableUpdateLayout() will then call TableLoadSettingsForColumns() to apply the data.
4014}
4015
4016// NB: This was written to be similar to the logic in TableReconcileColumns().
4017void ImGui::TableLoadSettingsForColumns(ImGuiTable* table)
4018{
4019 for (ImGuiTableColumn& column : table->Columns)
4020 column.IsLoadedSettings = false;
4021 ImGuiTableSettings* settings = TableGetBoundSettings(table);
4022 if (settings == NULL)
4023 return;
4024
4025 table->SettingsLoadedFlags |= ImGuiTableFlags_Reorderable; // We handle above in code above.
4026
4027 // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn
4028 ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
4029
4030 // Fast path
4031 int matches = 0;
4032 for (int n = 0; n < table->ColumnsCount; n++)
4033 {
4034 if (n >= settings->ColumnsCount || column_settings[n].ID != table->Columns[n].ID)
4035 break;
4036 TableLoadSettingsForColumn(&table->Columns[n], &column_settings[n], settings->SaveFlags);
4037 matches++;
4038 }
4039 if (matches == settings->ColumnsCount)
4040 return;
4041 const int settings_start_n = matches; // Small optimization
4042 for (int n = settings_start_n; n < settings->ColumnsCount; n++)
4043 column_settings[n].IsLoaded = false;
4044
4045 // Find matches for named columns
4046 for (ImGuiTableColumn& column : table->Columns)
4047 if (column.ID != 0 && !column.IsLoadedSettings)
4048 for (int n = settings_start_n; n < settings->ColumnsCount; n++)
4049 if (column_settings[n].ID == column.ID && !column_settings[n].IsLoaded)
4050 {
4051 TableLoadSettingsForColumn(&column, &column_settings[n], settings->SaveFlags);
4052 matches++;
4053 break;
4054 }
4055
4056 // Remaining entries are matched sequentially
4057 int dst_idx = 0;
4058 for (int n = settings_start_n; n < settings->ColumnsCount; n++)
4059 if (!column_settings[n].IsLoaded)
4060 {
4061 while (dst_idx < table->ColumnsCount && table->Columns[dst_idx].IsLoadedSettings)
4062 dst_idx++;
4063 if (dst_idx >= table->ColumnsCount)
4064 break;
4065 TableLoadSettingsForColumn(&table->Columns[dst_idx], &column_settings[n], settings->SaveFlags);
4066 dst_idx++;
4067 }
4068}
4069
4070void ImGui::TableLoadSettingsForColumn(ImGuiTableColumn* column, ImGuiTableColumnSettings* column_settings, ImGuiTableFlags load_flags)
4071{
4072 column->IsLoadedSettings = true;
4073 column_settings->IsLoaded = true;
4074 if (load_flags & ImGuiTableFlags_Resizable)
4075 {
4076 if (column_settings->IsStretch)
4077 column->StretchWeight = column_settings->WidthOrWeight;
4078 else
4079 column->WidthRequest = column_settings->WidthOrWeight;
4080 column->AutoFitQueue = 0x00;
4081 }
4082 if (load_flags & ImGuiTableFlags_Reorderable)
4083 column->DisplayOrder = column_settings->DisplayOrder;
4084 else
4085 column->DisplayOrder = column_settings->Index; // Because default depends on previous Index, we need to set that up and cannot rely on TableInitColumnDefaults()
4086 if ((load_flags & ImGuiTableFlags_Hideable) && column_settings->IsEnabled != -1)
4087 column->IsUserEnabled = column->IsUserEnabledNextFrame = (column_settings->IsEnabled == 1);
4088 column->SortOrder = column_settings->SortOrder;
4089 column->SortDirection = column_settings->SortDirection;
4090}
4091
4092struct ImGuiTableFixDisplayOrderColumnData
4093{
4094 ImGuiTableColumnIdx Idx;
4095 ImGuiTable* Table; // This is unfortunate but we don't have userdata in qsort api.
4096};
4097
4098// Sort by DisplayOrder and then Index
4099static int IMGUI_CDECL TableFixDisplayOrderComparer(const void* lhs, const void* rhs)
4100{
4101 const ImGuiTable* table = ((const ImGuiTableFixDisplayOrderColumnData*)lhs)->Table;
4102 const ImGuiTableColumnIdx lhs_idx = ((const ImGuiTableFixDisplayOrderColumnData*)lhs)->Idx;
4103 const ImGuiTableColumnIdx rhs_idx = ((const ImGuiTableFixDisplayOrderColumnData*)rhs)->Idx;
4104 // Assume ImGuiTableColumnIdx == signed short, to turn -1 into a large value so that it always sort after.
4105 const int order_delta = ((unsigned short)table->Columns[lhs_idx].DisplayOrder - (unsigned short)table->Columns[rhs_idx].DisplayOrder);
4106 return (order_delta > 0) ? +1 : (order_delta < 0) ? -1 : (lhs_idx > rhs_idx) ? +1 : -1;
4107}
4108
4109// Fix invalid display order data: compact values (0,1,3 -> 0,1,2); preserve relative order (0,3,1 -> 0,2,1); deduplicate (0,4,1,1 -> 0,3,1,2)
4110void ImGui::TableFixDisplayOrder(ImGuiTable* table)
4111{
4112 ImGuiContext& g = *GImGui;
4113 g.TempBuffer.reserve((int)(sizeof(ImGuiTableFixDisplayOrderColumnData) * table->ColumnsCount)); // FIXME: Maybe wrap those two lines as a helper.
4114 ImGuiTableFixDisplayOrderColumnData* fdo_columns = (ImGuiTableFixDisplayOrderColumnData*)(void*)g.TempBuffer.Data;
4115 for (int n = 0; n < table->ColumnsCount; n++)
4116 {
4117 fdo_columns[n].Idx = (ImGuiTableColumnIdx)n;
4118 fdo_columns[n].Table = table;
4119 }
4120 ImQsort(fdo_columns, (size_t)table->ColumnsCount, sizeof(ImGuiTableFixDisplayOrderColumnData), TableFixDisplayOrderComparer);
4121 for (int n = 0; n < table->ColumnsCount; n++)
4122 table->Columns[fdo_columns[n].Idx].DisplayOrder = (ImGuiTableColumnIdx)n;
4123 for (int n = 0; n < table->ColumnsCount; n++)
4124 table->DisplayOrderToIndex[table->Columns[n].DisplayOrder] = (ImGuiTableColumnIdx)n;
4125}
4126
4127static void TableSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
4128{
4129 ImGuiContext& g = *ctx;
4130 for (int i = 0; i != g.Tables.GetMapSize(); i++)
4131 if (ImGuiTable* table = g.Tables.TryGetMapData(i))
4132 table->SettingsOffset = -1;
4133 g.SettingsTables.clear();
4134}
4135
4136static void TableSettingsHandler_Cleanup(ImGuiContext* ctx, ImGuiSettingsHandler*, ImGuiSettingsCleanupArgs* args)
4137{
4138 ImGuiContext& g = *ctx;
4139 for (int i = 0; i != g.Tables.GetMapSize(); i++)
4140 if (ImGuiTable* table = g.Tables.TryGetMapData(i))
4141 table->SettingsOffset = -1;
4142 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
4143 {
4144 const bool is_valid = settings->LastUsedDate.IsValid();
4145 if (args->_DiscardOlderThanDate != 0 && settings->LastUsedDate.Unpack() < args->_DiscardOlderThanDate)
4146 settings->ID = 0;
4147 else if (args->DiscardWhenMissingDate && !is_valid)
4148 settings->ID = 0;
4149 else if (args->SetCurrentSessionDateToAll || (args->SetCurrentSessionDateWhenMissingDate && !is_valid))
4150 settings->LastUsedDate = g.SessionDate;
4151 }
4152}
4153
4154// Apply to existing windows (if any)
4155static void TableSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
4156{
4157 ImGuiContext& g = *ctx;
4158 for (int i = 0; i != g.Tables.GetMapSize(); i++)
4159 if (ImGuiTable* table = g.Tables.TryGetMapData(i))
4160 {
4161 table->IsSettingsRequestLoad = true;
4162 table->SettingsOffset = -1;
4163 }
4164}
4165
4166static void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
4167{
4168 // FIXME: As topology changes are allowed, strictly speaking a >= IMGUI_TABLE_MAX_COLUMNS tables stored in .ini file
4169 // that was emitted with a higher max count could still be meaningful in some unlikely cases.
4170 // We might want to use another MAX defined as (1<<(sizeof(ImGuiTableColumnIdx)*8-1))-1.
4171 ImGuiID id = 0;
4172 int columns_count = 0;
4173 if (sscanf(name, "0x%08X,%d", &id, &columns_count) < 2 || columns_count <= 0 || columns_count >= IMGUI_TABLE_MAX_COLUMNS)
4174 return NULL;
4175 return ImGui::TableSettingsCreate(id, columns_count);
4176}
4177
4178static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
4179{
4180 // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v"
4181 ImGuiTableSettings* settings = (ImGuiTableSettings*)entry;
4182 float f = 0.0f;
4183 int column_n = 0, r = 0, n = 0;
4184
4185 if (sscanf(line, "RefScale=%f", &f) == 1) { settings->RefScale = f; return; }
4186 if (sscanf(line, "LastUsed=%d", &n) == 1) { settings->LastUsedDate = n; return; }
4187
4188 if (sscanf(line, "Column %d%n", &column_n, &r) == 1)
4189 {
4190 if (column_n < 0 || column_n >= settings->ColumnsCount)
4191 return;
4192 line = ImStrSkipBlank(line + r);
4193 char c = 0;
4194 ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n;
4195 column->Index = (ImGuiTableColumnIdx)column_n;
4196 if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r)==1) { line = ImStrSkipBlank(line + r); } // FIXME-LEGACY: Removed 2025/11/12, was never properly set.
4197 if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = (float)n; column->IsStretch = 0; settings->SaveFlags |= ImGuiTableFlags_Resizable; }
4198 if (sscanf(line, "Weight=%f%n", &f, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = f; column->IsStretch = 1; settings->SaveFlags |= ImGuiTableFlags_Resizable; }
4199 if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->IsEnabled = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; }
4200 if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImGuiTableColumnIdx)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; }
4201 if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImGuiTableColumnIdx)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; }
4202 if (sscanf(line, "ID=0x%08X%n", (ImU32*)&n, &r) == 1) { line = ImStrSkipBlank(line + r); column->ID = (ImGuiID)n; }
4203 }
4204}
4205
4206static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
4207{
4208 ImGuiContext& g = *ctx;
4209 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
4210 {
4211 if (settings->ID == 0) // Skip ditched settings
4212 continue;
4213
4214 // TableSaveSettings() may clear some of those flags when we establish that the data can be stripped
4215 // (e.g. Order was unchanged)
4216 const bool save_size = (settings->SaveFlags & ImGuiTableFlags_Resizable) != 0;
4217 const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0;
4218 const bool save_order = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0;
4219 const bool save_sort = (settings->SaveFlags & ImGuiTableFlags_Sortable) != 0;
4220 // We need to save the [Table] entry even if all the bools are false, since this records a table with "default settings".
4221
4222 buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve
4223 buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount);
4224 if (settings->RefScale != 0.0f)
4225 buf->appendf("RefScale=%g\n", settings->RefScale);
4226 ImGuiTableColumnSettings* column = settings->GetColumnSettings();
4227 for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++)
4228 {
4229 // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v"
4230 bool save_column = save_size || save_visible || save_order || (save_sort && column->SortOrder != -1);
4231 if (!save_column)
4232 continue;
4233 buf->appendf("Column %-2d", column_n);
4234 if (save_size && column->IsStretch) { buf->appendf(" Weight=%.4f", column->WidthOrWeight); }
4235 if (save_size && !column->IsStretch) { buf->appendf(" Width=%d", (int)column->WidthOrWeight); }
4236 if (save_visible) { buf->appendf(" Visible=%d", column->IsEnabled); }
4237 if (save_order) { buf->appendf(" Order=%d", column->DisplayOrder); }
4238 if (save_sort && column->SortOrder != -1) { buf->appendf(" Sort=%d%c", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^'); }
4239 if (column->ID != 0) { buf->appendf(" ID=0x%08X", column->ID); }
4240 buf->append("\n");
4241 }
4242 if (g.IO.ConfigIniSettingsSaveLastUsedDate)
4243 if (int last_used_date = settings->LastUsedDate.Unpack())
4244 buf->appendf("LastUsed=%08d\n", last_used_date);
4245 buf->append("\n");
4246 }
4247}
4248
4249void ImGui::TableSettingsAddSettingsHandler()
4250{
4251 ImGuiSettingsHandler ini_handler;
4252 ini_handler.TypeName = "Table";
4253 ini_handler.TypeHash = ImHashStr("Table");
4254 ini_handler.ClearAllFn = TableSettingsHandler_ClearAll;
4255 ini_handler.CleanupFn = TableSettingsHandler_Cleanup;
4256 ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen;
4257 ini_handler.ReadLineFn = TableSettingsHandler_ReadLine;
4258 ini_handler.ApplyAllFn = TableSettingsHandler_ApplyAll;
4259 ini_handler.WriteAllFn = TableSettingsHandler_WriteAll;
4260 AddSettingsHandler(&ini_handler);
4261}
4262
4263//-------------------------------------------------------------------------
4264// [SECTION] Tables: Garbage Collection
4265//-------------------------------------------------------------------------
4266// - TableRemove() [Internal]
4267// - TableGcCompactTransientBuffers() [Internal]
4268// - TableGcCompactSettings() [Internal]
4269//-------------------------------------------------------------------------
4270
4271// Remove Table data (currently only used by TestEngine)
4272void ImGui::TableRemove(ImGuiTable* table)
4273{
4274 //IMGUI_DEBUG_PRINT("TableRemove() id=0x%08X\n", table->ID);
4275 ImGuiContext& g = *GImGui;
4276 int table_idx = g.Tables.GetIndex(table);
4277 //memset(table->RawData.Data, 0, table->RawData.size_in_bytes());
4278 //memset(table, 0, sizeof(ImGuiTable));
4279 g.Tables.Remove(table->ID, table);
4280 g.TablesLastTimeActive[table_idx] = -1.0f;
4281}
4282
4283// Free up/compact internal Table buffers for when it gets unused
4284void ImGui::TableGcCompactTransientBuffers(ImGuiTable* table)
4285{
4286 //IMGUI_DEBUG_PRINT("TableGcCompactTransientBuffers() id=0x%08X\n", table->ID);
4287 ImGuiContext& g = *GImGui;
4288 IM_ASSERT(table->MemoryCompacted == false);
4289 table->SortSpecs.Specs = NULL;
4290 table->SortSpecsMulti.clear();
4291 table->IsSortSpecsDirty = true; // FIXME: In theory shouldn't have to leak into user performing a sort on resume.
4292 table->ColumnsNames.clear();
4293 table->MemoryCompacted = true;
4294 for (int n = 0; n < table->ColumnsCount; n++)
4295 table->Columns[n].NameOffset = -1;
4296 g.TablesLastTimeActive[g.Tables.GetIndex(table)] = -1.0f;
4297}
4298
4299void ImGui::TableGcCompactTransientBuffers(ImGuiTableTempData* temp_data)
4300{
4301 temp_data->AngledHeadersRequests.clear();
4302 temp_data->DrawSplitter.ClearFreeMemory();
4303 temp_data->LastTimeActive = -1.0f;
4304}
4305
4306// Compact and remove unused or resize settings data (only TestEngine mark unused, but resizing table down can lead to compaction)
4307void ImGui::TableGcCompactSettings()
4308{
4309 ImGuiContext& g = *GImGui;
4310 int required_memory = 0;
4311 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
4312 if (settings->ID != 0)
4313 required_memory += (int)TableSettingsCalcChunkSize(settings->ColumnsCount);
4314 if (required_memory == g.SettingsTables.Buf.Size)
4315 return;
4316 ImChunkStream<ImGuiTableSettings> new_chunk_stream;
4317 new_chunk_stream.Buf.reserve(required_memory);
4318 for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
4319 if (settings->ID != 0)
4320 memcpy(new_chunk_stream.alloc_chunk(TableSettingsCalcChunkSize(settings->ColumnsCount)), settings, TableSettingsCalcChunkSize(settings->ColumnsCount));
4321 g.SettingsTables.swap(new_chunk_stream);
4322 for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
4323 if (ImGuiTable* table = g.Tables.TryGetMapData(table_n))
4324 table->SettingsOffset = -1;
4325}
4326
4327
4328//-------------------------------------------------------------------------
4329// [SECTION] Tables: Debugging
4330//-------------------------------------------------------------------------
4331// - DebugNodeTable() [Internal]
4332// - DebugNodeTableSettings() [Internal]
4333//-------------------------------------------------------------------------
4334
4335#ifndef IMGUI_DISABLE_DEBUG_TOOLS
4336
4337static const char* DebugNodeTableGetSizingPolicyDesc(ImGuiTableFlags sizing_policy)
4338{
4339 sizing_policy &= ImGuiTableFlags_SizingMask_;
4340 if (sizing_policy == ImGuiTableFlags_SizingFixedFit) { return "FixedFit"; }
4341 if (sizing_policy == ImGuiTableFlags_SizingFixedSame) { return "FixedSame"; }
4342 if (sizing_policy == ImGuiTableFlags_SizingStretchProp) { return "StretchProp"; }
4343 if (sizing_policy == ImGuiTableFlags_SizingStretchSame) { return "StretchSame"; }
4344 return "N/A";
4345}
4346
4347void ImGui::DebugNodeTable(ImGuiTable* table)
4348{
4349 ImGuiContext& g = *GImGui;
4350 const bool is_active = (table->LastFrameActive >= g.FrameCount - 2); // Note that fully clipped early out scrolling tables will appear as inactive here.
4351 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
4352 bool open = TreeNode(table, "Table 0x%08X (%d columns, in '%s')%s", table->ID, table->ColumnsCount, table->OuterWindow->Name, is_active ? "" : " *Inactive*");
4353 if (!is_active) { PopStyleColor(); }
4354 if (IsItemHovered())
4355 GetForegroundDrawList(table->OuterWindow)->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255));
4356 if (IsItemVisible() && table->HoveredColumnBody != -1)
4357 GetForegroundDrawList(table->OuterWindow)->AddRect(GetItemRectMin(), GetItemRectMax(), IM_COL32(255, 255, 0, 255));
4358 if (!open)
4359 return;
4360 if (table->InstanceCurrent > 0)
4361 Text("** %d instances of same table! Some data below will refer to last instance.", table->InstanceCurrent + 1);
4362 if (g.IO.ConfigDebugIsDebuggerPresent)
4363 {
4364 if (DebugBreakButton("**DebugBreak**", "in BeginTable()"))
4365 g.DebugBreakInTable = table->ID;
4366 SameLine();
4367 }
4368
4369 bool clear_settings = SmallButton("Clear settings");
4370 BulletText("OuterRect: Pos: (%.1f,%.1f) Size: (%.1f,%.1f) Sizing: '%s'", table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.GetWidth(), table->OuterRect.GetHeight(), DebugNodeTableGetSizingPolicyDesc(table->Flags));
4371 BulletText("ColumnsGivenWidth: %.1f, ColumnsAutoFitWidth: %.1f, InnerWidth: %.1f%s", table->ColumnsGivenWidth, table->ColumnsAutoFitWidth, table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : "");
4372 BulletText("CellPaddingX: %.1f, CellSpacingX: %.1f/%.1f, OuterPaddingX: %.1f", table->CellPaddingX, table->CellSpacingX1, table->CellSpacingX2, table->OuterPaddingX);
4373 BulletText("HoveredColumnBody: %d, HoveredColumnBorder: %d", table->HoveredColumnBody, table->HoveredColumnBorder);
4374 BulletText("ResizedColumn: %d, HeldHeaderColumn: %d, ReorderColumn: %d", table->LastResizedColumn, table->LastHeldHeaderColumn, table->ReorderColumn);
4375 for (int n = 0; n < table->InstanceCurrent + 1; n++)
4376 {
4377 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, n);
4378 BulletText("Instance %d: HoveredRow: %d, LastOuterHeight: %.2f", n, table_instance->HoveredRowLast, table_instance->LastOuterHeight);
4379 }
4380 //BulletText("BgDrawChannels: %d/%d", 0, table->BgDrawChannelUnfrozen);
4381 float sum_weights = 0.0f;
4382 for (int n = 0; n < table->ColumnsCount; n++)
4383 if (table->Columns[n].Flags & ImGuiTableColumnFlags_WidthStretch)
4384 sum_weights += table->Columns[n].StretchWeight;
4385 for (int n = 0; n < table->ColumnsCount; n++)
4386 {
4387 ImGuiTableColumn* column = &table->Columns[n];
4388 const char* name = TableGetColumnName(table, n);
4389 char buf[512];
4390 ImFormatString(buf, IM_COUNTOF(buf),
4391 "Column %d order %d '%s': offset %+.2f to %+.2f%s\n"
4392 "Enabled: %d, VisibleX/Y: %d/%d, RequestOutput: %d, SkipItems: %d, DrawChannels: %d,%d\n"
4393 "WidthGiven: %.1f, Request/Auto: %.1f/%.1f, StretchWeight: %.3f (%.1f%%)\n"
4394 "MinX: %.1f, MaxX: %.1f (%+.1f), ClipRect: %.1f to %.1f (+%.1f)\n"
4395 "ContentWidth: %.1f,%.1f, HeadersUsed/Ideal %.1f/%.1f\n"
4396 "Sort: %d%s, UserData: 0x%08X, Flags: 0x%04X: %s%s%s..",
4397 n, column->DisplayOrder, name, column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, (n < table->FreezeColumnsRequest) ? " (Frozen)" : "",
4398 column->IsEnabled, column->IsVisibleX, column->IsVisibleY, column->IsRequestOutput, column->IsSkipItems, column->DrawChannelFrozen, column->DrawChannelUnfrozen,
4399 column->WidthGiven, column->WidthRequest, column->WidthAuto, column->StretchWeight, column->StretchWeight > 0.0f ? (column->StretchWeight / sum_weights) * 100.0f : 0.0f,
4400 column->MinX, column->MaxX, column->MaxX - column->MinX, column->ClipRect.Min.x, column->ClipRect.Max.x, column->ClipRect.Max.x - column->ClipRect.Min.x,
4401 column->ContentMaxXFrozen - column->WorkMinX, column->ContentMaxXUnfrozen - column->WorkMinX, column->ContentMaxXHeadersUsed - column->WorkMinX, column->ContentMaxXHeadersIdeal - column->WorkMinX,
4402 column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? " (Asc)" : (column->SortDirection == ImGuiSortDirection_Descending) ? " (Des)" : "", column->UserData, column->Flags,
4403 (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "",
4404 (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "",
4405 (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : "");
4406 Bullet();
4407 Selectable(buf);
4408 if (IsItemHovered())
4409 {
4410 ImRect r(column->MinX, table->OuterRect.Min.y, column->MaxX, table->OuterRect.Max.y);
4411 GetForegroundDrawList(table->OuterWindow)->AddRect(r.Min, r.Max, IM_COL32(255, 255, 0, 255));
4412 }
4413 }
4414 if (ImGuiTableSettings* settings = TableGetBoundSettings(table))
4415 DebugNodeTableSettings(settings, table);
4416 if (clear_settings)
4417 table->IsResetAllRequest = true; // Queue a call to TableResetSettings()
4418 TreePop();
4419}
4420
4421void ImGui::DebugNodeTableSettings(ImGuiTableSettings* settings, ImGuiTable* table)
4422{
4423 if (settings->ID == 0)
4424 PushID(settings);
4425 const bool open = TreeNode((void*)(intptr_t)settings->ID, "Settings 0x%08X (%d columns)", settings->ID, settings->ColumnsCount);
4426 const bool hovered = IsItemHovered();
4427 if (hovered && table == NULL && settings->ID != 0)
4428 table = TableFindByID(settings->ID);
4429 if (hovered && table != NULL)
4430 GetForegroundDrawList(table->OuterWindow)->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255));
4431 if (open)
4432 {
4433 BulletText("SaveFlags: 0x%08X", settings->SaveFlags);
4434 BulletText("ColumnsCount: %d (max %d)", settings->ColumnsCount, settings->ColumnsCountMax);
4435 for (int n = 0; n < settings->ColumnsCount; n++)
4436 {
4437 ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n];
4438 ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? (ImGuiSortDirection)column_settings->SortDirection : ImGuiSortDirection_None;
4439 BulletText("Column %d Order %d SortOrder %2d %s Vis %d %s %7.3f ID 0x%08X",
4440 n, column_settings->DisplayOrder, column_settings->SortOrder,
4441 (sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---",
4442 column_settings->IsEnabled, column_settings->IsStretch ? "Weight" : "Width ", column_settings->WidthOrWeight, column_settings->ID);
4443 }
4444 TreePop();
4445 }
4446 if (settings->ID == 0)
4447 PopID();
4448}
4449
4450#else // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
4451
4452void ImGui::DebugNodeTable(ImGuiTable*) {}
4453void ImGui::DebugNodeTableSettings(ImGuiTableSettings*, ImGuiTable*) {}
4454
4455#endif
4456
4457
4458//-------------------------------------------------------------------------
4459// [SECTION] Columns, BeginColumns, EndColumns, etc.
4460// (This is a legacy API, prefer using BeginTable/EndTable!)
4461//-------------------------------------------------------------------------
4462// FIXME: sizing is lossy when columns width is very small (default width may turn negative etc.)
4463//-------------------------------------------------------------------------
4464// - SetWindowClipRectBeforeSetChannel() [Internal]
4465// - GetColumnIndex()
4466// - GetColumnsCount()
4467// - GetColumnOffset()
4468// - GetColumnWidth()
4469// - SetColumnOffset()
4470// - SetColumnWidth()
4471// - PushColumnClipRect() [Internal]
4472// - PushColumnsBackground() [Internal]
4473// - PopColumnsBackground() [Internal]
4474// - FindOrCreateColumns() [Internal]
4475// - GetColumnsID() [Internal]
4476// - BeginColumns()
4477// - NextColumn()
4478// - EndColumns()
4479// - Columns()
4480//-------------------------------------------------------------------------
4481
4482// [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences,
4483// they would meddle many times with the underlying ImDrawCmd.
4484// Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let
4485// the subsequent single call to SetCurrentChannel() does it things once.
4486void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect)
4487{
4488 ImVec4 clip_rect_vec4 = clip_rect.ToVec4();
4489 window->ClipRect = clip_rect;
4490 window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4;
4491 window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4;
4492}
4493
4494int ImGui::GetColumnIndex()
4495{
4496 ImGuiWindow* window = GetCurrentWindowRead();
4497 return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0;
4498}
4499
4500int ImGui::GetColumnsCount()
4501{
4502 ImGuiWindow* window = GetCurrentWindowRead();
4503 return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1;
4504}
4505
4506float ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm)
4507{
4508 return offset_norm * (columns->OffMaxX - columns->OffMinX);
4509}
4510
4511float ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset)
4512{
4513 return offset / (columns->OffMaxX - columns->OffMinX);
4514}
4515
4516static const float COLUMNS_HIT_RECT_HALF_THICKNESS = 4.0f;
4517
4518static float GetDraggedColumnOffset(ImGuiOldColumns* columns, int column_index)
4519{
4520 // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
4521 // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
4522 ImGuiContext& g = *GImGui;
4523 ImGuiWindow* window = g.CurrentWindow;
4524 IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
4525 IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
4526
4527 float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + ImTrunc(COLUMNS_HIT_RECT_HALF_THICKNESS * g.CurrentDpiScale) - window->Pos.x;
4528 x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
4529 if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths))
4530 x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
4531
4532 return x;
4533}
4534
4535float ImGui::GetColumnOffset(int column_index)
4536{
4537 ImGuiWindow* window = GetCurrentWindowRead();
4538 ImGuiOldColumns* columns = window->DC.CurrentColumns;
4539 if (columns == NULL)
4540 return 0.0f;
4541
4542 if (column_index < 0)
4543 column_index = columns->Current;
4544 IM_ASSERT(column_index < columns->Columns.Size);
4545
4546 const float t = columns->Columns[column_index].OffsetNorm;
4547 const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t);
4548 return x_offset;
4549}
4550
4551static float GetColumnWidthEx(ImGuiOldColumns* columns, int column_index, bool before_resize = false)
4552{
4553 if (column_index < 0)
4554 column_index = columns->Current;
4555
4556 float offset_norm;
4557 if (before_resize)
4558 offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
4559 else
4560 offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
4561 return ImGui::GetColumnOffsetFromNorm(columns, offset_norm);
4562}
4563
4564float ImGui::GetColumnWidth(int column_index)
4565{
4566 ImGuiContext& g = *GImGui;
4567 ImGuiWindow* window = g.CurrentWindow;
4568 ImGuiOldColumns* columns = window->DC.CurrentColumns;
4569 if (columns == NULL)
4570 return GetContentRegionAvail().x;
4571
4572 if (column_index < 0)
4573 column_index = columns->Current;
4574 return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
4575}
4576
4577void ImGui::SetColumnOffset(int column_index, float offset)
4578{
4579 ImGuiContext& g = *GImGui;
4580 ImGuiWindow* window = g.CurrentWindow;
4581 ImGuiOldColumns* columns = window->DC.CurrentColumns;
4582 IM_ASSERT(columns != NULL);
4583
4584 if (column_index < 0)
4585 column_index = columns->Current;
4586 IM_ASSERT(column_index < columns->Columns.Size);
4587
4588 const bool preserve_width = !(columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1);
4589 const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
4590
4591 if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow))
4592 offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
4593 columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX);
4594
4595 if (preserve_width)
4596 SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
4597}
4598
4599void ImGui::SetColumnWidth(int column_index, float width)
4600{
4601 ImGuiWindow* window = GetCurrentWindowRead();
4602 ImGuiOldColumns* columns = window->DC.CurrentColumns;
4603 IM_ASSERT(columns != NULL);
4604
4605 if (column_index < 0)
4606 column_index = columns->Current;
4607 SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
4608}
4609
4610void ImGui::PushColumnClipRect(int column_index)
4611{
4612 ImGuiWindow* window = GetCurrentWindowRead();
4613 ImGuiOldColumns* columns = window->DC.CurrentColumns;
4614 if (column_index < 0)
4615 column_index = columns->Current;
4616
4617 ImGuiOldColumnData* column = &columns->Columns[column_index];
4618 PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false);
4619}
4620
4621// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns)
4622void ImGui::PushColumnsBackground()
4623{
4624 ImGuiWindow* window = GetCurrentWindowRead();
4625 ImGuiOldColumns* columns = window->DC.CurrentColumns;
4626 if (columns->Count == 1)
4627 return;
4628
4629 // Optimization: avoid SetCurrentChannel() + PushClipRect()
4630 columns->HostBackupClipRect = window->ClipRect;
4631 SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect);
4632 columns->Splitter.SetCurrentChannel(window->DrawList, 0);
4633}
4634
4635void ImGui::PopColumnsBackground()
4636{
4637 ImGuiWindow* window = GetCurrentWindowRead();
4638 ImGuiOldColumns* columns = window->DC.CurrentColumns;
4639 if (columns->Count == 1)
4640 return;
4641
4642 // Optimization: avoid PopClipRect() + SetCurrentChannel()
4643 SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect);
4644 columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
4645}
4646
4647ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id)
4648{
4649 // We have few columns per window so for now we don't need bother much with turning this into a faster lookup.
4650 for (int n = 0; n < window->ColumnsStorage.Size; n++)
4651 if (window->ColumnsStorage[n].ID == id)
4652 return &window->ColumnsStorage[n];
4653
4654 window->ColumnsStorage.push_back(ImGuiOldColumns());
4655 ImGuiOldColumns* columns = &window->ColumnsStorage.back();
4656 columns->ID = id;
4657 return columns;
4658}
4659
4660ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count)
4661{
4662 ImGuiWindow* window = GetCurrentWindow();
4663
4664 // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
4665 // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
4666 PushID(0x11223347 + (str_id ? 0 : columns_count));
4667 ImGuiID id = window->GetID(str_id ? str_id : "columns");
4668 PopID();
4669
4670 return id;
4671}
4672
4673void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags)
4674{
4675 ImGuiContext& g = *GImGui;
4676 ImGuiWindow* window = GetCurrentWindow();
4677
4678 IM_ASSERT(columns_count >= 1);
4679 IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported
4680
4681 // Acquire storage for the columns set
4682 ImGuiID id = GetColumnsID(str_id, columns_count);
4683 ImGuiOldColumns* columns = FindOrCreateColumns(window, id);
4684 IM_ASSERT(columns->ID == id);
4685 columns->Current = 0;
4686 columns->Count = columns_count;
4687 columns->Flags = flags;
4688 window->DC.CurrentColumns = columns;
4689 window->DC.NavIsScrollPushableX = false; // Shortcut for NavUpdateCurrentWindowIsScrollPushableX();
4690
4691 columns->HostCursorPosY = window->DC.CursorPos.y;
4692 columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x;
4693 columns->HostInitialClipRect = window->ClipRect;
4694 columns->HostBackupParentWorkRect = window->ParentWorkRect;
4695 window->ParentWorkRect = window->WorkRect;
4696
4697 // Set state for first column
4698 // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect
4699 const float column_padding = g.Style.ItemSpacing.x;
4700 const float half_clip_extend_x = ImTrunc(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize));
4701 const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f);
4702 const float max_2 = window->WorkRect.Max.x + half_clip_extend_x;
4703 columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f);
4704 columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f);
4705 columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
4706
4707 // Clear data if columns count changed
4708 if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
4709 columns->Columns.resize(0);
4710
4711 // Initialize default widths
4712 columns->IsFirstFrame = (columns->Columns.Size == 0);
4713 if (columns->Columns.Size == 0)
4714 {
4715 columns->Columns.reserve(columns_count + 1);
4716 for (int n = 0; n < columns_count + 1; n++)
4717 {
4718 ImGuiOldColumnData column;
4719 column.OffsetNorm = n / (float)columns_count;
4720 columns->Columns.push_back(column);
4721 }
4722 }
4723
4724 for (int n = 0; n < columns_count; n++)
4725 {
4726 // Compute clipping rectangle
4727 ImGuiOldColumnData* column = &columns->Columns[n];
4728 float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n));
4729 float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
4730 column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
4731 column->ClipRect.ClipWithFull(window->ClipRect);
4732 }
4733
4734 if (columns->Count > 1)
4735 {
4736 columns->Splitter.Split(window->DrawList, 1 + columns->Count);
4737 columns->Splitter.SetCurrentChannel(window->DrawList, 1);
4738 PushColumnClipRect(0);
4739 }
4740
4741 // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user.
4742 float offset_0 = GetColumnOffset(columns->Current);
4743 float offset_1 = GetColumnOffset(columns->Current + 1);
4744 float width = offset_1 - offset_0;
4745 PushItemWidth(width * 0.65f);
4746 window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
4747 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
4748 window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
4749 window->WorkRect.Max.y = window->ContentRegionRect.Max.y;
4750}
4751
4752void ImGui::NextColumn()
4753{
4754 ImGuiWindow* window = GetCurrentWindow();
4755 if (window->SkipItems || window->DC.CurrentColumns == NULL)
4756 return;
4757
4758 ImGuiContext& g = *GImGui;
4759 ImGuiOldColumns* columns = window->DC.CurrentColumns;
4760
4761 if (columns->Count == 1)
4762 {
4763 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
4764 IM_ASSERT(columns->Current == 0);
4765 return;
4766 }
4767
4768 // Next column
4769 if (++columns->Current == columns->Count)
4770 columns->Current = 0;
4771
4772 PopItemWidth();
4773
4774 // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect()
4775 // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them),
4776 ImGuiOldColumnData* column = &columns->Columns[columns->Current];
4777 SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
4778 columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
4779
4780 const float column_padding = g.Style.ItemSpacing.x;
4781 columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
4782 if (columns->Current > 0)
4783 {
4784 // Columns 1+ ignore IndentX (by canceling it out)
4785 // FIXME-COLUMNS: Unnecessary, could be locked?
4786 window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding;
4787 }
4788 else
4789 {
4790 // New row/line: column 0 honor IndentX.
4791 window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
4792 window->DC.IsSameLine = false;
4793 columns->LineMinY = columns->LineMaxY;
4794 }
4795 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
4796 window->DC.CursorPos.y = columns->LineMinY;
4797 window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
4798 window->DC.CurrLineTextBaseOffset = 0.0f;
4799
4800 // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup.
4801 float offset_0 = GetColumnOffset(columns->Current);
4802 float offset_1 = GetColumnOffset(columns->Current + 1);
4803 float width = offset_1 - offset_0;
4804 PushItemWidth(width * 0.65f);
4805 window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
4806}
4807
4808void ImGui::EndColumns()
4809{
4810 ImGuiContext& g = *GImGui;
4811 ImGuiWindow* window = GetCurrentWindow();
4812 ImGuiOldColumns* columns = window->DC.CurrentColumns;
4813 IM_ASSERT(columns != NULL);
4814
4815 PopItemWidth();
4816 if (columns->Count > 1)
4817 {
4818 PopClipRect();
4819 columns->Splitter.Merge(window->DrawList);
4820 }
4821
4822 const ImGuiOldColumnFlags flags = columns->Flags;
4823 columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
4824 window->DC.CursorPos.y = columns->LineMaxY;
4825 if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize))
4826 window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent
4827
4828 // Draw columns borders and handle resize
4829 // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy
4830 bool is_being_resized = false;
4831 if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems)
4832 {
4833 // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.
4834 const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y);
4835 const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y);
4836 int dragging_column = -1;
4837 for (int n = 1; n < columns->Count; n++)
4838 {
4839 ImGuiOldColumnData* column = &columns->Columns[n];
4840 float x = window->Pos.x + GetColumnOffset(n);
4841 const ImGuiID column_id = columns->ID + ImGuiID(n);
4842 const float column_hit_hw = ImTrunc(COLUMNS_HIT_RECT_HALF_THICKNESS * g.CurrentDpiScale);
4843 const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2));
4844 if (!ItemAdd(column_hit_rect, column_id, NULL, ImGuiItemFlags_NoNav))
4845 continue;
4846
4847 bool hovered = false, held = false;
4848 if (!(flags & ImGuiOldColumnFlags_NoResize))
4849 {
4850 ButtonBehavior(column_hit_rect, column_id, &hovered, &held);
4851 if (hovered || held)
4852 SetMouseCursor(ImGuiMouseCursor_ResizeEW);
4853 if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize))
4854 dragging_column = n;
4855 }
4856
4857 // Draw column
4858 const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
4859 const float xi = IM_TRUNC(x);
4860 window->DrawList->AddLineV(xi, y1 + 1.0f, y2, col);
4861 }
4862
4863 // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
4864 if (dragging_column != -1)
4865 {
4866 if (!columns->IsBeingResized)
4867 for (int n = 0; n < columns->Count + 1; n++)
4868 columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
4869 columns->IsBeingResized = is_being_resized = true;
4870 float x = GetDraggedColumnOffset(columns, dragging_column);
4871 SetColumnOffset(dragging_column, x);
4872 }
4873 }
4874 columns->IsBeingResized = is_being_resized;
4875
4876 window->WorkRect = window->ParentWorkRect;
4877 window->ParentWorkRect = columns->HostBackupParentWorkRect;
4878 window->DC.CurrentColumns = NULL;
4879 window->DC.ColumnsOffset.x = 0.0f;
4880 window->DC.CursorPos.x = IM_TRUNC(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
4881 NavUpdateCurrentWindowIsScrollPushableX();
4882}
4883
4884void ImGui::Columns(int columns_count, const char* id, bool borders)
4885{
4886 ImGuiWindow* window = GetCurrentWindow();
4887 IM_ASSERT(columns_count >= 1);
4888
4889 ImGuiOldColumnFlags flags = (borders ? 0 : ImGuiOldColumnFlags_NoBorder);
4890 //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior
4891 ImGuiOldColumns* columns = window->DC.CurrentColumns;
4892 if (columns != NULL && columns->Count == columns_count && columns->Flags == flags)
4893 return;
4894
4895 if (columns != NULL)
4896 EndColumns();
4897
4898 if (columns_count != 1)
4899 BeginColumns(id, columns_count, flags);
4900}
4901
4902//-------------------------------------------------------------------------
4903
4904#endif // #ifndef IMGUI_DISABLE