1// dear imgui, v1.90.0
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 IDE: CTRL+comma ("Edit.GoToAll") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot.
28// - With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments.
29
30//-----------------------------------------------------------------------------
31// [SECTION] Commentary
32//-----------------------------------------------------------------------------
33
34//-----------------------------------------------------------------------------
35// Typical tables call flow: (root level is generally public API):
36//-----------------------------------------------------------------------------
37// - BeginTable() user begin into a table
38// | BeginChild() - (if ScrollX/ScrollY is set)
39// | TableBeginInitMemory() - first time table is used
40// | TableResetSettings() - on settings reset
41// | TableLoadSettings() - on settings load
42// | TableBeginApplyRequests() - apply queued resizing/reordering/hiding requests
43// | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame)
44// | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width
45// - TableSetupColumn() user submit columns details (optional)
46// - TableSetupScrollFreeze() user submit scroll freeze information (optional)
47//-----------------------------------------------------------------------------
48// - TableUpdateLayout() [Internal] followup to BeginTable(): setup everything: widths, columns positions, clipping rectangles. Automatically called by the FIRST call to TableNextRow() or TableHeadersRow().
49// | TableSetupDrawChannels() - setup ImDrawList channels
50// | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission
51// | TableBeginContextMenuPopup()
52// | - TableDrawDefaultContextMenu() - draw right-click context menu contents
53//-----------------------------------------------------------------------------
54// - TableHeadersRow() or TableHeader() user submit a headers row (optional)
55// | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction
56// | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu
57// - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers)
58// - TableNextRow() user begin into a new row (also automatically called by TableHeadersRow())
59// | TableEndRow() - finish existing row
60// | TableBeginRow() - add a new row
61// - TableSetColumnIndex() / TableNextColumn() user begin into a cell
62// | TableEndCell() - close existing column/cell
63// | TableBeginCell() - enter into current column/cell
64// - [...] user emit contents
65//-----------------------------------------------------------------------------
66// - EndTable() user ends the table
67// | TableDrawBorders() - draw outer borders, inner vertical borders
68// | TableMergeDrawChannels() - merge draw channels if clipping isn't required
69// | EndChild() - (if ScrollX/ScrollY is set)
70//-----------------------------------------------------------------------------
71
72//-----------------------------------------------------------------------------
73// TABLE SIZING
74//-----------------------------------------------------------------------------
75// (Read carefully because this is subtle but it does make sense!)
76//-----------------------------------------------------------------------------
77// About 'outer_size':
78// Its meaning needs to differ slightly depending on if we are using ScrollX/ScrollY flags.
79// Default value is ImVec2(0.0f, 0.0f).
80// X
81// - 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.
82// - outer_size.x > 0.0f -> Set Fixed width.
83// Y with ScrollX/ScrollY disabled: we output table directly in current window
84// - outer_size.y < 0.0f -> Bottom-align (but will auto extend, unless _NoHostExtendY is set). Not meaningful if parent window can vertically scroll.
85// - outer_size.y = 0.0f -> No minimum height (but will auto extend, unless _NoHostExtendY is set)
86// - outer_size.y > 0.0f -> Set Minimum height (but will auto extend, unless _NoHostExtendY is set)
87// Y with ScrollX/ScrollY enabled: using a child window for scrolling
88// - outer_size.y < 0.0f -> Bottom-align. Not meaningful if parent window can vertically scroll.
89// - outer_size.y = 0.0f -> Bottom-align, consistent with BeginChild(). Not recommended unless table is last item in parent window.
90// - outer_size.y > 0.0f -> Set Exact height. Recommended when using Scrolling on any axis.
91//-----------------------------------------------------------------------------
92// Outer size is also affected by the NoHostExtendX/NoHostExtendY flags.
93// Important to note how the two flags have slightly different behaviors!
94// - 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.
95// - 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.
96// In theory ImGuiTableFlags_NoHostExtendY could be the default and any non-scrolling tables with outer_size.y != 0.0f would use exact height.
97// This would be consistent but perhaps less useful and more confusing (as vertically clipped items are not useful and not easily noticeable).
98//-----------------------------------------------------------------------------
99// About 'inner_width':
100// With ScrollX disabled:
101// - inner_width -> *ignored*
102// With ScrollX enabled:
103// - inner_width < 0.0f -> *illegal* fit in known width (right align from outer_size.x) <-- weird
104// - 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.
105// - 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!
106//-----------------------------------------------------------------------------
107// Details:
108// - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept
109// of "available space" doesn't make sense.
110// - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding
111// of what the value does.
112//-----------------------------------------------------------------------------
113
114//-----------------------------------------------------------------------------
115// COLUMNS SIZING POLICIES
116// (Reference: ImGuiTableFlags_SizingXXX flags and ImGuiTableColumnFlags_WidthXXX flags)
117//-----------------------------------------------------------------------------
118// About overriding column sizing policy and width/weight with TableSetupColumn():
119// We use a default parameter of -1 for 'init_width'/'init_weight'.
120// - with ImGuiTableColumnFlags_WidthFixed, init_width <= 0 (default) --> width is automatic
121// - with ImGuiTableColumnFlags_WidthFixed, init_width > 0 (explicit) --> width is custom
122// - with ImGuiTableColumnFlags_WidthStretch, init_weight <= 0 (default) --> weight is 1.0f
123// - with ImGuiTableColumnFlags_WidthStretch, init_weight > 0 (explicit) --> weight is custom
124// Widths are specified _without_ CellPadding. If you specify a width of 100.0f, the column will be cover (100.0f + Padding * 2.0f)
125// and you can fit a 100.0f wide item in it without clipping and with padding honored.
126//-----------------------------------------------------------------------------
127// About default sizing policy (if you don't specify a ImGuiTableColumnFlags_WidthXXXX flag)
128// - with Table policy ImGuiTableFlags_SizingFixedFit --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is equal to contents width
129// - with Table policy ImGuiTableFlags_SizingFixedSame --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is max of all contents width
130// - with Table policy ImGuiTableFlags_SizingStretchSame --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is 1.0f
131// - with Table policy ImGuiTableFlags_SizingStretchWeight --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is proportional to contents
132// Default Width and default Weight can be overridden when calling TableSetupColumn().
133//-----------------------------------------------------------------------------
134// About mixing Fixed/Auto and Stretch columns together:
135// - the typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns.
136// - 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!
137// that is, unless 'inner_width' is passed to BeginTable() to explicitly provide a total width to layout columns in.
138// - when using ImGuiTableFlags_SizingFixedSame with mixed columns, only the Fixed/Auto columns will match their widths to the width of the maximum contents.
139// - when using ImGuiTableFlags_SizingStretchSame with mixed columns, only the Stretch columns will match their weights/widths.
140//-----------------------------------------------------------------------------
141// About using column width:
142// If a column is manually resizable or has a width specified with TableSetupColumn():
143// - you may use GetContentRegionAvail().x to query the width available in a given column.
144// - right-side alignment features such as SetNextItemWidth(-x) or PushItemWidth(-x) will rely on this width.
145// If the column is not resizable and has no width specified with TableSetupColumn():
146// - its width will be automatic and be set to the max of items submitted.
147// - therefore you generally cannot have ALL items of the columns use e.g. SetNextItemWidth(-FLT_MIN).
148// - but if the column has one or more items of known/fixed size, this will become the reference width used by SetNextItemWidth(-FLT_MIN).
149//-----------------------------------------------------------------------------
150
151
152//-----------------------------------------------------------------------------
153// TABLES CLIPPING/CULLING
154//-----------------------------------------------------------------------------
155// About clipping/culling of Rows in Tables:
156// - For large numbers of rows, it is recommended you use ImGuiListClipper to submit only visible rows.
157// ImGuiListClipper is reliant on the fact that rows are of equal height.
158// See 'Demo->Tables->Vertical Scrolling' or 'Demo->Tables->Advanced' for a demo of using the clipper.
159// - Note that auto-resizing columns don't play well with using the clipper.
160// By default a table with _ScrollX but without _Resizable will have column auto-resize.
161// So, if you want to use the clipper, make sure to either enable _Resizable, either setup columns width explicitly with _WidthFixed.
162//-----------------------------------------------------------------------------
163// About clipping/culling of Columns in Tables:
164// - Both TableSetColumnIndex() and TableNextColumn() return true when the column is visible or performing
165// width measurements. Otherwise, you may skip submitting the contents of a cell/column, BUT ONLY if you know
166// it is not going to contribute to row height.
167// In many situations, you may skip submitting contents for every column but one (e.g. the first one).
168// - Case A: column is not hidden by user, and at least partially in sight (most common case).
169// - 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.
170// - Case C: column is hidden explicitly by the user (e.g. via the context menu, or _DefaultHide column flag, etc.).
171//
172// [A] [B] [C]
173// 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.
174// SkipItems: false false true -> [internal] when SkipItems is true, most widgets will early out if submitted, resulting is no layout output.
175// ClipRect: normal zero-width zero-width -> [internal] when ClipRect is zero, ItemAdd() will return false and most widgets will early out mid-way.
176// ImDrawList output: normal dummy dummy -> [internal] when using the dummy channel, ImDrawList submissions (if any) will be wasted (because cliprect is zero-width anyway).
177//
178// - 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.
179// 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.
180//-----------------------------------------------------------------------------
181// About clipping/culling of whole Tables:
182// - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false.
183//-----------------------------------------------------------------------------
184
185//-----------------------------------------------------------------------------
186// [SECTION] Header mess
187//-----------------------------------------------------------------------------
188
189#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
190#define _CRT_SECURE_NO_WARNINGS
191#endif
192
193#ifndef IMGUI_DEFINE_MATH_OPERATORS
194#define IMGUI_DEFINE_MATH_OPERATORS
195#endif
196
197#include "imgui.h"
198#ifndef IMGUI_DISABLE
199#include "imgui_internal.h"
200
201// System includes
202#include <stdint.h> // intptr_t
203
204// Visual Studio warnings
205#ifdef _MSC_VER
206#pragma warning (disable: 4127) // condition expression is constant
207#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
208#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
209#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
210#endif
211#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).
212#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
213#endif
214
215// Clang/GCC warnings with -Weverything
216#if defined(__clang__)
217#if __has_warning("-Wunknown-warning-option")
218#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!
219#endif
220#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
221#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
222#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.
223#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.
224#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
225#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
226#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.
227#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_')
228#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
229#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
230#elif defined(__GNUC__)
231#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
232#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
233#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
234#endif
235
236//-----------------------------------------------------------------------------
237// [SECTION] Tables: Main code
238//-----------------------------------------------------------------------------
239// - TableFixFlags() [Internal]
240// - TableFindByID() [Internal]
241// - BeginTable()
242// - BeginTableEx() [Internal]
243// - TableBeginInitMemory() [Internal]
244// - TableBeginApplyRequests() [Internal]
245// - TableSetupColumnFlags() [Internal]
246// - TableUpdateLayout() [Internal]
247// - TableUpdateBorders() [Internal]
248// - EndTable()
249// - TableSetupColumn()
250// - TableSetupScrollFreeze()
251//-----------------------------------------------------------------------------
252
253// Configuration
254static const int TABLE_DRAW_CHANNEL_BG0 = 0;
255static const int TABLE_DRAW_CHANNEL_BG2_FROZEN = 1;
256static const int TABLE_DRAW_CHANNEL_NOCLIP = 2; // When using ImGuiTableFlags_NoClip (this becomes the last visible channel)
257static const float TABLE_BORDER_SIZE = 1.0f; // FIXME-TABLE: Currently hard-coded because of clipping assumptions with outer borders rendering.
258static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders.
259static 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.
260
261// Helper
262inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags, ImGuiWindow* outer_window)
263{
264 // Adjust flags: set default sizing policy
265 if ((flags & ImGuiTableFlags_SizingMask_) == 0)
266 flags |= ((flags & ImGuiTableFlags_ScrollX) || (outer_window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) ? ImGuiTableFlags_SizingFixedFit : ImGuiTableFlags_SizingStretchSame;
267
268 // Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags_SizingFixedSame
269 if ((flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame)
270 flags |= ImGuiTableFlags_NoKeepColumnsVisible;
271
272 // Adjust flags: enforce borders when resizable
273 if (flags & ImGuiTableFlags_Resizable)
274 flags |= ImGuiTableFlags_BordersInnerV;
275
276 // Adjust flags: disable NoHostExtendX/NoHostExtendY if we have any scrolling going on
277 if (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY))
278 flags &= ~(ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_NoHostExtendY);
279
280 // Adjust flags: NoBordersInBodyUntilResize takes priority over NoBordersInBody
281 if (flags & ImGuiTableFlags_NoBordersInBodyUntilResize)
282 flags &= ~ImGuiTableFlags_NoBordersInBody;
283
284 // Adjust flags: disable saved settings if there's nothing to save
285 if ((flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Sortable)) == 0)
286 flags |= ImGuiTableFlags_NoSavedSettings;
287
288 // Inherit _NoSavedSettings from top-level window (child windows always have _NoSavedSettings set)
289 if (outer_window->RootWindow->Flags & ImGuiWindowFlags_NoSavedSettings)
290 flags |= ImGuiTableFlags_NoSavedSettings;
291
292 return flags;
293}
294
295ImGuiTable* ImGui::TableFindByID(ImGuiID id)
296{
297 ImGuiContext& g = *GImGui;
298 return g.Tables.GetByKey(key: id);
299}
300
301// Read about "TABLE SIZING" at the top of this file.
302bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
303{
304 ImGuiID id = GetID(str_id);
305 return BeginTableEx(name: str_id, id, columns_count, flags, outer_size, inner_width);
306}
307
308bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
309{
310 ImGuiContext& g = *GImGui;
311 ImGuiWindow* outer_window = GetCurrentWindow();
312 if (outer_window->SkipItems) // Consistent with other tables + beneficial side effect that assert on miscalling EndTable() will be more visible.
313 return false;
314
315 // Sanity checks
316 IM_ASSERT(columns_count > 0 && columns_count < IMGUI_TABLE_MAX_COLUMNS);
317 if (flags & ImGuiTableFlags_ScrollX)
318 IM_ASSERT(inner_width >= 0.0f);
319
320 // If an outer size is specified ahead we will be able to early out when not visible. Exact clipping criteria may evolve.
321 const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0;
322 const ImVec2 avail_size = GetContentRegionAvail();
323 const ImVec2 actual_outer_size = CalcItemSize(size: outer_size, default_w: ImMax(lhs: avail_size.x, rhs: 1.0f), default_h: use_child_window ? ImMax(lhs: avail_size.y, rhs: 1.0f) : 0.0f);
324 const ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size);
325 const bool outer_window_is_measuring_size = (outer_window->AutoFitFramesX > 0) || (outer_window->AutoFitFramesY > 0); // Doesn't apply to AlwaysAutoResize windows!
326 if (use_child_window && IsClippedEx(bb: outer_rect, id: 0) && !outer_window_is_measuring_size)
327 {
328 ItemSize(bb: outer_rect);
329 return false;
330 }
331
332 // Acquire storage for the table
333 ImGuiTable* table = g.Tables.GetOrAddByKey(key: id);
334 const ImGuiTableFlags table_last_flags = table->Flags;
335
336 // Acquire temporary buffers
337 const int table_idx = g.Tables.GetIndex(p: table);
338 if (++g.TablesTempDataStacked > g.TablesTempData.Size)
339 g.TablesTempData.resize(new_size: g.TablesTempDataStacked, v: ImGuiTableTempData());
340 ImGuiTableTempData* temp_data = table->TempData = &g.TablesTempData[g.TablesTempDataStacked - 1];
341 temp_data->TableIndex = table_idx;
342 table->DrawSplitter = &table->TempData->DrawSplitter;
343 table->DrawSplitter->Clear();
344
345 // Fix flags
346 table->IsDefaultSizingPolicy = (flags & ImGuiTableFlags_SizingMask_) == 0;
347 flags = TableFixFlags(flags, outer_window);
348
349 // Initialize
350 const int previous_frame_active = table->LastFrameActive;
351 const int instance_no = (previous_frame_active != g.FrameCount) ? 0 : table->InstanceCurrent + 1;
352 table->ID = id;
353 table->Flags = flags;
354 table->LastFrameActive = g.FrameCount;
355 table->OuterWindow = table->InnerWindow = outer_window;
356 table->ColumnsCount = columns_count;
357 table->IsLayoutLocked = false;
358 table->InnerWidth = inner_width;
359 temp_data->UserOuterSize = outer_size;
360
361 // Instance data (for instance 0, TableID == TableInstanceID)
362 ImGuiID instance_id;
363 table->InstanceCurrent = (ImS16)instance_no;
364 if (instance_no > 0)
365 {
366 IM_ASSERT(table->ColumnsCount == columns_count && "BeginTable(): Cannot change columns count mid-frame while preserving same ID");
367 if (table->InstanceDataExtra.Size < instance_no)
368 table->InstanceDataExtra.push_back(v: ImGuiTableInstanceData());
369 instance_id = GetIDWithSeed(n: instance_no, seed: GetIDWithSeed(str_id_begin: "##Instances", NULL, seed: id)); // Push "##Instances" followed by (int)instance_no in ID stack.
370 }
371 else
372 {
373 instance_id = id;
374 }
375 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, instance_no: table->InstanceCurrent);
376 table_instance->TableInstanceID = instance_id;
377
378 // When not using a child window, WorkRect.Max will grow as we append contents.
379 if (use_child_window)
380 {
381 // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent
382 // (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing)
383 ImVec2 override_content_size(FLT_MAX, FLT_MAX);
384 if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY))
385 override_content_size.y = FLT_MIN;
386
387 // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and
388 // never lead to any scrolling). We don't handle inner_width < 0.0f, we could potentially use it to right-align
389 // based on the right side of the child window work rect, which would require knowing ahead if we are going to
390 // have decoration taking horizontal spaces (typically a vertical scrollbar).
391 if ((flags & ImGuiTableFlags_ScrollX) && inner_width > 0.0f)
392 override_content_size.x = inner_width;
393
394 if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX)
395 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));
396
397 // Reset scroll if we are reactivating it
398 if ((table_last_flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) == 0)
399 SetNextWindowScroll(ImVec2(0.0f, 0.0f));
400
401 // Create scrolling region (without border and zero window padding)
402 ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None;
403 BeginChildEx(name, id: instance_id, size_arg: outer_rect.GetSize(), child_flags: false, window_flags: child_flags);
404 table->InnerWindow = g.CurrentWindow;
405 table->WorkRect = table->InnerWindow->WorkRect;
406 table->OuterRect = table->InnerWindow->Rect();
407 table->InnerRect = table->InnerWindow->InnerRect;
408 IM_ASSERT(table->InnerWindow->WindowPadding.x == 0.0f && table->InnerWindow->WindowPadding.y == 0.0f && table->InnerWindow->WindowBorderSize == 0.0f);
409
410 // Allow submitting when host is measuring
411 if (table->InnerWindow->SkipItems && outer_window_is_measuring_size)
412 table->InnerWindow->SkipItems = false;
413
414 // When using multiple instances, ensure they have the same amount of horizontal decorations (aka vertical scrollbar) so stretched columns can be aligned)
415 if (instance_no == 0)
416 {
417 table->HasScrollbarYPrev = table->HasScrollbarYCurr;
418 table->HasScrollbarYCurr = false;
419 }
420 table->HasScrollbarYCurr |= table->InnerWindow->ScrollbarY;
421 }
422 else
423 {
424 // For non-scrolling tables, WorkRect == OuterRect == InnerRect.
425 // 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().
426 table->WorkRect = table->OuterRect = table->InnerRect = outer_rect;
427 }
428
429 // Push a standardized ID for both child-using and not-child-using tables
430 PushOverrideID(id);
431 if (instance_no > 0)
432 PushOverrideID(id: instance_id); // FIXME: Somehow this is not resolved by stack-tool, even tho GetIDWithSeed() submitted the symbol.
433
434 // Backup a copy of host window members we will modify
435 ImGuiWindow* inner_window = table->InnerWindow;
436 table->HostIndentX = inner_window->DC.Indent.x;
437 table->HostClipRect = inner_window->ClipRect;
438 table->HostSkipItems = inner_window->SkipItems;
439 temp_data->HostBackupWorkRect = inner_window->WorkRect;
440 temp_data->HostBackupParentWorkRect = inner_window->ParentWorkRect;
441 temp_data->HostBackupColumnsOffset = outer_window->DC.ColumnsOffset;
442 temp_data->HostBackupPrevLineSize = inner_window->DC.PrevLineSize;
443 temp_data->HostBackupCurrLineSize = inner_window->DC.CurrLineSize;
444 temp_data->HostBackupCursorMaxPos = inner_window->DC.CursorMaxPos;
445 temp_data->HostBackupItemWidth = outer_window->DC.ItemWidth;
446 temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size;
447 inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
448
449 // Make left and top borders not overlap our contents by offsetting HostClipRect (#6765)
450 // (we normally shouldn't alter HostClipRect as we rely on TableMergeDrawChannels() expanding non-clipped column toward the
451 // limits of that rectangle, in order for ImDrawListSplitter::Merge() to merge the draw commands. However since the overlap
452 // problem only affect scrolling tables in this case we can get away with doing it without extra cost).
453 if (inner_window != outer_window)
454 {
455 if (flags & ImGuiTableFlags_BordersOuterV)
456 table->HostClipRect.Min.x = ImMin(lhs: table->HostClipRect.Min.x + TABLE_BORDER_SIZE, rhs: table->HostClipRect.Max.x);
457 if (flags & ImGuiTableFlags_BordersOuterH)
458 table->HostClipRect.Min.y = ImMin(lhs: table->HostClipRect.Min.y + TABLE_BORDER_SIZE, rhs: table->HostClipRect.Max.y);
459 }
460
461 // Padding and Spacing
462 // - None ........Content..... Pad .....Content........
463 // - PadOuter | Pad ..Content..... Pad .....Content.. Pad |
464 // - PadInner ........Content.. Pad | Pad ..Content........
465 // - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad |
466 const bool pad_outer_x = (flags & ImGuiTableFlags_NoPadOuterX) ? false : (flags & ImGuiTableFlags_PadOuterX) ? true : (flags & ImGuiTableFlags_BordersOuterV) != 0;
467 const bool pad_inner_x = (flags & ImGuiTableFlags_NoPadInnerX) ? false : true;
468 const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? TABLE_BORDER_SIZE : 0.0f;
469 const float inner_spacing_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) == 0) ? g.Style.CellPadding.x : 0.0f;
470 const float inner_padding_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) != 0) ? g.Style.CellPadding.x : 0.0f;
471 table->CellSpacingX1 = inner_spacing_explicit + inner_spacing_for_border;
472 table->CellSpacingX2 = inner_spacing_explicit;
473 table->CellPaddingX = inner_padding_explicit;
474
475 const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;
476 const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f;
477 table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX;
478
479 table->CurrentColumn = -1;
480 table->CurrentRow = -1;
481 table->RowBgColorCounter = 0;
482 table->LastRowFlags = ImGuiTableRowFlags_None;
483 table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect;
484 table->InnerClipRect.ClipWith(r: table->WorkRect); // We need this to honor inner_width
485 table->InnerClipRect.ClipWithFull(r: table->HostClipRect);
486 table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(lhs: table->InnerClipRect.Max.y, rhs: inner_window->WorkRect.Max.y) : inner_window->ClipRect.Max.y;
487
488 table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow
489 table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow()
490 table->RowCellPaddingY = 0.0f;
491 table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any
492 table->FreezeColumnsRequest = table->FreezeColumnsCount = 0;
493 table->IsUnfrozenRows = true;
494 table->DeclColumnsCount = table->AngledHeadersCount = 0;
495 if (previous_frame_active + 1 < g.FrameCount)
496 table->IsActiveIdInTable = false;
497 temp_data->AngledheadersExtraWidth = 0.0f;
498
499 // Using opaque colors facilitate overlapping lines of the grid, otherwise we'd need to improve TableDrawBorders()
500 table->BorderColorStrong = GetColorU32(idx: ImGuiCol_TableBorderStrong);
501 table->BorderColorLight = GetColorU32(idx: ImGuiCol_TableBorderLight);
502
503 // Make table current
504 g.CurrentTable = table;
505 outer_window->DC.NavIsScrollPushableX = false; // Shortcut for NavUpdateCurrentWindowIsScrollPushableX();
506 outer_window->DC.CurrentTableIdx = table_idx;
507 if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly.
508 inner_window->DC.CurrentTableIdx = table_idx;
509
510 if ((table_last_flags & ImGuiTableFlags_Reorderable) && (flags & ImGuiTableFlags_Reorderable) == 0)
511 table->IsResetDisplayOrderRequest = true;
512
513 // Mark as used to avoid GC
514 if (table_idx >= g.TablesLastTimeActive.Size)
515 g.TablesLastTimeActive.resize(new_size: table_idx + 1, v: -1.0f);
516 g.TablesLastTimeActive[table_idx] = (float)g.Time;
517 temp_data->LastTimeActive = (float)g.Time;
518 table->MemoryCompacted = false;
519
520 // Setup memory buffer (clear data if columns count changed)
521 ImGuiTableColumn* old_columns_to_preserve = NULL;
522 void* old_columns_raw_data = NULL;
523 const int old_columns_count = table->Columns.size();
524 if (old_columns_count != 0 && old_columns_count != columns_count)
525 {
526 // Attempt to preserve width on column count change (#4046)
527 old_columns_to_preserve = table->Columns.Data;
528 old_columns_raw_data = table->RawData;
529 table->RawData = NULL;
530 }
531 if (table->RawData == NULL)
532 {
533 TableBeginInitMemory(table, columns_count);
534 table->IsInitializing = table->IsSettingsRequestLoad = true;
535 }
536 if (table->IsResetAllRequest)
537 TableResetSettings(table);
538 if (table->IsInitializing)
539 {
540 // Initialize
541 table->SettingsOffset = -1;
542 table->IsSortSpecsDirty = true;
543 table->InstanceInteracted = -1;
544 table->ContextPopupColumn = -1;
545 table->ReorderColumn = table->ResizedColumn = table->LastResizedColumn = -1;
546 table->AutoFitSingleColumn = -1;
547 table->HoveredColumnBody = table->HoveredColumnBorder = -1;
548 for (int n = 0; n < columns_count; n++)
549 {
550 ImGuiTableColumn* column = &table->Columns[n];
551 if (old_columns_to_preserve && n < old_columns_count)
552 {
553 // FIXME: We don't attempt to preserve column order in this path.
554 *column = old_columns_to_preserve[n];
555 }
556 else
557 {
558 float width_auto = column->WidthAuto;
559 *column = ImGuiTableColumn();
560 column->WidthAuto = width_auto;
561 column->IsPreserveWidthAuto = true; // Preserve WidthAuto when reinitializing a live table: not technically necessary but remove a visible flicker
562 column->IsEnabled = column->IsUserEnabled = column->IsUserEnabledNextFrame = true;
563 }
564 column->DisplayOrder = table->DisplayOrderToIndex[n] = (ImGuiTableColumnIdx)n;
565 }
566 }
567 if (old_columns_raw_data)
568 IM_FREE(old_columns_raw_data);
569
570 // Load settings
571 if (table->IsSettingsRequestLoad)
572 TableLoadSettings(table);
573
574 // Handle DPI/font resize
575 // This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well.
576 // It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition.
577 // FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory.
578 // This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path.
579 const float new_ref_scale_unit = g.FontSize; // g.Font->GetCharAdvance('A') ?
580 if (table->RefScale != 0.0f && table->RefScale != new_ref_scale_unit)
581 {
582 const float scale_factor = new_ref_scale_unit / table->RefScale;
583 //IMGUI_DEBUG_PRINT("[table] %08X RefScaleUnit %.3f -> %.3f, scaling width by %.3f\n", table->ID, table->RefScaleUnit, new_ref_scale_unit, scale_factor);
584 for (int n = 0; n < columns_count; n++)
585 table->Columns[n].WidthRequest = table->Columns[n].WidthRequest * scale_factor;
586 }
587 table->RefScale = new_ref_scale_unit;
588
589 // Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call..
590 // This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user.
591 // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option.
592 inner_window->SkipItems = true;
593
594 // Clear names
595 // At this point the ->NameOffset field of each column will be invalid until TableUpdateLayout() or the first call to TableSetupColumn()
596 if (table->ColumnsNames.Buf.Size > 0)
597 table->ColumnsNames.Buf.resize(new_size: 0);
598
599 // Apply queued resizing/reordering/hiding requests
600 TableBeginApplyRequests(table);
601
602 return true;
603}
604
605// For reference, the average total _allocation count_ for a table is:
606// + 0 (for ImGuiTable instance, we are pooling allocations in g.Tables[])
607// + 1 (for table->RawData allocated below)
608// + 1 (for table->ColumnsNames, if names are used)
609// Shared allocations for the maximum number of simultaneously nested tables (generally a very small number)
610// + 1 (for table->Splitter._Channels)
611// + 2 * active_channels_count (for ImDrawCmd and ImDrawIdx buffers inside channels)
612// Where active_channels_count is variable but often == columns_count or == columns_count + 1, see TableSetupDrawChannels() for details.
613// Unused channels don't perform their +2 allocations.
614void ImGui::TableBeginInitMemory(ImGuiTable* table, int columns_count)
615{
616 // Allocate single buffer for our arrays
617 const int columns_bit_array_size = (int)ImBitArrayGetStorageSizeInBytes(bitcount: columns_count);
618 ImSpanAllocator<6> span_allocator;
619 span_allocator.Reserve(n: 0, sz: columns_count * sizeof(ImGuiTableColumn));
620 span_allocator.Reserve(n: 1, sz: columns_count * sizeof(ImGuiTableColumnIdx));
621 span_allocator.Reserve(n: 2, sz: columns_count * sizeof(ImGuiTableCellData), a: 4);
622 for (int n = 3; n < 6; n++)
623 span_allocator.Reserve(n, sz: columns_bit_array_size);
624 table->RawData = IM_ALLOC(span_allocator.GetArenaSizeInBytes());
625 memset(s: table->RawData, c: 0, n: span_allocator.GetArenaSizeInBytes());
626 span_allocator.SetArenaBasePtr(table->RawData);
627 span_allocator.GetSpan(n: 0, span: &table->Columns);
628 span_allocator.GetSpan(n: 1, span: &table->DisplayOrderToIndex);
629 span_allocator.GetSpan(n: 2, span: &table->RowCellData);
630 table->EnabledMaskByDisplayOrder = (ImU32*)span_allocator.GetSpanPtrBegin(n: 3);
631 table->EnabledMaskByIndex = (ImU32*)span_allocator.GetSpanPtrBegin(n: 4);
632 table->VisibleMaskByIndex = (ImU32*)span_allocator.GetSpanPtrBegin(n: 5);
633}
634
635// Apply queued resizing/reordering/hiding requests
636void ImGui::TableBeginApplyRequests(ImGuiTable* table)
637{
638 // Handle resizing request
639 // (We process this in the TableBegin() of the first instance of each table)
640 // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling?
641 if (table->InstanceCurrent == 0)
642 {
643 if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX)
644 TableSetColumnWidth(column_n: table->ResizedColumn, width: table->ResizedColumnNextWidth);
645 table->LastResizedColumn = table->ResizedColumn;
646 table->ResizedColumnNextWidth = FLT_MAX;
647 table->ResizedColumn = -1;
648
649 // Process auto-fit for single column, which is a special case for stretch columns and fixed columns with FixedSame policy.
650 // FIXME-TABLE: Would be nice to redistribute available stretch space accordingly to other weights, instead of giving it all to siblings.
651 if (table->AutoFitSingleColumn != -1)
652 {
653 TableSetColumnWidth(column_n: table->AutoFitSingleColumn, width: table->Columns[table->AutoFitSingleColumn].WidthAuto);
654 table->AutoFitSingleColumn = -1;
655 }
656 }
657
658 // Handle reordering request
659 // Note: we don't clear ReorderColumn after handling the request.
660 if (table->InstanceCurrent == 0)
661 {
662 if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1)
663 table->ReorderColumn = -1;
664 table->HeldHeaderColumn = -1;
665 if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0)
666 {
667 // We need to handle reordering across hidden columns.
668 // In the configuration below, moving C to the right of E will lead to:
669 // ... C [D] E ---> ... [D] E C (Column name/index)
670 // ... 2 3 4 ... 2 3 4 (Display order)
671 const int reorder_dir = table->ReorderColumnDir;
672 IM_ASSERT(reorder_dir == -1 || reorder_dir == +1);
673 IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable);
674 ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn];
675 ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevEnabledColumn : src_column->NextEnabledColumn];
676 IM_UNUSED(dst_column);
677 const int src_order = src_column->DisplayOrder;
678 const int dst_order = dst_column->DisplayOrder;
679 src_column->DisplayOrder = (ImGuiTableColumnIdx)dst_order;
680 for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir)
681 table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImGuiTableColumnIdx)reorder_dir;
682 IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir);
683
684 // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[]. Rebuild later from the former.
685 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
686 table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n;
687 table->ReorderColumnDir = 0;
688 table->IsSettingsDirty = true;
689 }
690 }
691
692 // Handle display order reset request
693 if (table->IsResetDisplayOrderRequest)
694 {
695 for (int n = 0; n < table->ColumnsCount; n++)
696 table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n;
697 table->IsResetDisplayOrderRequest = false;
698 table->IsSettingsDirty = true;
699 }
700}
701
702// Adjust flags: default width mode + stretch columns are not allowed when auto extending
703static void TableSetupColumnFlags(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags flags_in)
704{
705 ImGuiTableColumnFlags flags = flags_in;
706
707 // Sizing Policy
708 if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0)
709 {
710 const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_);
711 if (table_sizing_policy == ImGuiTableFlags_SizingFixedFit || table_sizing_policy == ImGuiTableFlags_SizingFixedSame)
712 flags |= ImGuiTableColumnFlags_WidthFixed;
713 else
714 flags |= ImGuiTableColumnFlags_WidthStretch;
715 }
716 else
717 {
718 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_WidthMask_)); // Check that only 1 of each set is used.
719 }
720
721 // Resize
722 if ((table->Flags & ImGuiTableFlags_Resizable) == 0)
723 flags |= ImGuiTableColumnFlags_NoResize;
724
725 // Sorting
726 if ((flags & ImGuiTableColumnFlags_NoSortAscending) && (flags & ImGuiTableColumnFlags_NoSortDescending))
727 flags |= ImGuiTableColumnFlags_NoSort;
728
729 // Indentation
730 if ((flags & ImGuiTableColumnFlags_IndentMask_) == 0)
731 flags |= (table->Columns.index_from_ptr(it: column) == 0) ? ImGuiTableColumnFlags_IndentEnable : ImGuiTableColumnFlags_IndentDisable;
732
733 // Alignment
734 //if ((flags & ImGuiTableColumnFlags_AlignMask_) == 0)
735 // flags |= ImGuiTableColumnFlags_AlignCenter;
736 //IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_AlignMask_)); // Check that only 1 of each set is used.
737
738 // Preserve status flags
739 column->Flags = flags | (column->Flags & ImGuiTableColumnFlags_StatusMask_);
740
741 // Build an ordered list of available sort directions
742 column->SortDirectionsAvailCount = column->SortDirectionsAvailMask = column->SortDirectionsAvailList = 0;
743 if (table->Flags & ImGuiTableFlags_Sortable)
744 {
745 int count = 0, mask = 0, list = 0;
746 if ((flags & ImGuiTableColumnFlags_PreferSortAscending) != 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; }
747 if ((flags & ImGuiTableColumnFlags_PreferSortDescending) != 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; }
748 if ((flags & ImGuiTableColumnFlags_PreferSortAscending) == 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; }
749 if ((flags & ImGuiTableColumnFlags_PreferSortDescending) == 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; }
750 if ((table->Flags & ImGuiTableFlags_SortTristate) || count == 0) { mask |= 1 << ImGuiSortDirection_None; count++; }
751 column->SortDirectionsAvailList = (ImU8)list;
752 column->SortDirectionsAvailMask = (ImU8)mask;
753 column->SortDirectionsAvailCount = (ImU8)count;
754 ImGui::TableFixColumnSortDirection(table, column);
755 }
756}
757
758// Layout columns for the frame. This is in essence the followup to BeginTable() and this is our largest function.
759// Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() and other TableSetupXXXXX() functions to be called first.
760// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns.
761// Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns?
762void ImGui::TableUpdateLayout(ImGuiTable* table)
763{
764 ImGuiContext& g = *GImGui;
765 IM_ASSERT(table->IsLayoutLocked == false);
766
767 const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_);
768 table->IsDefaultDisplayOrder = true;
769 table->ColumnsEnabledCount = 0;
770 ImBitArrayClearAllBits(arr: table->EnabledMaskByIndex, bitcount: table->ColumnsCount);
771 ImBitArrayClearAllBits(arr: table->EnabledMaskByDisplayOrder, bitcount: table->ColumnsCount);
772 table->LeftMostEnabledColumn = -1;
773 table->MinColumnWidth = ImMax(lhs: 1.0f, rhs: g.Style.FramePadding.x * 1.0f); // g.Style.ColumnsMinSpacing; // FIXME-TABLE
774
775 // [Part 1] Apply/lock Enabled and Order states. Calculate auto/ideal width for columns. Count fixed/stretch columns.
776 // Process columns in their visible orders as we are building the Prev/Next indices.
777 int count_fixed = 0; // Number of columns that have fixed sizing policies
778 int count_stretch = 0; // Number of columns that have stretch sizing policies
779 int prev_visible_column_idx = -1;
780 bool has_auto_fit_request = false;
781 bool has_resizable = false;
782 float stretch_sum_width_auto = 0.0f;
783 float fixed_max_width_auto = 0.0f;
784 for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
785 {
786 const int column_n = table->DisplayOrderToIndex[order_n];
787 if (column_n != order_n)
788 table->IsDefaultDisplayOrder = false;
789 ImGuiTableColumn* column = &table->Columns[column_n];
790
791 // Clear column setup if not submitted by user. Currently we make it mandatory to call TableSetupColumn() every frame.
792 // It would easily work without but we're not ready to guarantee it since e.g. names need resubmission anyway.
793 // We take a slight shortcut but in theory we could be calling TableSetupColumn() here with dummy values, it should yield the same effect.
794 if (table->DeclColumnsCount <= column_n)
795 {
796 TableSetupColumnFlags(table, column, flags_in: ImGuiTableColumnFlags_None);
797 column->NameOffset = -1;
798 column->UserID = 0;
799 column->InitStretchWeightOrWidth = -1.0f;
800 }
801
802 // Update Enabled state, mark settings and sort specs dirty
803 if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide))
804 column->IsUserEnabledNextFrame = true;
805 if (column->IsUserEnabled != column->IsUserEnabledNextFrame)
806 {
807 column->IsUserEnabled = column->IsUserEnabledNextFrame;
808 table->IsSettingsDirty = true;
809 }
810 column->IsEnabled = column->IsUserEnabled && (column->Flags & ImGuiTableColumnFlags_Disabled) == 0;
811
812 if (column->SortOrder != -1 && !column->IsEnabled)
813 table->IsSortSpecsDirty = true;
814 if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_SortMulti))
815 table->IsSortSpecsDirty = true;
816
817 // Auto-fit unsized columns
818 const bool start_auto_fit = (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? (column->WidthRequest < 0.0f) : (column->StretchWeight < 0.0f);
819 if (start_auto_fit)
820 column->AutoFitQueue = column->CannotSkipItemsQueue = (1 << 3) - 1; // Fit for three frames
821
822 if (!column->IsEnabled)
823 {
824 column->IndexWithinEnabledSet = -1;
825 continue;
826 }
827
828 // Mark as enabled and link to previous/next enabled column
829 column->PrevEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx;
830 column->NextEnabledColumn = -1;
831 if (prev_visible_column_idx != -1)
832 table->Columns[prev_visible_column_idx].NextEnabledColumn = (ImGuiTableColumnIdx)column_n;
833 else
834 table->LeftMostEnabledColumn = (ImGuiTableColumnIdx)column_n;
835 column->IndexWithinEnabledSet = table->ColumnsEnabledCount++;
836 ImBitArraySetBit(arr: table->EnabledMaskByIndex, n: column_n);
837 ImBitArraySetBit(arr: table->EnabledMaskByDisplayOrder, n: column->DisplayOrder);
838 prev_visible_column_idx = column_n;
839 IM_ASSERT(column->IndexWithinEnabledSet <= column->DisplayOrder);
840
841 // Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping)
842 // Combine width from regular rows + width from headers unless requested not to.
843 if (!column->IsPreserveWidthAuto)
844 column->WidthAuto = TableGetColumnWidthAuto(table, column);
845
846 // Non-resizable columns keep their requested width (apply user value regardless of IsPreserveWidthAuto)
847 const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0;
848 if (column_is_resizable)
849 has_resizable = true;
850 if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f && !column_is_resizable)
851 column->WidthAuto = column->InitStretchWeightOrWidth;
852
853 if (column->AutoFitQueue != 0x00)
854 has_auto_fit_request = true;
855 if (column->Flags & ImGuiTableColumnFlags_WidthStretch)
856 {
857 stretch_sum_width_auto += column->WidthAuto;
858 count_stretch++;
859 }
860 else
861 {
862 fixed_max_width_auto = ImMax(lhs: fixed_max_width_auto, rhs: column->WidthAuto);
863 count_fixed++;
864 }
865 }
866 if ((table->Flags & ImGuiTableFlags_Sortable) && table->SortSpecsCount == 0 && !(table->Flags & ImGuiTableFlags_SortTristate))
867 table->IsSortSpecsDirty = true;
868 table->RightMostEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx;
869 IM_ASSERT(table->LeftMostEnabledColumn >= 0 && table->RightMostEnabledColumn >= 0);
870
871 // [Part 2] Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid
872 // 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.
873 // FIXME-TABLE: for always auto-resizing columns may not want to do that all the time.
874 if (has_auto_fit_request && table->OuterWindow != table->InnerWindow)
875 table->InnerWindow->SkipItems = false;
876 if (has_auto_fit_request)
877 table->IsSettingsDirty = true;
878
879 // [Part 3] Fix column flags and record a few extra information.
880 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.
881 float stretch_sum_weights = 0.0f; // Sum of all weights for stretch columns.
882 table->LeftMostStretchedColumn = table->RightMostStretchedColumn = -1;
883 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
884 {
885 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n))
886 continue;
887 ImGuiTableColumn* column = &table->Columns[column_n];
888
889 const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0;
890 if (column->Flags & ImGuiTableColumnFlags_WidthFixed)
891 {
892 // Apply same widths policy
893 float width_auto = column->WidthAuto;
894 if (table_sizing_policy == ImGuiTableFlags_SizingFixedSame && (column->AutoFitQueue != 0x00 || !column_is_resizable))
895 width_auto = fixed_max_width_auto;
896
897 // Apply automatic width
898 // Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!)
899 if (column->AutoFitQueue != 0x00)
900 column->WidthRequest = width_auto;
901 else if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !column_is_resizable && column->IsRequestOutput)
902 column->WidthRequest = width_auto;
903
904 // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets
905 // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very
906 // large height (= first frame scrollbar display very off + clipper would skip lots of items).
907 // This is merely making the side-effect less extreme, but doesn't properly fixes it.
908 // FIXME: Move this to ->WidthGiven to avoid temporary lossyless?
909 // FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller.
910 if (column->AutoFitQueue > 0x01 && table->IsInitializing && !column->IsPreserveWidthAuto)
911 column->WidthRequest = ImMax(lhs: column->WidthRequest, rhs: table->MinColumnWidth * 4.0f); // FIXME-TABLE: Another constant/scale?
912 sum_width_requests += column->WidthRequest;
913 }
914 else
915 {
916 // Initialize stretch weight
917 if (column->AutoFitQueue != 0x00 || column->StretchWeight < 0.0f || !column_is_resizable)
918 {
919 if (column->InitStretchWeightOrWidth > 0.0f)
920 column->StretchWeight = column->InitStretchWeightOrWidth;
921 else if (table_sizing_policy == ImGuiTableFlags_SizingStretchProp)
922 column->StretchWeight = (column->WidthAuto / stretch_sum_width_auto) * count_stretch;
923 else
924 column->StretchWeight = 1.0f;
925 }
926
927 stretch_sum_weights += column->StretchWeight;
928 if (table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder > column->DisplayOrder)
929 table->LeftMostStretchedColumn = (ImGuiTableColumnIdx)column_n;
930 if (table->RightMostStretchedColumn == -1 || table->Columns[table->RightMostStretchedColumn].DisplayOrder < column->DisplayOrder)
931 table->RightMostStretchedColumn = (ImGuiTableColumnIdx)column_n;
932 }
933 column->IsPreserveWidthAuto = false;
934 sum_width_requests += table->CellPaddingX * 2.0f;
935 }
936 table->ColumnsEnabledFixedCount = (ImGuiTableColumnIdx)count_fixed;
937 table->ColumnsStretchSumWeights = stretch_sum_weights;
938
939 // [Part 4] Apply final widths based on requested widths
940 const ImRect work_rect = table->WorkRect;
941 const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1);
942 const float width_removed = (table->HasScrollbarYPrev && !table->InnerWindow->ScrollbarY) ? g.Style.ScrollbarSize : 0.0f; // To synchronize decoration width of synched tables with mismatching scrollbar state (#5920)
943 const float width_avail = ImMax(lhs: 1.0f, rhs: (((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) ? table->InnerClipRect.GetWidth() : work_rect.GetWidth()) - width_removed);
944 const float width_avail_for_stretched_columns = width_avail - width_spacings - sum_width_requests;
945 float width_remaining_for_stretched_columns = width_avail_for_stretched_columns;
946 table->ColumnsGivenWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount;
947 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
948 {
949 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n))
950 continue;
951 ImGuiTableColumn* column = &table->Columns[column_n];
952
953 // Allocate width for stretched/weighted columns (StretchWeight gets converted into WidthRequest)
954 if (column->Flags & ImGuiTableColumnFlags_WidthStretch)
955 {
956 float weight_ratio = column->StretchWeight / stretch_sum_weights;
957 column->WidthRequest = IM_TRUNC(ImMax(width_avail_for_stretched_columns * weight_ratio, table->MinColumnWidth) + 0.01f);
958 width_remaining_for_stretched_columns -= column->WidthRequest;
959 }
960
961 // [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column
962 // See additional comments in TableSetColumnWidth().
963 if (column->NextEnabledColumn == -1 && table->LeftMostStretchedColumn != -1)
964 column->Flags |= ImGuiTableColumnFlags_NoDirectResize_;
965
966 // Assign final width, record width in case we will need to shrink
967 column->WidthGiven = ImTrunc(f: ImMax(lhs: column->WidthRequest, rhs: table->MinColumnWidth));
968 table->ColumnsGivenWidth += column->WidthGiven;
969 }
970
971 // [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0f * number of Stretch column).
972 // Using right-to-left distribution (more likely to match resizing cursor).
973 if (width_remaining_for_stretched_columns >= 1.0f && !(table->Flags & ImGuiTableFlags_PreciseWidths))
974 for (int order_n = table->ColumnsCount - 1; stretch_sum_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--)
975 {
976 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n))
977 continue;
978 ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]];
979 if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch))
980 continue;
981 column->WidthRequest += 1.0f;
982 column->WidthGiven += 1.0f;
983 width_remaining_for_stretched_columns -= 1.0f;
984 }
985
986 // Determine if table is hovered which will be used to flag columns as hovered.
987 // - In principle we'd like to use the equivalent of IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
988 // but because our item is partially submitted at this point we use ItemHoverable() and a workaround (temporarily
989 // clear ActiveId, which is equivalent to the change provided by _AllowWhenBLockedByActiveItem).
990 // - This allows columns to be marked as hovered when e.g. clicking a button inside the column, or using drag and drop.
991 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, instance_no: table->InstanceCurrent);
992 table_instance->HoveredRowLast = table_instance->HoveredRowNext;
993 table_instance->HoveredRowNext = -1;
994 table->HoveredColumnBody = table->HoveredColumnBorder = -1;
995 const ImRect mouse_hit_rect(table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.Max.x, ImMax(lhs: table->OuterRect.Max.y, rhs: table->OuterRect.Min.y + table_instance->LastOuterHeight));
996 const ImGuiID backup_active_id = g.ActiveId;
997 g.ActiveId = 0;
998 const bool is_hovering_table = ItemHoverable(bb: mouse_hit_rect, id: 0, item_flags: ImGuiItemFlags_None);
999 g.ActiveId = backup_active_id;
1000
1001 // Determine skewed MousePos.x to support angled headers.
1002 float mouse_skewed_x = g.IO.MousePos.x;
1003 if (table->AngledHeadersHeight > 0.0f)
1004 if (g.IO.MousePos.y >= table->OuterRect.Min.y && g.IO.MousePos.y <= table->OuterRect.Min.y + table->AngledHeadersHeight)
1005 mouse_skewed_x += ImTrunc(f: (table->OuterRect.Min.y + table->AngledHeadersHeight - g.IO.MousePos.y) * table->AngledHeadersSlope);
1006
1007 // [Part 6] Setup final position, offset, skip/clip states and clipping rectangles, detect hovered column
1008 // Process columns in their visible orders as we are comparing the visible order and adjusting host_clip_rect while looping.
1009 int visible_n = 0;
1010 bool has_at_least_one_column_requesting_output = false;
1011 bool offset_x_frozen = (table->FreezeColumnsCount > 0);
1012 float offset_x = ((table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x) + table->OuterPaddingX - table->CellSpacingX1;
1013 ImRect host_clip_rect = table->InnerClipRect;
1014 //host_clip_rect.Max.x += table->CellPaddingX + table->CellSpacingX2;
1015 ImBitArrayClearAllBits(arr: table->VisibleMaskByIndex, bitcount: table->ColumnsCount);
1016 for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
1017 {
1018 const int column_n = table->DisplayOrderToIndex[order_n];
1019 ImGuiTableColumn* column = &table->Columns[column_n];
1020
1021 column->NavLayerCurrent = (ImS8)(table->FreezeRowsCount > 0 ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main); // Use Count NOT request so Header line changes layer when frozen
1022
1023 if (offset_x_frozen && table->FreezeColumnsCount == visible_n)
1024 {
1025 offset_x += work_rect.Min.x - table->OuterRect.Min.x;
1026 offset_x_frozen = false;
1027 }
1028
1029 // Clear status flags
1030 column->Flags &= ~ImGuiTableColumnFlags_StatusMask_;
1031
1032 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n))
1033 {
1034 // Hidden column: clear a few fields and we are done with it for the remainder of the function.
1035 // We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper.
1036 column->MinX = column->MaxX = column->WorkMinX = column->ClipRect.Min.x = column->ClipRect.Max.x = offset_x;
1037 column->WidthGiven = 0.0f;
1038 column->ClipRect.Min.y = work_rect.Min.y;
1039 column->ClipRect.Max.y = FLT_MAX;
1040 column->ClipRect.ClipWithFull(r: host_clip_rect);
1041 column->IsVisibleX = column->IsVisibleY = column->IsRequestOutput = false;
1042 column->IsSkipItems = true;
1043 column->ItemWidth = 1.0f;
1044 continue;
1045 }
1046
1047 // Detect hovered column
1048 if (is_hovering_table && mouse_skewed_x >= column->ClipRect.Min.x && mouse_skewed_x < column->ClipRect.Max.x)
1049 table->HoveredColumnBody = (ImGuiTableColumnIdx)column_n;
1050
1051 // Lock start position
1052 column->MinX = offset_x;
1053
1054 // Lock width based on start position and minimum/maximum width for this position
1055 float max_width = TableGetMaxColumnWidth(table, column_n);
1056 column->WidthGiven = ImMin(lhs: column->WidthGiven, rhs: max_width);
1057 column->WidthGiven = ImMax(lhs: column->WidthGiven, rhs: ImMin(lhs: column->WidthRequest, rhs: table->MinColumnWidth));
1058 column->MaxX = offset_x + column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f;
1059
1060 // Lock other positions
1061 // - 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.
1062 // - 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.
1063 // - ClipRect.Max.x: using MaxX makes it easier for header to receive hover highlight with no discontinuity and display sorting arrow.
1064 // - 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.
1065 column->WorkMinX = column->MinX + table->CellPaddingX + table->CellSpacingX1;
1066 column->WorkMaxX = column->MaxX - table->CellPaddingX - table->CellSpacingX2; // Expected max
1067 column->ItemWidth = ImTrunc(f: column->WidthGiven * 0.65f);
1068 column->ClipRect.Min.x = column->MinX;
1069 column->ClipRect.Min.y = work_rect.Min.y;
1070 column->ClipRect.Max.x = column->MaxX; //column->WorkMaxX;
1071 column->ClipRect.Max.y = FLT_MAX;
1072 column->ClipRect.ClipWithFull(r: host_clip_rect);
1073
1074 // Mark column as Clipped (not in sight)
1075 // Note that scrolling tables (where inner_window != outer_window) handle Y clipped earlier in BeginTable() so IsVisibleY really only applies to non-scrolling tables.
1076 // 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.
1077 // Taking advantage of LastOuterHeight would yield good results there...
1078 // 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,
1079 // and this may be used (e.g. typically by outer_window using AlwaysAutoResize or outer_window's horizontal scrollbar, but could be something else).
1080 // 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.
1081 column->IsVisibleX = (column->ClipRect.Max.x > column->ClipRect.Min.x);
1082 column->IsVisibleY = true; // (column->ClipRect.Max.y > column->ClipRect.Min.y);
1083 const bool is_visible = column->IsVisibleX; //&& column->IsVisibleY;
1084 if (is_visible)
1085 ImBitArraySetBit(arr: table->VisibleMaskByIndex, n: column_n);
1086
1087 // Mark column as requesting output from user. Note that fixed + non-resizable sets are auto-fitting at all times and therefore always request output.
1088 column->IsRequestOutput = is_visible || column->AutoFitQueue != 0 || column->CannotSkipItemsQueue != 0;
1089
1090 // Mark column as SkipItems (ignoring all items/layout)
1091 // (table->HostSkipItems is a copy of inner_window->SkipItems before we cleared it above in Part 2)
1092 column->IsSkipItems = !column->IsEnabled || table->HostSkipItems;
1093 if (column->IsSkipItems)
1094 IM_ASSERT(!is_visible);
1095 if (column->IsRequestOutput && !column->IsSkipItems)
1096 has_at_least_one_column_requesting_output = true;
1097
1098 // Update status flags
1099 column->Flags |= ImGuiTableColumnFlags_IsEnabled;
1100 if (is_visible)
1101 column->Flags |= ImGuiTableColumnFlags_IsVisible;
1102 if (column->SortOrder != -1)
1103 column->Flags |= ImGuiTableColumnFlags_IsSorted;
1104 if (table->HoveredColumnBody == column_n)
1105 column->Flags |= ImGuiTableColumnFlags_IsHovered;
1106
1107 // Alignment
1108 // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in
1109 // many cases (to be able to honor this we might be able to store a log of cells width, per row, for
1110 // visible rows, but nav/programmatic scroll would have visible artifacts.)
1111 //if (column->Flags & ImGuiTableColumnFlags_AlignRight)
1112 // column->WorkMinX = ImMax(column->WorkMinX, column->MaxX - column->ContentWidthRowsUnfrozen);
1113 //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter)
1114 // column->WorkMinX = ImLerp(column->WorkMinX, ImMax(column->StartX, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f);
1115
1116 // Reset content width variables
1117 column->ContentMaxXFrozen = column->ContentMaxXUnfrozen = column->WorkMinX;
1118 column->ContentMaxXHeadersUsed = column->ContentMaxXHeadersIdeal = column->WorkMinX;
1119
1120 // Don't decrement auto-fit counters until container window got a chance to submit its items
1121 if (table->HostSkipItems == false)
1122 {
1123 column->AutoFitQueue >>= 1;
1124 column->CannotSkipItemsQueue >>= 1;
1125 }
1126
1127 if (visible_n < table->FreezeColumnsCount)
1128 host_clip_rect.Min.x = ImClamp(v: column->MaxX + TABLE_BORDER_SIZE, mn: host_clip_rect.Min.x, mx: host_clip_rect.Max.x);
1129
1130 offset_x += column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f;
1131 visible_n++;
1132 }
1133
1134 // In case the table is visible (e.g. decorations) but all columns clipped, we keep a column visible.
1135 // Else if give no chance to a clipper-savy user to submit rows and therefore total contents height used by scrollbar.
1136 if (has_at_least_one_column_requesting_output == false)
1137 {
1138 table->Columns[table->LeftMostEnabledColumn].IsRequestOutput = true;
1139 table->Columns[table->LeftMostEnabledColumn].IsSkipItems = false;
1140 }
1141
1142 // [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)
1143 // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either
1144 // because of using _WidthAuto/_WidthStretch). This will hide the resizing option from the context menu.
1145 const float unused_x1 = ImMax(lhs: table->WorkRect.Min.x, rhs: table->Columns[table->RightMostEnabledColumn].ClipRect.Max.x);
1146 if (is_hovering_table && table->HoveredColumnBody == -1)
1147 if (mouse_skewed_x >= unused_x1)
1148 table->HoveredColumnBody = (ImGuiTableColumnIdx)table->ColumnsCount;
1149 if (has_resizable == false && (table->Flags & ImGuiTableFlags_Resizable))
1150 table->Flags &= ~ImGuiTableFlags_Resizable;
1151
1152 table->IsActiveIdAliveBeforeTable = (g.ActiveIdIsAlive != 0);
1153
1154 // [Part 8] Lock actual OuterRect/WorkRect right-most position.
1155 // This is done late to handle the case of fixed-columns tables not claiming more widths that they need.
1156 // Because of this we are careful with uses of WorkRect and InnerClipRect before this point.
1157 if (table->RightMostStretchedColumn != -1)
1158 table->Flags &= ~ImGuiTableFlags_NoHostExtendX;
1159 if (table->Flags & ImGuiTableFlags_NoHostExtendX)
1160 {
1161 table->OuterRect.Max.x = table->WorkRect.Max.x = unused_x1;
1162 table->InnerClipRect.Max.x = ImMin(lhs: table->InnerClipRect.Max.x, rhs: unused_x1);
1163 }
1164 table->InnerWindow->ParentWorkRect = table->WorkRect;
1165 table->BorderX1 = table->InnerClipRect.Min.x;
1166 table->BorderX2 = table->InnerClipRect.Max.x;
1167
1168 // Setup window's WorkRect.Max.y for GetContentRegionAvail(). Other values will be updated in each TableBeginCell() call.
1169 float window_content_max_y;
1170 if (table->Flags & ImGuiTableFlags_NoHostExtendY)
1171 window_content_max_y = table->OuterRect.Max.y;
1172 else
1173 window_content_max_y = ImMax(lhs: table->InnerWindow->ContentRegionRect.Max.y, rhs: (table->Flags & ImGuiTableFlags_ScrollY) ? 0.0f : table->OuterRect.Max.y);
1174 table->InnerWindow->WorkRect.Max.y = ImClamp(v: window_content_max_y - g.Style.CellPadding.y, mn: table->InnerWindow->WorkRect.Min.y, mx: table->InnerWindow->WorkRect.Max.y);
1175
1176 // [Part 9] Allocate draw channels and setup background cliprect
1177 TableSetupDrawChannels(table);
1178
1179 // [Part 10] Hit testing on borders
1180 if (table->Flags & ImGuiTableFlags_Resizable)
1181 TableUpdateBorders(table);
1182 table_instance->LastTopHeadersRowHeight = 0.0f;
1183 table->IsLayoutLocked = true;
1184 table->IsUsingHeaders = false;
1185
1186 // Highlight header
1187 table->HighlightColumnHeader = -1;
1188 if (table->IsContextPopupOpen && table->ContextPopupColumn != -1 && table->InstanceInteracted == table->InstanceCurrent)
1189 table->HighlightColumnHeader = table->ContextPopupColumn;
1190 else if ((table->Flags & ImGuiTableFlags_HighlightHoveredColumn) && table->HoveredColumnBody != -1 && table->HoveredColumnBody != table->ColumnsCount && table->HoveredColumnBorder == -1)
1191 if (g.ActiveId == 0 || (table->IsActiveIdInTable || g.DragDropActive))
1192 table->HighlightColumnHeader = table->HoveredColumnBody;
1193
1194 // [Part 11] Default context menu
1195 // - To append to this menu: you can call TableBeginContextMenuPopup()/.../EndPopup().
1196 // - To modify or replace this: set table->IsContextPopupNoDefaultContents = true, then call TableBeginContextMenuPopup()/.../EndPopup().
1197 // - You may call TableDrawDefaultContextMenu() with selected flags to display specific sections of the default menu,
1198 // e.g. TableDrawDefaultContextMenu(table, table->Flags & ~ImGuiTableFlags_Hideable) will display everything EXCEPT columns visibility options.
1199 if (table->DisableDefaultContextMenu == false && TableBeginContextMenuPopup(table))
1200 {
1201 TableDrawDefaultContextMenu(table, flags_for_section_to_display: table->Flags);
1202 EndPopup();
1203 }
1204
1205 // [Part 12] Sanitize and build sort specs before we have a chance to use them for display.
1206 // This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change)
1207 if (table->IsSortSpecsDirty && (table->Flags & ImGuiTableFlags_Sortable))
1208 TableSortSpecsBuild(table);
1209
1210 // [Part 13] Setup inner window decoration size (for scrolling / nav tracking to properly take account of frozen rows/columns)
1211 if (table->FreezeColumnsRequest > 0)
1212 table->InnerWindow->DecoInnerSizeX1 = table->Columns[table->DisplayOrderToIndex[table->FreezeColumnsRequest - 1]].MaxX - table->OuterRect.Min.x;
1213 if (table->FreezeRowsRequest > 0)
1214 table->InnerWindow->DecoInnerSizeY1 = table_instance->LastFrozenHeight;
1215 table_instance->LastFrozenHeight = 0.0f;
1216
1217 // Initial state
1218 ImGuiWindow* inner_window = table->InnerWindow;
1219 if (table->Flags & ImGuiTableFlags_NoClip)
1220 table->DrawSplitter->SetCurrentChannel(draw_list: inner_window->DrawList, channel_idx: TABLE_DRAW_CHANNEL_NOCLIP);
1221 else
1222 inner_window->DrawList->PushClipRect(clip_rect_min: inner_window->ClipRect.Min, clip_rect_max: inner_window->ClipRect.Max, intersect_with_current_clip_rect: false);
1223}
1224
1225// Process hit-testing on resizing borders. Actual size change will be applied in EndTable()
1226// - Set table->HoveredColumnBorder with a short delay/timer to reduce visual feedback noise.
1227void ImGui::TableUpdateBorders(ImGuiTable* table)
1228{
1229 ImGuiContext& g = *GImGui;
1230 IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable);
1231
1232 // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and
1233 // use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not
1234 // really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height).
1235 // Actual columns highlight/render will be performed in EndTable() and not be affected.
1236 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, instance_no: table->InstanceCurrent);
1237 const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS;
1238 const float hit_y1 = (table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight;
1239 const float hit_y2_body = ImMax(lhs: table->OuterRect.Max.y, rhs: hit_y1 + table_instance->LastOuterHeight);
1240 const float hit_y2_head = hit_y1 + table_instance->LastTopHeadersRowHeight;
1241
1242 for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
1243 {
1244 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n))
1245 continue;
1246
1247 const int column_n = table->DisplayOrderToIndex[order_n];
1248 ImGuiTableColumn* column = &table->Columns[column_n];
1249 if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_))
1250 continue;
1251
1252 // ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders()
1253 const float border_y2_hit = (table->Flags & ImGuiTableFlags_NoBordersInBody) ? hit_y2_head : hit_y2_body;
1254 if ((table->Flags & ImGuiTableFlags_NoBordersInBody) && table->IsUsingHeaders == false)
1255 continue;
1256
1257 if (!column->IsVisibleX && table->LastResizedColumn != column_n)
1258 continue;
1259
1260 ImGuiID column_id = TableGetColumnResizeID(table, column_n, instance_no: table->InstanceCurrent);
1261 ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, border_y2_hit);
1262 ItemAdd(bb: hit_rect, id: column_id, NULL, extra_flags: ImGuiItemFlags_NoNav);
1263 //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100));
1264
1265 bool hovered = false, held = false;
1266 bool pressed = ButtonBehavior(bb: hit_rect, id: column_id, out_hovered: &hovered, out_held: &held, flags: ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick | ImGuiButtonFlags_NoNavFocus);
1267 if (pressed && IsMouseDoubleClicked(button: 0))
1268 {
1269 TableSetColumnWidthAutoSingle(table, column_n);
1270 ClearActiveID();
1271 held = false;
1272 }
1273 if (held)
1274 {
1275 if (table->LastResizedColumn == -1)
1276 table->ResizeLockMinContentsX2 = table->RightMostEnabledColumn != -1 ? table->Columns[table->RightMostEnabledColumn].MaxX : -FLT_MAX;
1277 table->ResizedColumn = (ImGuiTableColumnIdx)column_n;
1278 table->InstanceInteracted = table->InstanceCurrent;
1279 }
1280 if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held)
1281 {
1282 table->HoveredColumnBorder = (ImGuiTableColumnIdx)column_n;
1283 SetMouseCursor(ImGuiMouseCursor_ResizeEW);
1284 }
1285 }
1286}
1287
1288void ImGui::EndTable()
1289{
1290 ImGuiContext& g = *GImGui;
1291 ImGuiTable* table = g.CurrentTable;
1292 IM_ASSERT(table != NULL && "Only call EndTable() if BeginTable() returns true!");
1293
1294 // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some
1295 // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border)
1296 //IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?");
1297
1298 // If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our
1299 // code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc.
1300 if (!table->IsLayoutLocked)
1301 TableUpdateLayout(table);
1302
1303 const ImGuiTableFlags flags = table->Flags;
1304 ImGuiWindow* inner_window = table->InnerWindow;
1305 ImGuiWindow* outer_window = table->OuterWindow;
1306 ImGuiTableTempData* temp_data = table->TempData;
1307 IM_ASSERT(inner_window == g.CurrentWindow);
1308 IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow);
1309
1310 if (table->IsInsideRow)
1311 TableEndRow(table);
1312
1313 // Context menu in columns body
1314 if (flags & ImGuiTableFlags_ContextMenuInBody)
1315 if (table->HoveredColumnBody != -1 && !IsAnyItemHovered() && IsMouseReleased(button: ImGuiMouseButton_Right))
1316 TableOpenContextMenu(column_n: (int)table->HoveredColumnBody);
1317
1318 // Finalize table height
1319 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, instance_no: table->InstanceCurrent);
1320 inner_window->DC.PrevLineSize = temp_data->HostBackupPrevLineSize;
1321 inner_window->DC.CurrLineSize = temp_data->HostBackupCurrLineSize;
1322 inner_window->DC.CursorMaxPos = temp_data->HostBackupCursorMaxPos;
1323 const float inner_content_max_y = table->RowPosY2;
1324 IM_ASSERT(table->RowPosY2 == inner_window->DC.CursorPos.y);
1325 if (inner_window != outer_window)
1326 inner_window->DC.CursorMaxPos.y = inner_content_max_y;
1327 else if (!(flags & ImGuiTableFlags_NoHostExtendY))
1328 table->OuterRect.Max.y = table->InnerRect.Max.y = ImMax(lhs: table->OuterRect.Max.y, rhs: inner_content_max_y); // Patch OuterRect/InnerRect height
1329 table->WorkRect.Max.y = ImMax(lhs: table->WorkRect.Max.y, rhs: table->OuterRect.Max.y);
1330 table_instance->LastOuterHeight = table->OuterRect.GetHeight();
1331
1332 // Setup inner scrolling range
1333 // FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window->DC.CursorMaxPos.y,
1334 // but since the later is likely to be impossible to do we'd rather update both axises together.
1335 if (table->Flags & ImGuiTableFlags_ScrollX)
1336 {
1337 const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;
1338 float max_pos_x = table->InnerWindow->DC.CursorMaxPos.x;
1339 if (table->RightMostEnabledColumn != -1)
1340 max_pos_x = ImMax(lhs: max_pos_x, rhs: table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border);
1341 if (table->ResizedColumn != -1)
1342 max_pos_x = ImMax(lhs: max_pos_x, rhs: table->ResizeLockMinContentsX2);
1343 table->InnerWindow->DC.CursorMaxPos.x = max_pos_x + table->TempData->AngledheadersExtraWidth;
1344 }
1345
1346 // Pop clipping rect
1347 if (!(flags & ImGuiTableFlags_NoClip))
1348 inner_window->DrawList->PopClipRect();
1349 inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back();
1350
1351 // Draw borders
1352 if ((flags & ImGuiTableFlags_Borders) != 0)
1353 TableDrawBorders(table);
1354
1355#if 0
1356 // Strip out dummy channel draw calls
1357 // We have no way to prevent user submitting direct ImDrawList calls into a hidden column (but ImGui:: calls will be clipped out)
1358 // Pros: remove draw calls which will have no effect. since they'll have zero-size cliprect they may be early out anyway.
1359 // Cons: making it harder for users watching metrics/debugger to spot the wasted vertices.
1360 if (table->DummyDrawChannel != (ImGuiTableColumnIdx)-1)
1361 {
1362 ImDrawChannel* dummy_channel = &table->DrawSplitter._Channels[table->DummyDrawChannel];
1363 dummy_channel->_CmdBuffer.resize(0);
1364 dummy_channel->_IdxBuffer.resize(0);
1365 }
1366#endif
1367
1368 // Flatten channels and merge draw calls
1369 ImDrawListSplitter* splitter = table->DrawSplitter;
1370 splitter->SetCurrentChannel(draw_list: inner_window->DrawList, channel_idx: 0);
1371 if ((table->Flags & ImGuiTableFlags_NoClip) == 0)
1372 TableMergeDrawChannels(table);
1373 splitter->Merge(draw_list: inner_window->DrawList);
1374
1375 // Update ColumnsAutoFitWidth to get us ahead for host using our size to auto-resize without waiting for next BeginTable()
1376 float auto_fit_width_for_fixed = 0.0f;
1377 float auto_fit_width_for_stretched = 0.0f;
1378 float auto_fit_width_for_stretched_min = 0.0f;
1379 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
1380 if (IM_BITARRAY_TESTBIT(table->EnabledMaskByIndex, column_n))
1381 {
1382 ImGuiTableColumn* column = &table->Columns[column_n];
1383 float column_width_request = ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !(column->Flags & ImGuiTableColumnFlags_NoResize)) ? column->WidthRequest : TableGetColumnWidthAuto(table, column);
1384 if (column->Flags & ImGuiTableColumnFlags_WidthFixed)
1385 auto_fit_width_for_fixed += column_width_request;
1386 else
1387 auto_fit_width_for_stretched += column_width_request;
1388 if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) && (column->Flags & ImGuiTableColumnFlags_NoResize) != 0)
1389 auto_fit_width_for_stretched_min = ImMax(lhs: auto_fit_width_for_stretched_min, rhs: column_width_request / (column->StretchWeight / table->ColumnsStretchSumWeights));
1390 }
1391 const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1);
1392 table->ColumnsAutoFitWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount + auto_fit_width_for_fixed + ImMax(lhs: auto_fit_width_for_stretched, rhs: auto_fit_width_for_stretched_min);
1393
1394 // Update scroll
1395 if ((table->Flags & ImGuiTableFlags_ScrollX) == 0 && inner_window != outer_window)
1396 {
1397 inner_window->Scroll.x = 0.0f;
1398 }
1399 else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceCurrent)
1400 {
1401 // When releasing a column being resized, scroll to keep the resulting column in sight
1402 const float neighbor_width_to_keep_visible = table->MinColumnWidth + table->CellPaddingX * 2.0f;
1403 ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn];
1404 if (column->MaxX < table->InnerClipRect.Min.x)
1405 SetScrollFromPosX(window: inner_window, local_x: column->MaxX - inner_window->Pos.x - neighbor_width_to_keep_visible, center_x_ratio: 1.0f);
1406 else if (column->MaxX > table->InnerClipRect.Max.x)
1407 SetScrollFromPosX(window: inner_window, local_x: column->MaxX - inner_window->Pos.x + neighbor_width_to_keep_visible, center_x_ratio: 1.0f);
1408 }
1409
1410 // Apply resizing/dragging at the end of the frame
1411 if (table->ResizedColumn != -1 && table->InstanceCurrent == table->InstanceInteracted)
1412 {
1413 ImGuiTableColumn* column = &table->Columns[table->ResizedColumn];
1414 const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + TABLE_RESIZE_SEPARATOR_HALF_THICKNESS);
1415 const float new_width = ImTrunc(f: new_x2 - column->MinX - table->CellSpacingX1 - table->CellPaddingX * 2.0f);
1416 table->ResizedColumnNextWidth = new_width;
1417 }
1418
1419 table->IsActiveIdInTable = (g.ActiveIdIsAlive != 0 && table->IsActiveIdAliveBeforeTable == false);
1420
1421 // Pop from id stack
1422 IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table_instance->TableInstanceID, "Mismatching PushID/PopID!");
1423 IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, "Too many PopItemWidth!");
1424 if (table->InstanceCurrent > 0)
1425 PopID();
1426 PopID();
1427
1428 // Restore window data that we modified
1429 const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;
1430 inner_window->WorkRect = temp_data->HostBackupWorkRect;
1431 inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect;
1432 inner_window->SkipItems = table->HostSkipItems;
1433 outer_window->DC.CursorPos = table->OuterRect.Min;
1434 outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth;
1435 outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize;
1436 outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset;
1437
1438 // Layout in outer window
1439 // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding
1440 // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)
1441 if (inner_window != outer_window)
1442 {
1443 EndChild();
1444 }
1445 else
1446 {
1447 ItemSize(size: table->OuterRect.GetSize());
1448 ItemAdd(bb: table->OuterRect, id: 0);
1449 }
1450
1451 // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar
1452 if (table->Flags & ImGuiTableFlags_NoHostExtendX)
1453 {
1454 // FIXME-TABLE: Could we remove this section?
1455 // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents
1456 IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);
1457 outer_window->DC.CursorMaxPos.x = ImMax(lhs: backup_outer_max_pos.x, rhs: table->OuterRect.Min.x + table->ColumnsAutoFitWidth);
1458 }
1459 else if (temp_data->UserOuterSize.x <= 0.0f)
1460 {
1461 const float decoration_size = table->TempData->AngledheadersExtraWidth + ((table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f);
1462 outer_window->DC.IdealMaxPos.x = ImMax(lhs: outer_window->DC.IdealMaxPos.x, rhs: table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - temp_data->UserOuterSize.x);
1463 outer_window->DC.CursorMaxPos.x = ImMax(lhs: backup_outer_max_pos.x, rhs: ImMin(lhs: table->OuterRect.Max.x, rhs: table->OuterRect.Min.x + table->ColumnsAutoFitWidth));
1464 }
1465 else
1466 {
1467 outer_window->DC.CursorMaxPos.x = ImMax(lhs: backup_outer_max_pos.x, rhs: table->OuterRect.Max.x);
1468 }
1469 if (temp_data->UserOuterSize.y <= 0.0f)
1470 {
1471 const float decoration_size = (table->Flags & ImGuiTableFlags_ScrollY) ? inner_window->ScrollbarSizes.y : 0.0f;
1472 outer_window->DC.IdealMaxPos.y = ImMax(lhs: outer_window->DC.IdealMaxPos.y, rhs: inner_content_max_y + decoration_size - temp_data->UserOuterSize.y);
1473 outer_window->DC.CursorMaxPos.y = ImMax(lhs: backup_outer_max_pos.y, rhs: ImMin(lhs: table->OuterRect.Max.y, rhs: inner_content_max_y));
1474 }
1475 else
1476 {
1477 // OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set)
1478 outer_window->DC.CursorMaxPos.y = ImMax(lhs: backup_outer_max_pos.y, rhs: table->OuterRect.Max.y);
1479 }
1480
1481 // Save settings
1482 if (table->IsSettingsDirty)
1483 TableSaveSettings(table);
1484 table->IsInitializing = false;
1485
1486 // Clear or restore current table, if any
1487 IM_ASSERT(g.CurrentWindow == outer_window && g.CurrentTable == table);
1488 IM_ASSERT(g.TablesTempDataStacked > 0);
1489 temp_data = (--g.TablesTempDataStacked > 0) ? &g.TablesTempData[g.TablesTempDataStacked - 1] : NULL;
1490 g.CurrentTable = temp_data ? g.Tables.GetByIndex(n: temp_data->TableIndex) : NULL;
1491 if (g.CurrentTable)
1492 {
1493 g.CurrentTable->TempData = temp_data;
1494 g.CurrentTable->DrawSplitter = &temp_data->DrawSplitter;
1495 }
1496 outer_window->DC.CurrentTableIdx = g.CurrentTable ? g.Tables.GetIndex(p: g.CurrentTable) : -1;
1497 NavUpdateCurrentWindowIsScrollPushableX();
1498}
1499
1500// See "COLUMNS SIZING POLICIES" comments at the top of this file
1501// If (init_width_or_weight <= 0.0f) it is ignored
1502void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id)
1503{
1504 ImGuiContext& g = *GImGui;
1505 ImGuiTable* table = g.CurrentTable;
1506 IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!");
1507 IM_ASSERT(table->IsLayoutLocked == false && "Need to call call TableSetupColumn() before first row!");
1508 IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && "Illegal to pass StatusMask values to TableSetupColumn()");
1509 if (table->DeclColumnsCount >= table->ColumnsCount)
1510 {
1511 IM_ASSERT_USER_ERROR(table->DeclColumnsCount < table->ColumnsCount, "Called TableSetupColumn() too many times!");
1512 return;
1513 }
1514
1515 ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount];
1516 table->DeclColumnsCount++;
1517
1518 // Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa.
1519 // Give a grace to users of ImGuiTableFlags_ScrollX.
1520 if (table->IsDefaultSizingPolicy && (flags & ImGuiTableColumnFlags_WidthMask_) == 0 && (flags & ImGuiTableFlags_ScrollX) == 0)
1521 IM_ASSERT(init_width_or_weight <= 0.0f && "Can only specify width/weight if sizing policy is set explicitly in either Table or Column.");
1522
1523 // When passing a width automatically enforce WidthFixed policy
1524 // (whereas TableSetupColumnFlags would default to WidthAuto if table is not Resizable)
1525 if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0 && init_width_or_weight > 0.0f)
1526 if ((table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedFit || (table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame)
1527 flags |= ImGuiTableColumnFlags_WidthFixed;
1528 if (flags & ImGuiTableColumnFlags_AngledHeader)
1529 {
1530 flags |= ImGuiTableColumnFlags_NoHeaderLabel;
1531 table->AngledHeadersCount++;
1532 }
1533
1534 TableSetupColumnFlags(table, column, flags_in: flags);
1535 column->UserID = user_id;
1536 flags = column->Flags;
1537
1538 // Initialize defaults
1539 column->InitStretchWeightOrWidth = init_width_or_weight;
1540 if (table->IsInitializing)
1541 {
1542 // Init width or weight
1543 if (column->WidthRequest < 0.0f && column->StretchWeight < 0.0f)
1544 {
1545 if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f)
1546 column->WidthRequest = init_width_or_weight;
1547 if (flags & ImGuiTableColumnFlags_WidthStretch)
1548 column->StretchWeight = (init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f;
1549
1550 // Disable auto-fit if an explicit width/weight has been specified
1551 if (init_width_or_weight > 0.0f)
1552 column->AutoFitQueue = 0x00;
1553 }
1554
1555 // Init default visibility/sort state
1556 if ((flags & ImGuiTableColumnFlags_DefaultHide) && (table->SettingsLoadedFlags & ImGuiTableFlags_Hideable) == 0)
1557 column->IsUserEnabled = column->IsUserEnabledNextFrame = false;
1558 if (flags & ImGuiTableColumnFlags_DefaultSort && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0)
1559 {
1560 column->SortOrder = 0; // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs.
1561 column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending);
1562 }
1563 }
1564
1565 // Store name (append with zero-terminator in contiguous buffer)
1566 column->NameOffset = -1;
1567 if (label != NULL && label[0] != 0)
1568 {
1569 column->NameOffset = (ImS16)table->ColumnsNames.size();
1570 table->ColumnsNames.append(str: label, str_end: label + strlen(s: label) + 1);
1571 }
1572}
1573
1574// [Public]
1575void ImGui::TableSetupScrollFreeze(int columns, int rows)
1576{
1577 ImGuiContext& g = *GImGui;
1578 ImGuiTable* table = g.CurrentTable;
1579 IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!");
1580 IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!");
1581 IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS);
1582 IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit
1583
1584 table->FreezeColumnsRequest = (table->Flags & ImGuiTableFlags_ScrollX) ? (ImGuiTableColumnIdx)ImMin(lhs: columns, rhs: table->ColumnsCount) : 0;
1585 table->FreezeColumnsCount = (table->InnerWindow->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0;
1586 table->FreezeRowsRequest = (table->Flags & ImGuiTableFlags_ScrollY) ? (ImGuiTableColumnIdx)rows : 0;
1587 table->FreezeRowsCount = (table->InnerWindow->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0;
1588 table->IsUnfrozenRows = (table->FreezeRowsCount == 0); // Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it.b
1589
1590 // Ensure frozen columns are ordered in their section. We still allow multiple frozen columns to be reordered.
1591 // FIXME-TABLE: This work for preserving 2143 into 21|43. How about 4321 turning into 21|43? (preserve relative order in each section)
1592 for (int column_n = 0; column_n < table->FreezeColumnsRequest; column_n++)
1593 {
1594 int order_n = table->DisplayOrderToIndex[column_n];
1595 if (order_n != column_n && order_n >= table->FreezeColumnsRequest)
1596 {
1597 ImSwap(a&: table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder, b&: table->Columns[table->DisplayOrderToIndex[column_n]].DisplayOrder);
1598 ImSwap(a&: table->DisplayOrderToIndex[order_n], b&: table->DisplayOrderToIndex[column_n]);
1599 }
1600 }
1601}
1602
1603//-----------------------------------------------------------------------------
1604// [SECTION] Tables: Simple accessors
1605//-----------------------------------------------------------------------------
1606// - TableGetColumnCount()
1607// - TableGetColumnName()
1608// - TableGetColumnName() [Internal]
1609// - TableSetColumnEnabled()
1610// - TableGetColumnFlags()
1611// - TableGetCellBgRect() [Internal]
1612// - TableGetColumnResizeID() [Internal]
1613// - TableGetHoveredColumn() [Internal]
1614// - TableGetHoveredRow() [Internal]
1615// - TableSetBgColor()
1616//-----------------------------------------------------------------------------
1617
1618int ImGui::TableGetColumnCount()
1619{
1620 ImGuiContext& g = *GImGui;
1621 ImGuiTable* table = g.CurrentTable;
1622 return table ? table->ColumnsCount : 0;
1623}
1624
1625const char* ImGui::TableGetColumnName(int column_n)
1626{
1627 ImGuiContext& g = *GImGui;
1628 ImGuiTable* table = g.CurrentTable;
1629 if (!table)
1630 return NULL;
1631 if (column_n < 0)
1632 column_n = table->CurrentColumn;
1633 return TableGetColumnName(table, column_n);
1634}
1635
1636const char* ImGui::TableGetColumnName(const ImGuiTable* table, int column_n)
1637{
1638 if (table->IsLayoutLocked == false && column_n >= table->DeclColumnsCount)
1639 return ""; // NameOffset is invalid at this point
1640 const ImGuiTableColumn* column = &table->Columns[column_n];
1641 if (column->NameOffset == -1)
1642 return "";
1643 return &table->ColumnsNames.Buf[column->NameOffset];
1644}
1645
1646// Change user accessible enabled/disabled state of a column (often perceived as "showing/hiding" from users point of view)
1647// 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)
1648// - Require table to have the ImGuiTableFlags_Hideable flag because we are manipulating user accessible state.
1649// - Request will be applied during next layout, which happens on the first call to TableNextRow() after BeginTable().
1650// - For the getter you can test (TableGetColumnFlags() & ImGuiTableColumnFlags_IsEnabled) != 0.
1651// - Alternative: the ImGuiTableColumnFlags_Disabled is an overriding/master disable flag which will also hide the column from context menu.
1652void ImGui::TableSetColumnEnabled(int column_n, bool enabled)
1653{
1654 ImGuiContext& g = *GImGui;
1655 ImGuiTable* table = g.CurrentTable;
1656 IM_ASSERT(table != NULL);
1657 if (!table)
1658 return;
1659 IM_ASSERT(table->Flags & ImGuiTableFlags_Hideable); // See comments above
1660 if (column_n < 0)
1661 column_n = table->CurrentColumn;
1662 IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
1663 ImGuiTableColumn* column = &table->Columns[column_n];
1664 column->IsUserEnabledNextFrame = enabled;
1665}
1666
1667// We allow querying for an extra column in order to poll the IsHovered state of the right-most section
1668ImGuiTableColumnFlags ImGui::TableGetColumnFlags(int column_n)
1669{
1670 ImGuiContext& g = *GImGui;
1671 ImGuiTable* table = g.CurrentTable;
1672 if (!table)
1673 return ImGuiTableColumnFlags_None;
1674 if (column_n < 0)
1675 column_n = table->CurrentColumn;
1676 if (column_n == table->ColumnsCount)
1677 return (table->HoveredColumnBody == column_n) ? ImGuiTableColumnFlags_IsHovered : ImGuiTableColumnFlags_None;
1678 return table->Columns[column_n].Flags;
1679}
1680
1681// Return the cell rectangle based on currently known height.
1682// - Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations.
1683// 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.
1684// - Important: if ImGuiTableFlags_PadOuterX is set but ImGuiTableFlags_PadInnerX is not set, the outer-most left and right
1685// columns report a small offset so their CellBgRect can extend up to the outer border.
1686// FIXME: But the rendering code in TableEndRow() nullifies that with clamping required for scrolling.
1687ImRect ImGui::TableGetCellBgRect(const ImGuiTable* table, int column_n)
1688{
1689 const ImGuiTableColumn* column = &table->Columns[column_n];
1690 float x1 = column->MinX;
1691 float x2 = column->MaxX;
1692 //if (column->PrevEnabledColumn == -1)
1693 // x1 -= table->OuterPaddingX;
1694 //if (column->NextEnabledColumn == -1)
1695 // x2 += table->OuterPaddingX;
1696 x1 = ImMax(lhs: x1, rhs: table->WorkRect.Min.x);
1697 x2 = ImMin(lhs: x2, rhs: table->WorkRect.Max.x);
1698 return ImRect(x1, table->RowPosY1, x2, table->RowPosY2);
1699}
1700
1701// Return the resizing ID for the right-side of the given column.
1702ImGuiID ImGui::TableGetColumnResizeID(ImGuiTable* table, int column_n, int instance_no)
1703{
1704 IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
1705 ImGuiID instance_id = TableGetInstanceID(table, instance_no);
1706 return instance_id + 1 + column_n; // FIXME: #6140: still not ideal
1707}
1708
1709// Return -1 when table is not hovered. return columns_count if hovering the unused space at the right of the right-most visible column.
1710int ImGui::TableGetHoveredColumn()
1711{
1712 ImGuiContext& g = *GImGui;
1713 ImGuiTable* table = g.CurrentTable;
1714 if (!table)
1715 return -1;
1716 return (int)table->HoveredColumnBody;
1717}
1718
1719// Return -1 when table is not hovered. Return maxrow+1 if in table but below last submitted row.
1720// *IMPORTANT* Unlike TableGetHoveredColumn(), this has a one frame latency in updating the value.
1721// This difference with is the reason why this is not public yet.
1722int ImGui::TableGetHoveredRow()
1723{
1724 ImGuiContext& g = *GImGui;
1725 ImGuiTable* table = g.CurrentTable;
1726 if (!table)
1727 return -1;
1728 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, instance_no: table->InstanceCurrent);
1729 return (int)table_instance->HoveredRowLast;
1730}
1731
1732void ImGui::TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n)
1733{
1734 ImGuiContext& g = *GImGui;
1735 ImGuiTable* table = g.CurrentTable;
1736 IM_ASSERT(target != ImGuiTableBgTarget_None);
1737
1738 if (color == IM_COL32_DISABLE)
1739 color = 0;
1740
1741 // We cannot draw neither the cell or row background immediately as we don't know the row height at this point in time.
1742 switch (target)
1743 {
1744 case ImGuiTableBgTarget_CellBg:
1745 {
1746 if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard
1747 return;
1748 if (column_n == -1)
1749 column_n = table->CurrentColumn;
1750 if (!IM_BITARRAY_TESTBIT(table->VisibleMaskByIndex, column_n))
1751 return;
1752 if (table->RowCellDataCurrent < 0 || table->RowCellData[table->RowCellDataCurrent].Column != column_n)
1753 table->RowCellDataCurrent++;
1754 ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCurrent];
1755 cell_data->BgColor = color;
1756 cell_data->Column = (ImGuiTableColumnIdx)column_n;
1757 break;
1758 }
1759 case ImGuiTableBgTarget_RowBg0:
1760 case ImGuiTableBgTarget_RowBg1:
1761 {
1762 if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard
1763 return;
1764 IM_ASSERT(column_n == -1);
1765 int bg_idx = (target == ImGuiTableBgTarget_RowBg1) ? 1 : 0;
1766 table->RowBgColor[bg_idx] = color;
1767 break;
1768 }
1769 default:
1770 IM_ASSERT(0);
1771 }
1772}
1773
1774//-------------------------------------------------------------------------
1775// [SECTION] Tables: Row changes
1776//-------------------------------------------------------------------------
1777// - TableGetRowIndex()
1778// - TableNextRow()
1779// - TableBeginRow() [Internal]
1780// - TableEndRow() [Internal]
1781//-------------------------------------------------------------------------
1782
1783// [Public] Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows
1784int ImGui::TableGetRowIndex()
1785{
1786 ImGuiContext& g = *GImGui;
1787 ImGuiTable* table = g.CurrentTable;
1788 if (!table)
1789 return 0;
1790 return table->CurrentRow;
1791}
1792
1793// [Public] Starts into the first cell of a new row
1794void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float row_min_height)
1795{
1796 ImGuiContext& g = *GImGui;
1797 ImGuiTable* table = g.CurrentTable;
1798
1799 if (!table->IsLayoutLocked)
1800 TableUpdateLayout(table);
1801 if (table->IsInsideRow)
1802 TableEndRow(table);
1803
1804 table->LastRowFlags = table->RowFlags;
1805 table->RowFlags = row_flags;
1806 table->RowCellPaddingY = g.Style.CellPadding.y;
1807 table->RowMinHeight = row_min_height;
1808 TableBeginRow(table);
1809
1810 // We honor min_row_height requested by user, but cannot guarantee per-row maximum height,
1811 // because that would essentially require a unique clipping rectangle per-cell.
1812 table->RowPosY2 += table->RowCellPaddingY * 2.0f;
1813 table->RowPosY2 = ImMax(lhs: table->RowPosY2, rhs: table->RowPosY1 + row_min_height);
1814
1815 // Disable output until user calls TableNextColumn()
1816 table->InnerWindow->SkipItems = true;
1817}
1818
1819// [Internal] Only called by TableNextRow()
1820void ImGui::TableBeginRow(ImGuiTable* table)
1821{
1822 ImGuiWindow* window = table->InnerWindow;
1823 IM_ASSERT(!table->IsInsideRow);
1824
1825 // New row
1826 table->CurrentRow++;
1827 table->CurrentColumn = -1;
1828 table->RowBgColor[0] = table->RowBgColor[1] = IM_COL32_DISABLE;
1829 table->RowCellDataCurrent = -1;
1830 table->IsInsideRow = true;
1831
1832 // Begin frozen rows
1833 float next_y1 = table->RowPosY2;
1834 if (table->CurrentRow == 0 && table->FreezeRowsCount > 0)
1835 next_y1 = window->DC.CursorPos.y = table->OuterRect.Min.y;
1836
1837 table->RowPosY1 = table->RowPosY2 = next_y1;
1838 table->RowTextBaseline = 0.0f;
1839 table->RowIndentOffsetX = window->DC.Indent.x - table->HostIndentX; // Lock indent
1840
1841 window->DC.PrevLineTextBaseOffset = 0.0f;
1842 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.
1843 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.
1844 window->DC.IsSameLine = window->DC.IsSetPos = false;
1845 window->DC.CursorMaxPos.y = next_y1;
1846
1847 // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging.
1848 if (table->RowFlags & ImGuiTableRowFlags_Headers)
1849 {
1850 TableSetBgColor(target: ImGuiTableBgTarget_RowBg0, color: GetColorU32(idx: ImGuiCol_TableHeaderBg));
1851 if (table->CurrentRow == 0)
1852 table->IsUsingHeaders = true;
1853 }
1854}
1855
1856// [Internal] Called by TableNextRow()
1857void ImGui::TableEndRow(ImGuiTable* table)
1858{
1859 ImGuiContext& g = *GImGui;
1860 ImGuiWindow* window = g.CurrentWindow;
1861 IM_ASSERT(window == table->InnerWindow);
1862 IM_ASSERT(table->IsInsideRow);
1863
1864 if (table->CurrentColumn != -1)
1865 TableEndCell(table);
1866
1867 // Logging
1868 if (g.LogEnabled)
1869 LogRenderedText(NULL, text: "|");
1870
1871 // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is
1872 // likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding.
1873 window->DC.CursorPos.y = table->RowPosY2;
1874
1875 // Row background fill
1876 const float bg_y1 = table->RowPosY1;
1877 const float bg_y2 = table->RowPosY2;
1878 const bool unfreeze_rows_actual = (table->CurrentRow + 1 == table->FreezeRowsCount);
1879 const bool unfreeze_rows_request = (table->CurrentRow + 1 == table->FreezeRowsRequest);
1880 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, instance_no: table->InstanceCurrent);
1881 if ((table->RowFlags & ImGuiTableRowFlags_Headers) && (table->CurrentRow == 0 || (table->LastRowFlags & ImGuiTableRowFlags_Headers)))
1882 table_instance->LastTopHeadersRowHeight += bg_y2 - bg_y1;
1883
1884 const bool is_visible = (bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y);
1885 if (is_visible)
1886 {
1887 // Update data for TableGetHoveredRow()
1888 if (table->HoveredColumnBody != -1 && g.IO.MousePos.y >= bg_y1 && g.IO.MousePos.y < bg_y2)
1889 table_instance->HoveredRowNext = table->CurrentRow;
1890
1891 // Decide of background color for the row
1892 ImU32 bg_col0 = 0;
1893 ImU32 bg_col1 = 0;
1894 if (table->RowBgColor[0] != IM_COL32_DISABLE)
1895 bg_col0 = table->RowBgColor[0];
1896 else if (table->Flags & ImGuiTableFlags_RowBg)
1897 bg_col0 = GetColorU32(idx: (table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg);
1898 if (table->RowBgColor[1] != IM_COL32_DISABLE)
1899 bg_col1 = table->RowBgColor[1];
1900
1901 // Decide of top border color
1902 ImU32 top_border_col = 0;
1903 const float border_size = TABLE_BORDER_SIZE;
1904 if (table->CurrentRow > 0 && (table->Flags & ImGuiTableFlags_BordersInnerH))
1905 top_border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight;
1906
1907 const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0;
1908 const bool draw_strong_bottom_border = unfreeze_rows_actual;
1909 if ((bg_col0 | bg_col1 | top_border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color)
1910 {
1911 // In theory we could call SetWindowClipRectBeforeSetChannel() but since we know TableEndRow() is
1912 // always followed by a change of clipping rectangle we perform the smallest overwrite possible here.
1913 if ((table->Flags & ImGuiTableFlags_NoClip) == 0)
1914 window->DrawList->_CmdHeader.ClipRect = table->Bg0ClipRectForDrawCmd.ToVec4();
1915 table->DrawSplitter->SetCurrentChannel(draw_list: window->DrawList, channel_idx: TABLE_DRAW_CHANNEL_BG0);
1916 }
1917
1918 // Draw row background
1919 // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle
1920 if (bg_col0 || bg_col1)
1921 {
1922 ImRect row_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2);
1923 row_rect.ClipWith(r: table->BgClipRect);
1924 if (bg_col0 != 0 && row_rect.Min.y < row_rect.Max.y)
1925 window->DrawList->AddRectFilled(p_min: row_rect.Min, p_max: row_rect.Max, col: bg_col0);
1926 if (bg_col1 != 0 && row_rect.Min.y < row_rect.Max.y)
1927 window->DrawList->AddRectFilled(p_min: row_rect.Min, p_max: row_rect.Max, col: bg_col1);
1928 }
1929
1930 // Draw cell background color
1931 if (draw_cell_bg_color)
1932 {
1933 ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCurrent];
1934 for (ImGuiTableCellData* cell_data = &table->RowCellData[0]; cell_data <= cell_data_end; cell_data++)
1935 {
1936 // As we render the BG here we need to clip things (for layout we would not)
1937 // FIXME: This cancels the OuterPadding addition done by TableGetCellBgRect(), need to keep it while rendering correctly while scrolling.
1938 const ImGuiTableColumn* column = &table->Columns[cell_data->Column];
1939 ImRect cell_bg_rect = TableGetCellBgRect(table, column_n: cell_data->Column);
1940 cell_bg_rect.ClipWith(r: table->BgClipRect);
1941 cell_bg_rect.Min.x = ImMax(lhs: cell_bg_rect.Min.x, rhs: column->ClipRect.Min.x); // So that first column after frozen one gets clipped when scrolling
1942 cell_bg_rect.Max.x = ImMin(lhs: cell_bg_rect.Max.x, rhs: column->MaxX);
1943 window->DrawList->AddRectFilled(p_min: cell_bg_rect.Min, p_max: cell_bg_rect.Max, col: cell_data->BgColor);
1944 }
1945 }
1946
1947 // Draw top border
1948 if (top_border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y)
1949 window->DrawList->AddLine(p1: ImVec2(table->BorderX1, bg_y1), p2: ImVec2(table->BorderX2, bg_y1), col: top_border_col, thickness: border_size);
1950
1951 // Draw bottom border at the row unfreezing mark (always strong)
1952 if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y)
1953 window->DrawList->AddLine(p1: ImVec2(table->BorderX1, bg_y2), p2: ImVec2(table->BorderX2, bg_y2), col: table->BorderColorStrong, thickness: border_size);
1954 }
1955
1956 // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle)
1957 // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and
1958 // get the new cursor position.
1959 if (unfreeze_rows_request)
1960 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
1961 table->Columns[column_n].NavLayerCurrent = ImGuiNavLayer_Main;
1962 if (unfreeze_rows_actual)
1963 {
1964 IM_ASSERT(table->IsUnfrozenRows == false);
1965 const float y0 = ImMax(lhs: table->RowPosY2 + 1, rhs: window->InnerClipRect.Min.y);
1966 table->IsUnfrozenRows = true;
1967 table_instance->LastFrozenHeight = y0 - table->OuterRect.Min.y;
1968
1969 // BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect
1970 table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(lhs: y0, rhs: window->InnerClipRect.Max.y);
1971 table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = window->InnerClipRect.Max.y;
1972 table->Bg2DrawChannelCurrent = table->Bg2DrawChannelUnfrozen;
1973 IM_ASSERT(table->Bg2ClipRectForDrawCmd.Min.y <= table->Bg2ClipRectForDrawCmd.Max.y);
1974
1975 float row_height = table->RowPosY2 - table->RowPosY1;
1976 table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y;
1977 table->RowPosY1 = table->RowPosY2 - row_height;
1978 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
1979 {
1980 ImGuiTableColumn* column = &table->Columns[column_n];
1981 column->DrawChannelCurrent = column->DrawChannelUnfrozen;
1982 column->ClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y;
1983 }
1984
1985 // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y
1986 SetWindowClipRectBeforeSetChannel(window, clip_rect: table->Columns[0].ClipRect);
1987 table->DrawSplitter->SetCurrentChannel(draw_list: window->DrawList, channel_idx: table->Columns[0].DrawChannelCurrent);
1988 }
1989
1990 if (!(table->RowFlags & ImGuiTableRowFlags_Headers))
1991 table->RowBgColorCounter++;
1992 table->IsInsideRow = false;
1993}
1994
1995//-------------------------------------------------------------------------
1996// [SECTION] Tables: Columns changes
1997//-------------------------------------------------------------------------
1998// - TableGetColumnIndex()
1999// - TableSetColumnIndex()
2000// - TableNextColumn()
2001// - TableBeginCell() [Internal]
2002// - TableEndCell() [Internal]
2003//-------------------------------------------------------------------------
2004
2005int ImGui::TableGetColumnIndex()
2006{
2007 ImGuiContext& g = *GImGui;
2008 ImGuiTable* table = g.CurrentTable;
2009 if (!table)
2010 return 0;
2011 return table->CurrentColumn;
2012}
2013
2014// [Public] Append into a specific column
2015bool ImGui::TableSetColumnIndex(int column_n)
2016{
2017 ImGuiContext& g = *GImGui;
2018 ImGuiTable* table = g.CurrentTable;
2019 if (!table)
2020 return false;
2021
2022 if (table->CurrentColumn != column_n)
2023 {
2024 if (table->CurrentColumn != -1)
2025 TableEndCell(table);
2026 IM_ASSERT(column_n >= 0 && table->ColumnsCount);
2027 TableBeginCell(table, column_n);
2028 }
2029
2030 // Return whether the column is visible. User may choose to skip submitting items based on this return value,
2031 // however they shouldn't skip submitting for columns that may have the tallest contribution to row height.
2032 return table->Columns[column_n].IsRequestOutput;
2033}
2034
2035// [Public] Append into the next column, wrap and create a new row when already on last column
2036bool ImGui::TableNextColumn()
2037{
2038 ImGuiContext& g = *GImGui;
2039 ImGuiTable* table = g.CurrentTable;
2040 if (!table)
2041 return false;
2042
2043 if (table->IsInsideRow && table->CurrentColumn + 1 < table->ColumnsCount)
2044 {
2045 if (table->CurrentColumn != -1)
2046 TableEndCell(table);
2047 TableBeginCell(table, column_n: table->CurrentColumn + 1);
2048 }
2049 else
2050 {
2051 TableNextRow();
2052 TableBeginCell(table, column_n: 0);
2053 }
2054
2055 // Return whether the column is visible. User may choose to skip submitting items based on this return value,
2056 // however they shouldn't skip submitting for columns that may have the tallest contribution to row height.
2057 return table->Columns[table->CurrentColumn].IsRequestOutput;
2058}
2059
2060
2061// [Internal] Called by TableSetColumnIndex()/TableNextColumn()
2062// This is called very frequently, so we need to be mindful of unnecessary overhead.
2063// FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns.
2064void ImGui::TableBeginCell(ImGuiTable* table, int column_n)
2065{
2066 ImGuiContext& g = *GImGui;
2067 ImGuiTableColumn* column = &table->Columns[column_n];
2068 ImGuiWindow* window = table->InnerWindow;
2069 table->CurrentColumn = column_n;
2070
2071 // Start position is roughly ~~ CellRect.Min + CellPadding + Indent
2072 float start_x = column->WorkMinX;
2073 if (column->Flags & ImGuiTableColumnFlags_IndentEnable)
2074 start_x += table->RowIndentOffsetX; // ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row.
2075
2076 window->DC.CursorPos.x = start_x;
2077 window->DC.CursorPos.y = table->RowPosY1 + table->RowCellPaddingY;
2078 window->DC.CursorMaxPos.x = window->DC.CursorPos.x;
2079 window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT
2080 window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x; // PrevLine.y is preserved. This allows users to call SameLine() to share LineSize between columns.
2081 window->DC.CurrLineTextBaseOffset = table->RowTextBaseline;
2082 window->DC.NavLayerCurrent = (ImGuiNavLayer)column->NavLayerCurrent;
2083
2084 // Note how WorkRect.Max.y is only set once during layout
2085 window->WorkRect.Min.y = window->DC.CursorPos.y;
2086 window->WorkRect.Min.x = column->WorkMinX;
2087 window->WorkRect.Max.x = column->WorkMaxX;
2088 window->DC.ItemWidth = column->ItemWidth;
2089
2090 window->SkipItems = column->IsSkipItems;
2091 if (column->IsSkipItems)
2092 {
2093 g.LastItemData.ID = 0;
2094 g.LastItemData.StatusFlags = 0;
2095 }
2096
2097 if (table->Flags & ImGuiTableFlags_NoClip)
2098 {
2099 // FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed.
2100 table->DrawSplitter->SetCurrentChannel(draw_list: window->DrawList, channel_idx: TABLE_DRAW_CHANNEL_NOCLIP);
2101 //IM_ASSERT(table->DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP);
2102 }
2103 else
2104 {
2105 // FIXME-TABLE: Could avoid this if draw channel is dummy channel?
2106 SetWindowClipRectBeforeSetChannel(window, clip_rect: column->ClipRect);
2107 table->DrawSplitter->SetCurrentChannel(draw_list: window->DrawList, channel_idx: column->DrawChannelCurrent);
2108 }
2109
2110 // Logging
2111 if (g.LogEnabled && !column->IsSkipItems)
2112 {
2113 LogRenderedText(ref_pos: &window->DC.CursorPos, text: "|");
2114 g.LogLinePosY = FLT_MAX;
2115 }
2116}
2117
2118// [Internal] Called by TableNextRow()/TableSetColumnIndex()/TableNextColumn()
2119void ImGui::TableEndCell(ImGuiTable* table)
2120{
2121 ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
2122 ImGuiWindow* window = table->InnerWindow;
2123
2124 if (window->DC.IsSetPos)
2125 ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
2126
2127 // Report maximum position so we can infer content size per column.
2128 float* p_max_pos_x;
2129 if (table->RowFlags & ImGuiTableRowFlags_Headers)
2130 p_max_pos_x = &column->ContentMaxXHeadersUsed; // Useful in case user submit contents in header row that is not a TableHeader() call
2131 else
2132 p_max_pos_x = table->IsUnfrozenRows ? &column->ContentMaxXUnfrozen : &column->ContentMaxXFrozen;
2133 *p_max_pos_x = ImMax(lhs: *p_max_pos_x, rhs: window->DC.CursorMaxPos.x);
2134 if (column->IsEnabled)
2135 table->RowPosY2 = ImMax(lhs: table->RowPosY2, rhs: window->DC.CursorMaxPos.y + table->RowCellPaddingY);
2136 column->ItemWidth = window->DC.ItemWidth;
2137
2138 // Propagate text baseline for the entire row
2139 // FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one.
2140 table->RowTextBaseline = ImMax(lhs: table->RowTextBaseline, rhs: window->DC.PrevLineTextBaseOffset);
2141}
2142
2143//-------------------------------------------------------------------------
2144// [SECTION] Tables: Columns width management
2145//-------------------------------------------------------------------------
2146// - TableGetMaxColumnWidth() [Internal]
2147// - TableGetColumnWidthAuto() [Internal]
2148// - TableSetColumnWidth()
2149// - TableSetColumnWidthAutoSingle() [Internal]
2150// - TableSetColumnWidthAutoAll() [Internal]
2151// - TableUpdateColumnsWeightFromWidth() [Internal]
2152//-------------------------------------------------------------------------
2153
2154// Maximum column content width given current layout. Use column->MinX so this value on a per-column basis.
2155float ImGui::TableGetMaxColumnWidth(const ImGuiTable* table, int column_n)
2156{
2157 const ImGuiTableColumn* column = &table->Columns[column_n];
2158 float max_width = FLT_MAX;
2159 const float min_column_distance = table->MinColumnWidth + table->CellPaddingX * 2.0f + table->CellSpacingX1 + table->CellSpacingX2;
2160 if (table->Flags & ImGuiTableFlags_ScrollX)
2161 {
2162 // Frozen columns can't reach beyond visible width else scrolling will naturally break.
2163 // (we use DisplayOrder as within a set of multiple frozen column reordering is possible)
2164 if (column->DisplayOrder < table->FreezeColumnsRequest)
2165 {
2166 max_width = (table->InnerClipRect.Max.x - (table->FreezeColumnsRequest - column->DisplayOrder) * min_column_distance) - column->MinX;
2167 max_width = max_width - table->OuterPaddingX - table->CellPaddingX - table->CellSpacingX2;
2168 }
2169 }
2170 else if ((table->Flags & ImGuiTableFlags_NoKeepColumnsVisible) == 0)
2171 {
2172 // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make
2173 // sure they are all visible. Because of this we also know that all of the columns will always fit in
2174 // table->WorkRect and therefore in table->InnerRect (because ScrollX is off)
2175 // FIXME-TABLE: This is solved incorrectly but also quite a difficult problem to fix as we also want ClipRect width to match.
2176 // See "table_width_distrib" and "table_width_keep_visible" tests
2177 max_width = table->WorkRect.Max.x - (table->ColumnsEnabledCount - column->IndexWithinEnabledSet - 1) * min_column_distance - column->MinX;
2178 //max_width -= table->CellSpacingX1;
2179 max_width -= table->CellSpacingX2;
2180 max_width -= table->CellPaddingX * 2.0f;
2181 max_width -= table->OuterPaddingX;
2182 }
2183 return max_width;
2184}
2185
2186// Note this is meant to be stored in column->WidthAuto, please generally use the WidthAuto field
2187float ImGui::TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column)
2188{
2189 const float content_width_body = ImMax(lhs: column->ContentMaxXFrozen, rhs: column->ContentMaxXUnfrozen) - column->WorkMinX;
2190 const float content_width_headers = column->ContentMaxXHeadersIdeal - column->WorkMinX;
2191 float width_auto = content_width_body;
2192 if (!(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth))
2193 width_auto = ImMax(lhs: width_auto, rhs: content_width_headers);
2194
2195 // Non-resizable fixed columns preserve their requested width
2196 if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f)
2197 if (!(table->Flags & ImGuiTableFlags_Resizable) || (column->Flags & ImGuiTableColumnFlags_NoResize))
2198 width_auto = column->InitStretchWeightOrWidth;
2199
2200 return ImMax(lhs: width_auto, rhs: table->MinColumnWidth);
2201}
2202
2203// 'width' = inner column width, without padding
2204void ImGui::TableSetColumnWidth(int column_n, float width)
2205{
2206 ImGuiContext& g = *GImGui;
2207 ImGuiTable* table = g.CurrentTable;
2208 IM_ASSERT(table != NULL && table->IsLayoutLocked == false);
2209 IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
2210 ImGuiTableColumn* column_0 = &table->Columns[column_n];
2211 float column_0_width = width;
2212
2213 // Apply constraints early
2214 // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded)
2215 IM_ASSERT(table->MinColumnWidth > 0.0f);
2216 const float min_width = table->MinColumnWidth;
2217 const float max_width = ImMax(lhs: min_width, rhs: TableGetMaxColumnWidth(table, column_n));
2218 column_0_width = ImClamp(v: column_0_width, mn: min_width, mx: max_width);
2219 if (column_0->WidthGiven == column_0_width || column_0->WidthRequest == column_0_width)
2220 return;
2221
2222 //IMGUI_DEBUG_PRINT("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthGiven, column_0_width);
2223 ImGuiTableColumn* column_1 = (column_0->NextEnabledColumn != -1) ? &table->Columns[column_0->NextEnabledColumn] : NULL;
2224
2225 // In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns.
2226 // - All fixed: easy.
2227 // - All stretch: easy.
2228 // - One or more fixed + one stretch: easy.
2229 // - One or more fixed + more than one stretch: tricky.
2230 // Qt when manual resize is enabled only supports a single _trailing_ stretch column, we support more cases here.
2231
2232 // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1.
2233 // FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user.
2234 // Scenarios:
2235 // - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset.
2236 // - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered.
2237 // - 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.
2238 // - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
2239 // - W1 W2 W3 resize from W1| or W2| --> ok
2240 // - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
2241 // - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1)
2242 // - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1)
2243 // - W1 W2 F3 resize from W1| or W2| --> ok
2244 // - W1 F2 W3 resize from W1| or F2| --> ok
2245 // - F1 W2 F3 resize from W2| --> ok
2246 // - F1 W3 F2 resize from W3| --> ok
2247 // - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move.
2248 // - W1 F2 F3 resize from F2| --> ok
2249 // All resizes from a Wx columns are locking other columns.
2250
2251 // Possible improvements:
2252 // - 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.
2253 // - 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.
2254
2255 // [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout().
2256
2257 // 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.
2258 // This is the preferred resize path
2259 if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed)
2260 if (!column_1 || table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder >= column_0->DisplayOrder)
2261 {
2262 column_0->WidthRequest = column_0_width;
2263 table->IsSettingsDirty = true;
2264 return;
2265 }
2266
2267 // 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)
2268 if (column_1 == NULL)
2269 column_1 = (column_0->PrevEnabledColumn != -1) ? &table->Columns[column_0->PrevEnabledColumn] : NULL;
2270 if (column_1 == NULL)
2271 return;
2272
2273 // Resizing from right-side of a Stretch column before a Fixed column forward sizing to left-side of fixed column.
2274 // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b)
2275 float column_1_width = ImMax(lhs: column_1->WidthRequest - (column_0_width - column_0->WidthRequest), rhs: min_width);
2276 column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width;
2277 IM_ASSERT(column_0_width > 0.0f && column_1_width > 0.0f);
2278 column_0->WidthRequest = column_0_width;
2279 column_1->WidthRequest = column_1_width;
2280 if ((column_0->Flags | column_1->Flags) & ImGuiTableColumnFlags_WidthStretch)
2281 TableUpdateColumnsWeightFromWidth(table);
2282 table->IsSettingsDirty = true;
2283}
2284
2285// Disable clipping then auto-fit, will take 2 frames
2286// (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns)
2287void ImGui::TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n)
2288{
2289 // Single auto width uses auto-fit
2290 ImGuiTableColumn* column = &table->Columns[column_n];
2291 if (!column->IsEnabled)
2292 return;
2293 column->CannotSkipItemsQueue = (1 << 0);
2294 table->AutoFitSingleColumn = (ImGuiTableColumnIdx)column_n;
2295}
2296
2297void ImGui::TableSetColumnWidthAutoAll(ImGuiTable* table)
2298{
2299 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2300 {
2301 ImGuiTableColumn* column = &table->Columns[column_n];
2302 if (!column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) // Cannot reset weight of hidden stretch column
2303 continue;
2304 column->CannotSkipItemsQueue = (1 << 0);
2305 column->AutoFitQueue = (1 << 1);
2306 }
2307}
2308
2309void ImGui::TableUpdateColumnsWeightFromWidth(ImGuiTable* table)
2310{
2311 IM_ASSERT(table->LeftMostStretchedColumn != -1 && table->RightMostStretchedColumn != -1);
2312
2313 // Measure existing quantities
2314 float visible_weight = 0.0f;
2315 float visible_width = 0.0f;
2316 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2317 {
2318 ImGuiTableColumn* column = &table->Columns[column_n];
2319 if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
2320 continue;
2321 IM_ASSERT(column->StretchWeight > 0.0f);
2322 visible_weight += column->StretchWeight;
2323 visible_width += column->WidthRequest;
2324 }
2325 IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f);
2326
2327 // Apply new weights
2328 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2329 {
2330 ImGuiTableColumn* column = &table->Columns[column_n];
2331 if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
2332 continue;
2333 column->StretchWeight = (column->WidthRequest / visible_width) * visible_weight;
2334 IM_ASSERT(column->StretchWeight > 0.0f);
2335 }
2336}
2337
2338//-------------------------------------------------------------------------
2339// [SECTION] Tables: Drawing
2340//-------------------------------------------------------------------------
2341// - TablePushBackgroundChannel() [Internal]
2342// - TablePopBackgroundChannel() [Internal]
2343// - TableSetupDrawChannels() [Internal]
2344// - TableMergeDrawChannels() [Internal]
2345// - TableGetColumnBorderCol() [Internal]
2346// - TableDrawBorders() [Internal]
2347//-------------------------------------------------------------------------
2348
2349// Bg2 is used by Selectable (and possibly other widgets) to render to the background.
2350// 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.
2351void ImGui::TablePushBackgroundChannel()
2352{
2353 ImGuiContext& g = *GImGui;
2354 ImGuiWindow* window = g.CurrentWindow;
2355 ImGuiTable* table = g.CurrentTable;
2356
2357 // Optimization: avoid SetCurrentChannel() + PushClipRect()
2358 table->HostBackupInnerClipRect = window->ClipRect;
2359 SetWindowClipRectBeforeSetChannel(window, clip_rect: table->Bg2ClipRectForDrawCmd);
2360 table->DrawSplitter->SetCurrentChannel(draw_list: window->DrawList, channel_idx: table->Bg2DrawChannelCurrent);
2361}
2362
2363void ImGui::TablePopBackgroundChannel()
2364{
2365 ImGuiContext& g = *GImGui;
2366 ImGuiWindow* window = g.CurrentWindow;
2367 ImGuiTable* table = g.CurrentTable;
2368 ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
2369
2370 // Optimization: avoid PopClipRect() + SetCurrentChannel()
2371 SetWindowClipRectBeforeSetChannel(window, clip_rect: table->HostBackupInnerClipRect);
2372 table->DrawSplitter->SetCurrentChannel(draw_list: window->DrawList, channel_idx: column->DrawChannelCurrent);
2373}
2374
2375// Allocate draw channels. Called by TableUpdateLayout()
2376// - We allocate them following storage order instead of display order so reordering columns won't needlessly
2377// increase overall dormant memory cost.
2378// - We isolate headers draw commands in their own channels instead of just altering clip rects.
2379// This is in order to facilitate merging of draw commands.
2380// - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels.
2381// - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other
2382// channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged.
2383// - We allocate 1 or 2 background draw channels. This is because we know TablePushBackgroundChannel() is only used for
2384// horizontal spanning. If we allowed vertical spanning we'd need one background draw channel per merge group (1-4).
2385// Draw channel allocation (before merging):
2386// - NoClip --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call)
2387// - Clip --> 2+D+N channels
2388// - FreezeRows --> 2+D+N*2 (unless scrolling value is zero)
2389// - FreezeRows || FreezeColunns --> 3+D+N*2 (unless scrolling value is zero)
2390// Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0.
2391void ImGui::TableSetupDrawChannels(ImGuiTable* table)
2392{
2393 const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1;
2394 const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClip) ? 1 : table->ColumnsEnabledCount;
2395 const int channels_for_bg = 1 + 1 * freeze_row_multiplier;
2396 const int channels_for_dummy = (table->ColumnsEnabledCount < table->ColumnsCount || (memcmp(s1: table->VisibleMaskByIndex, s2: table->EnabledMaskByIndex, n: ImBitArrayGetStorageSizeInBytes(bitcount: table->ColumnsCount)) != 0)) ? +1 : 0;
2397 const int channels_total = channels_for_bg + (channels_for_row * freeze_row_multiplier) + channels_for_dummy;
2398 table->DrawSplitter->Split(draw_list: table->InnerWindow->DrawList, count: channels_total);
2399 table->DummyDrawChannel = (ImGuiTableDrawChannelIdx)((channels_for_dummy > 0) ? channels_total - 1 : -1);
2400 table->Bg2DrawChannelCurrent = TABLE_DRAW_CHANNEL_BG2_FROZEN;
2401 table->Bg2DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)((table->FreezeRowsCount > 0) ? 2 + channels_for_row : TABLE_DRAW_CHANNEL_BG2_FROZEN);
2402
2403 int draw_channel_current = 2;
2404 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2405 {
2406 ImGuiTableColumn* column = &table->Columns[column_n];
2407 if (column->IsVisibleX && column->IsVisibleY)
2408 {
2409 column->DrawChannelFrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current);
2410 column->DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row + 1 : 0));
2411 if (!(table->Flags & ImGuiTableFlags_NoClip))
2412 draw_channel_current++;
2413 }
2414 else
2415 {
2416 column->DrawChannelFrozen = column->DrawChannelUnfrozen = table->DummyDrawChannel;
2417 }
2418 column->DrawChannelCurrent = column->DrawChannelFrozen;
2419 }
2420
2421 // Initial draw cmd starts with a BgClipRect that matches the one of its host, to facilitate merge draw commands by default.
2422 // All our cell highlight are manually clipped with BgClipRect. When unfreezing it will be made smaller to fit scrolling rect.
2423 // (This technically isn't part of setting up draw channels, but is reasonably related to be done here)
2424 table->BgClipRect = table->InnerClipRect;
2425 table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect;
2426 table->Bg2ClipRectForDrawCmd = table->HostClipRect;
2427 IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y);
2428}
2429
2430// This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable().
2431// For simplicity we call it TableMergeDrawChannels() but in fact it only reorder channels + overwrite ClipRect,
2432// actual merging is done by table->DrawSplitter.Merge() which is called right after TableMergeDrawChannels().
2433//
2434// Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve
2435// this we merge their clip rect and make them contiguous in the channel list, so they can be merged
2436// by the call to DrawSplitter.Merge() following to the call to this function.
2437// We reorder draw commands by arranging them into a maximum of 4 distinct groups:
2438//
2439// 1 group: 2 groups: 2 groups: 4 groups:
2440// [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze
2441// [ .. ] or no scroll [ 2. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll
2442//
2443// Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled).
2444// When the contents of a column didn't stray off its limit, we move its channels into the corresponding group
2445// based on its position (within frozen rows/columns groups or not).
2446// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect.
2447// This function assume that each column are pointing to a distinct draw channel,
2448// otherwise merge_group->ChannelsCount will not match set bit count of merge_group->ChannelsMask.
2449//
2450// Column channels will not be merged into one of the 1-4 groups in the following cases:
2451// - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value).
2452// Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds
2453// matches, by e.g. calling SetCursorScreenPos().
2454// - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here..
2455// we could do better but it's going to be rare and probably not worth the hassle.
2456// Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd.
2457//
2458// This function is particularly tricky to understand.. take a breath.
2459void ImGui::TableMergeDrawChannels(ImGuiTable* table)
2460{
2461 ImGuiContext& g = *GImGui;
2462 ImDrawListSplitter* splitter = table->DrawSplitter;
2463 const bool has_freeze_v = (table->FreezeRowsCount > 0);
2464 const bool has_freeze_h = (table->FreezeColumnsCount > 0);
2465 IM_ASSERT(splitter->_Current == 0);
2466
2467 // Track which groups we are going to attempt to merge, and which channels goes into each group.
2468 struct MergeGroup
2469 {
2470 ImRect ClipRect;
2471 int ChannelsCount = 0;
2472 ImBitArrayPtr ChannelsMask = NULL;
2473 };
2474 int merge_group_mask = 0x00;
2475 MergeGroup merge_groups[4];
2476
2477 // Use a reusable temp buffer for the merge masks as they are dynamically sized.
2478 const int max_draw_channels = (4 + table->ColumnsCount * 2);
2479 const int size_for_masks_bitarrays_one = (int)ImBitArrayGetStorageSizeInBytes(bitcount: max_draw_channels);
2480 g.TempBuffer.reserve(new_capacity: size_for_masks_bitarrays_one * 5);
2481 memset(s: g.TempBuffer.Data, c: 0, n: size_for_masks_bitarrays_one * 5);
2482 for (int n = 0; n < IM_ARRAYSIZE(merge_groups); n++)
2483 merge_groups[n].ChannelsMask = (ImBitArrayPtr)(void*)(g.TempBuffer.Data + (size_for_masks_bitarrays_one * n));
2484 ImBitArrayPtr remaining_mask = (ImBitArrayPtr)(void*)(g.TempBuffer.Data + (size_for_masks_bitarrays_one * 4));
2485
2486 // 1. Scan channels and take note of those which can be merged
2487 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2488 {
2489 if (!IM_BITARRAY_TESTBIT(table->VisibleMaskByIndex, column_n))
2490 continue;
2491 ImGuiTableColumn* column = &table->Columns[column_n];
2492
2493 const int merge_group_sub_count = has_freeze_v ? 2 : 1;
2494 for (int merge_group_sub_n = 0; merge_group_sub_n < merge_group_sub_count; merge_group_sub_n++)
2495 {
2496 const int channel_no = (merge_group_sub_n == 0) ? column->DrawChannelFrozen : column->DrawChannelUnfrozen;
2497
2498 // Don't attempt to merge if there are multiple draw calls within the column
2499 ImDrawChannel* src_channel = &splitter->_Channels[channel_no];
2500 if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0 && src_channel->_CmdBuffer.back().UserCallback == NULL) // Equivalent of PopUnusedDrawCmd()
2501 src_channel->_CmdBuffer.pop_back();
2502 if (src_channel->_CmdBuffer.Size != 1)
2503 continue;
2504
2505 // Find out the width of this merge group and check if it will fit in our column
2506 // (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it)
2507 if (!(column->Flags & ImGuiTableColumnFlags_NoClip))
2508 {
2509 float content_max_x;
2510 if (!has_freeze_v)
2511 content_max_x = ImMax(lhs: column->ContentMaxXUnfrozen, rhs: column->ContentMaxXHeadersUsed); // No row freeze
2512 else if (merge_group_sub_n == 0)
2513 content_max_x = ImMax(lhs: column->ContentMaxXFrozen, rhs: column->ContentMaxXHeadersUsed); // Row freeze: use width before freeze
2514 else
2515 content_max_x = column->ContentMaxXUnfrozen; // Row freeze: use width after freeze
2516 if (content_max_x > column->ClipRect.Max.x)
2517 continue;
2518 }
2519
2520 const int merge_group_n = (has_freeze_h && column_n < table->FreezeColumnsCount ? 0 : 1) + (has_freeze_v && merge_group_sub_n == 0 ? 0 : 2);
2521 IM_ASSERT(channel_no < max_draw_channels);
2522 MergeGroup* merge_group = &merge_groups[merge_group_n];
2523 if (merge_group->ChannelsCount == 0)
2524 merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
2525 ImBitArraySetBit(arr: merge_group->ChannelsMask, n: channel_no);
2526 merge_group->ChannelsCount++;
2527 merge_group->ClipRect.Add(r: src_channel->_CmdBuffer[0].ClipRect);
2528 merge_group_mask |= (1 << merge_group_n);
2529 }
2530
2531 // Invalidate current draw channel
2532 // (we don't clear DrawChannelFrozen/DrawChannelUnfrozen solely to facilitate debugging/later inspection of data)
2533 column->DrawChannelCurrent = (ImGuiTableDrawChannelIdx)-1;
2534 }
2535
2536 // [DEBUG] Display merge groups
2537#if 0
2538 if (g.IO.KeyShift)
2539 for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++)
2540 {
2541 MergeGroup* merge_group = &merge_groups[merge_group_n];
2542 if (merge_group->ChannelsCount == 0)
2543 continue;
2544 char buf[32];
2545 ImFormatString(buf, 32, "MG%d:%d", merge_group_n, merge_group->ChannelsCount);
2546 ImVec2 text_pos = merge_group->ClipRect.Min + ImVec2(4, 4);
2547 ImVec2 text_size = CalcTextSize(buf, NULL);
2548 GetForegroundDrawList()->AddRectFilled(text_pos, text_pos + text_size, IM_COL32(0, 0, 0, 255));
2549 GetForegroundDrawList()->AddText(text_pos, IM_COL32(255, 255, 0, 255), buf, NULL);
2550 GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 255, 0, 255));
2551 }
2552#endif
2553
2554 // 2. Rewrite channel list in our preferred order
2555 if (merge_group_mask != 0)
2556 {
2557 // We skip channel 0 (Bg0/Bg1) and 1 (Bg2 frozen) from the shuffling since they won't move - see channels allocation in TableSetupDrawChannels().
2558 const int LEADING_DRAW_CHANNELS = 2;
2559 g.DrawChannelsTempMergeBuffer.resize(new_size: splitter->_Count - LEADING_DRAW_CHANNELS); // Use shared temporary storage so the allocation gets amortized
2560 ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data;
2561 ImBitArraySetBitRange(arr: remaining_mask, n: LEADING_DRAW_CHANNELS, n2: splitter->_Count);
2562 ImBitArrayClearBit(arr: remaining_mask, n: table->Bg2DrawChannelUnfrozen);
2563 IM_ASSERT(has_freeze_v == false || table->Bg2DrawChannelUnfrozen != TABLE_DRAW_CHANNEL_BG2_FROZEN);
2564 int remaining_count = splitter->_Count - (has_freeze_v ? LEADING_DRAW_CHANNELS + 1 : LEADING_DRAW_CHANNELS);
2565 //ImRect host_rect = (table->InnerWindow == table->OuterWindow) ? table->InnerClipRect : table->HostClipRect;
2566 ImRect host_rect = table->HostClipRect;
2567 for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++)
2568 {
2569 if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount)
2570 {
2571 MergeGroup* merge_group = &merge_groups[merge_group_n];
2572 ImRect merge_clip_rect = merge_group->ClipRect;
2573
2574 // Extend outer-most clip limits to match those of host, so draw calls can be merged even if
2575 // outer-most columns have some outer padding offsetting them from their parent ClipRect.
2576 // The principal cases this is dealing with are:
2577 // - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge
2578 // - 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
2579 // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit
2580 // within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect.
2581 if ((merge_group_n & 1) == 0 || !has_freeze_h)
2582 merge_clip_rect.Min.x = ImMin(lhs: merge_clip_rect.Min.x, rhs: host_rect.Min.x);
2583 if ((merge_group_n & 2) == 0 || !has_freeze_v)
2584 merge_clip_rect.Min.y = ImMin(lhs: merge_clip_rect.Min.y, rhs: host_rect.Min.y);
2585 if ((merge_group_n & 1) != 0)
2586 merge_clip_rect.Max.x = ImMax(lhs: merge_clip_rect.Max.x, rhs: host_rect.Max.x);
2587 if ((merge_group_n & 2) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0)
2588 merge_clip_rect.Max.y = ImMax(lhs: merge_clip_rect.Max.y, rhs: host_rect.Max.y);
2589 //GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, 0, 1.0f); // [DEBUG]
2590 //GetForegroundDrawList()->AddLine(merge_group->ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200));
2591 //GetForegroundDrawList()->AddLine(merge_group->ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200));
2592 remaining_count -= merge_group->ChannelsCount;
2593 for (int n = 0; n < (size_for_masks_bitarrays_one >> 2); n++)
2594 remaining_mask[n] &= ~merge_group->ChannelsMask[n];
2595 for (int n = 0; n < splitter->_Count && merge_channels_count != 0; n++)
2596 {
2597 // Copy + overwrite new clip rect
2598 if (!IM_BITARRAY_TESTBIT(merge_group->ChannelsMask, n))
2599 continue;
2600 IM_BITARRAY_CLEARBIT(merge_group->ChannelsMask, n);
2601 merge_channels_count--;
2602
2603 ImDrawChannel* channel = &splitter->_Channels[n];
2604 IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect)));
2605 channel->_CmdBuffer[0].ClipRect = merge_clip_rect.ToVec4();
2606 memcpy(dest: dst_tmp++, src: channel, n: sizeof(ImDrawChannel));
2607 }
2608 }
2609
2610 // Make sure Bg2DrawChannelUnfrozen appears in the middle of our groups (whereas Bg0/Bg1 and Bg2 frozen are fixed to 0 and 1)
2611 if (merge_group_n == 1 && has_freeze_v)
2612 memcpy(dest: dst_tmp++, src: &splitter->_Channels[table->Bg2DrawChannelUnfrozen], n: sizeof(ImDrawChannel));
2613 }
2614
2615 // Append unmergeable channels that we didn't reorder at the end of the list
2616 for (int n = 0; n < splitter->_Count && remaining_count != 0; n++)
2617 {
2618 if (!IM_BITARRAY_TESTBIT(remaining_mask, n))
2619 continue;
2620 ImDrawChannel* channel = &splitter->_Channels[n];
2621 memcpy(dest: dst_tmp++, src: channel, n: sizeof(ImDrawChannel));
2622 remaining_count--;
2623 }
2624 IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size);
2625 memcpy(dest: splitter->_Channels.Data + LEADING_DRAW_CHANNELS, src: g.DrawChannelsTempMergeBuffer.Data, n: (splitter->_Count - LEADING_DRAW_CHANNELS) * sizeof(ImDrawChannel));
2626 }
2627}
2628
2629static ImU32 TableGetColumnBorderCol(ImGuiTable* table, int order_n, int column_n)
2630{
2631 const bool is_hovered = (table->HoveredColumnBorder == column_n);
2632 const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent);
2633 const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1);
2634 if (is_resized || is_hovered)
2635 return ImGui::GetColorU32(idx: is_resized ? ImGuiCol_SeparatorActive : ImGuiCol_SeparatorHovered);
2636 if (is_frozen_separator || (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)))
2637 return table->BorderColorStrong;
2638 return table->BorderColorLight;
2639}
2640
2641// FIXME-TABLE: This is a mess, need to redesign how we render borders (as some are also done in TableEndRow)
2642void ImGui::TableDrawBorders(ImGuiTable* table)
2643{
2644 ImGuiWindow* inner_window = table->InnerWindow;
2645 if (!table->OuterWindow->ClipRect.Overlaps(r: table->OuterRect))
2646 return;
2647
2648 ImDrawList* inner_drawlist = inner_window->DrawList;
2649 table->DrawSplitter->SetCurrentChannel(draw_list: inner_drawlist, channel_idx: TABLE_DRAW_CHANNEL_BG0);
2650 inner_drawlist->PushClipRect(clip_rect_min: table->Bg0ClipRectForDrawCmd.Min, clip_rect_max: table->Bg0ClipRectForDrawCmd.Max, intersect_with_current_clip_rect: false);
2651
2652 // Draw inner border and resizing feedback
2653 ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, instance_no: table->InstanceCurrent);
2654 const float border_size = TABLE_BORDER_SIZE;
2655 const float draw_y1 = ImMax(lhs: table->InnerRect.Min.y, rhs: (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->AngledHeadersHeight) + ((table->Flags & ImGuiTableFlags_BordersOuterH) ? 1.0f : 0.0f);
2656 const float draw_y2_body = table->InnerRect.Max.y;
2657 const float draw_y2_head = table->IsUsingHeaders ? ImMin(lhs: table->InnerRect.Max.y, rhs: (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table_instance->LastTopHeadersRowHeight) : draw_y1;
2658 if (table->Flags & ImGuiTableFlags_BordersInnerV)
2659 {
2660 for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
2661 {
2662 if (!IM_BITARRAY_TESTBIT(table->EnabledMaskByDisplayOrder, order_n))
2663 continue;
2664
2665 const int column_n = table->DisplayOrderToIndex[order_n];
2666 ImGuiTableColumn* column = &table->Columns[column_n];
2667 const bool is_hovered = (table->HoveredColumnBorder == column_n);
2668 const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent);
2669 const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0;
2670 const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1);
2671 if (column->MaxX > table->InnerClipRect.Max.x && !is_resized)
2672 continue;
2673
2674 // Decide whether right-most column is visible
2675 if (column->NextEnabledColumn == -1 && !is_resizable)
2676 if ((table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame || (table->Flags & ImGuiTableFlags_NoHostExtendX))
2677 continue;
2678 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..
2679 continue;
2680
2681 // Draw in outer window so right-most column won't be clipped
2682 // Always draw full height border when being resized/hovered, or on the delimitation of frozen column scrolling.
2683 float draw_y2 = (is_hovered || is_resized || is_frozen_separator || (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) == 0) ? draw_y2_body : draw_y2_head;
2684 if (draw_y2 > draw_y1)
2685 inner_drawlist->AddLine(p1: ImVec2(column->MaxX, draw_y1), p2: ImVec2(column->MaxX, draw_y2), col: TableGetColumnBorderCol(table, order_n, column_n), thickness: border_size);
2686 }
2687 }
2688
2689 // Draw outer border
2690 // FIXME: could use AddRect or explicit VLine/HLine helper?
2691 if (table->Flags & ImGuiTableFlags_BordersOuter)
2692 {
2693 // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call
2694 // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their
2695 // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part
2696 // of it in inner window, and the part that's over scrollbars in the outer window..)
2697 // Either solution currently won't allow us to use a larger border size: the border would clipped.
2698 const ImRect outer_border = table->OuterRect;
2699 const ImU32 outer_col = table->BorderColorStrong;
2700 if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter)
2701 {
2702 inner_drawlist->AddRect(p_min: outer_border.Min, p_max: outer_border.Max + ImVec2(1, 1), col: outer_col, rounding: 0.0f, flags: 0, thickness: border_size);
2703 }
2704 else if (table->Flags & ImGuiTableFlags_BordersOuterV)
2705 {
2706 inner_drawlist->AddLine(p1: outer_border.Min, p2: ImVec2(outer_border.Min.x, outer_border.Max.y), col: outer_col, thickness: border_size);
2707 inner_drawlist->AddLine(p1: ImVec2(outer_border.Max.x, outer_border.Min.y), p2: outer_border.Max, col: outer_col, thickness: border_size);
2708 }
2709 else if (table->Flags & ImGuiTableFlags_BordersOuterH)
2710 {
2711 inner_drawlist->AddLine(p1: outer_border.Min, p2: ImVec2(outer_border.Max.x, outer_border.Min.y), col: outer_col, thickness: border_size);
2712 inner_drawlist->AddLine(p1: ImVec2(outer_border.Min.x, outer_border.Max.y), p2: outer_border.Max, col: outer_col, thickness: border_size);
2713 }
2714 }
2715 if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y)
2716 {
2717 // Draw bottom-most row border between it is above outer border.
2718 const float border_y = table->RowPosY2;
2719 if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y)
2720 inner_drawlist->AddLine(p1: ImVec2(table->BorderX1, border_y), p2: ImVec2(table->BorderX2, border_y), col: table->BorderColorLight, thickness: border_size);
2721 }
2722
2723 inner_drawlist->PopClipRect();
2724}
2725
2726//-------------------------------------------------------------------------
2727// [SECTION] Tables: Sorting
2728//-------------------------------------------------------------------------
2729// - TableGetSortSpecs()
2730// - TableFixColumnSortDirection() [Internal]
2731// - TableGetColumnNextSortDirection() [Internal]
2732// - TableSetColumnSortDirection() [Internal]
2733// - TableSortSpecsSanitize() [Internal]
2734// - TableSortSpecsBuild() [Internal]
2735//-------------------------------------------------------------------------
2736
2737// Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set)
2738// When 'sort_specs->SpecsDirty == true' you should sort your data. It will be true when sorting specs have
2739// changed since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting,
2740// else you may wastefully sort your data every frame!
2741// Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()!
2742ImGuiTableSortSpecs* ImGui::TableGetSortSpecs()
2743{
2744 ImGuiContext& g = *GImGui;
2745 ImGuiTable* table = g.CurrentTable;
2746 IM_ASSERT(table != NULL);
2747
2748 if (!(table->Flags & ImGuiTableFlags_Sortable))
2749 return NULL;
2750
2751 // Require layout (in case TableHeadersRow() hasn't been called) as it may alter IsSortSpecsDirty in some paths.
2752 if (!table->IsLayoutLocked)
2753 TableUpdateLayout(table);
2754
2755 TableSortSpecsBuild(table);
2756 return &table->SortSpecs;
2757}
2758
2759static inline ImGuiSortDirection TableGetColumnAvailSortDirection(ImGuiTableColumn* column, int n)
2760{
2761 IM_ASSERT(n < column->SortDirectionsAvailCount);
2762 return (column->SortDirectionsAvailList >> (n << 1)) & 0x03;
2763}
2764
2765// Fix sort direction if currently set on a value which is unavailable (e.g. activating NoSortAscending/NoSortDescending)
2766void ImGui::TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column)
2767{
2768 if (column->SortOrder == -1 || (column->SortDirectionsAvailMask & (1 << column->SortDirection)) != 0)
2769 return;
2770 column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, n: 0);
2771 table->IsSortSpecsDirty = true;
2772}
2773
2774// Calculate next sort direction that would be set after clicking the column
2775// - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click.
2776// - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op.
2777IM_STATIC_ASSERT(ImGuiSortDirection_None == 0 && ImGuiSortDirection_Ascending == 1 && ImGuiSortDirection_Descending == 2);
2778ImGuiSortDirection ImGui::TableGetColumnNextSortDirection(ImGuiTableColumn* column)
2779{
2780 IM_ASSERT(column->SortDirectionsAvailCount > 0);
2781 if (column->SortOrder == -1)
2782 return TableGetColumnAvailSortDirection(column, n: 0);
2783 for (int n = 0; n < 3; n++)
2784 if (column->SortDirection == TableGetColumnAvailSortDirection(column, n))
2785 return TableGetColumnAvailSortDirection(column, n: (n + 1) % column->SortDirectionsAvailCount);
2786 IM_ASSERT(0);
2787 return ImGuiSortDirection_None;
2788}
2789
2790// Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert
2791// the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code.
2792void ImGui::TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs)
2793{
2794 ImGuiContext& g = *GImGui;
2795 ImGuiTable* table = g.CurrentTable;
2796
2797 if (!(table->Flags & ImGuiTableFlags_SortMulti))
2798 append_to_sort_specs = false;
2799 if (!(table->Flags & ImGuiTableFlags_SortTristate))
2800 IM_ASSERT(sort_direction != ImGuiSortDirection_None);
2801
2802 ImGuiTableColumnIdx sort_order_max = 0;
2803 if (append_to_sort_specs)
2804 for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
2805 sort_order_max = ImMax(lhs: sort_order_max, rhs: table->Columns[other_column_n].SortOrder);
2806
2807 ImGuiTableColumn* column = &table->Columns[column_n];
2808 column->SortDirection = (ImU8)sort_direction;
2809 if (column->SortDirection == ImGuiSortDirection_None)
2810 column->SortOrder = -1;
2811 else if (column->SortOrder == -1 || !append_to_sort_specs)
2812 column->SortOrder = append_to_sort_specs ? sort_order_max + 1 : 0;
2813
2814 for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
2815 {
2816 ImGuiTableColumn* other_column = &table->Columns[other_column_n];
2817 if (other_column != column && !append_to_sort_specs)
2818 other_column->SortOrder = -1;
2819 TableFixColumnSortDirection(table, column: other_column);
2820 }
2821 table->IsSettingsDirty = true;
2822 table->IsSortSpecsDirty = true;
2823}
2824
2825void ImGui::TableSortSpecsSanitize(ImGuiTable* table)
2826{
2827 IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable);
2828
2829 // Clear SortOrder from hidden column and verify that there's no gap or duplicate.
2830 int sort_order_count = 0;
2831 ImU64 sort_order_mask = 0x00;
2832 for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
2833 {
2834 ImGuiTableColumn* column = &table->Columns[column_n];
2835 if (column->SortOrder != -1 && !column->IsEnabled)
2836 column->SortOrder = -1;
2837 if (