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