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