Debian Codegraph @

source/code/Libs/imgui/imgui_tables.cpp

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