Debian Codegraph @

extern/imgui_patched/imgui_tables.cpp

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