imgui_tables.cpp 133 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815
  1. // dear imgui, v1.80 WIP
  2. // (tables and columns code)
  3. /*
  4. *
  5. * Index of this file:
  6. *
  7. * // [SECTION] Widgets: BeginTable, EndTable, etc.
  8. * // [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc.
  9. *
  10. */
  11. #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
  12. #define _CRT_SECURE_NO_WARNINGS
  13. #endif
  14. #include "imgui.h"
  15. #ifndef IMGUI_DISABLE
  16. #ifndef IMGUI_DEFINE_MATH_OPERATORS
  17. #define IMGUI_DEFINE_MATH_OPERATORS
  18. #endif
  19. #include "imgui_internal.h"
  20. #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
  21. #include <stddef.h> // intptr_t
  22. #else
  23. #include <stdint.h> // intptr_t
  24. #endif
  25. // Visual Studio warnings
  26. #ifdef _MSC_VER
  27. #pragma warning (disable: 4127) // condition expression is constant
  28. #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
  29. #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
  30. #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
  31. #endif
  32. #endif
  33. // Clang/GCC warnings with -Weverything
  34. #if defined(__clang__)
  35. #if __has_warning("-Wunknown-warning-option")
  36. #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!
  37. #endif
  38. #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
  39. #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
  40. #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.
  41. #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
  42. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
  43. #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.
  44. #pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_')
  45. #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
  46. #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
  47. #elif defined(__GNUC__)
  48. #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
  49. #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
  50. #endif
  51. //-----------------------------------------------------------------------------
  52. // [SECTION] Widgets: BeginTable, EndTable, etc.
  53. //-----------------------------------------------------------------------------
  54. // Typical call flow: (root level is public API):
  55. // - BeginTable() user begin into a table
  56. // - BeginChild() - (if ScrollX/ScrollY is set)
  57. // - TableBeginInitVisibility() - lock columns visibility
  58. // - TableSetupColumn() user submit columns details (optional)
  59. // - TableAutoHeaders() or TableHeader() user submit a headers row (optional)
  60. // - TableSortSpecsClickColumn()
  61. // - TableGetSortSpecs() user queries updated sort specs (optional)
  62. // - TableNextRow() / TableNextCell() user begin into the first row, also automatically called by TableAutoHeaders()
  63. // - TableUpdateLayout() - called by the FIRST call to TableNextRow()
  64. // - TableUpdateDrawChannels() - setup ImDrawList channels
  65. // - TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission
  66. // - TableDrawContextMenu() - draw right-click context menu
  67. // - [...] user emit contents
  68. // - EndTable() user ends the table
  69. // - TableDrawBorders() - draw outer borders, inner vertical borders
  70. // - TableDrawMergeChannels() - merge draw channels if clipping isn't required
  71. // - TableSetColumnWidth() - apply resizing width
  72. // - TableUpdateColumnsWeightFromWidth()
  73. // - EndChild() - (if ScrollX/ScrollY is set)
  74. // Configuration
  75. static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders.
  76. 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.
  77. // Helper
  78. inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags)
  79. {
  80. // Adjust flags: set default sizing policy
  81. if ((flags & ImGuiTableFlags_SizingPolicyMaskX_) == 0)
  82. flags |= (flags & ImGuiTableFlags_ScrollX) ? ImGuiTableFlags_SizingPolicyFixedX : ImGuiTableFlags_SizingPolicyStretchX;
  83. // Adjust flags: MultiSortable automatically enable Sortable
  84. if (flags & ImGuiTableFlags_MultiSortable)
  85. flags |= ImGuiTableFlags_Sortable;
  86. // Adjust flags: disable saved settings if there's nothing to save
  87. if ((flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Sortable)) == 0)
  88. flags |= ImGuiTableFlags_NoSavedSettings;
  89. // Adjust flags: enforce borders when resizable
  90. if (flags & ImGuiTableFlags_Resizable)
  91. flags |= ImGuiTableFlags_BordersV;
  92. // Adjust flags: disable top rows freezing if there's no scrolling
  93. if ((flags & ImGuiTableFlags_ScrollX) == 0)
  94. flags &= ~ImGuiTableFlags_ScrollFreezeColumnsMask_;
  95. if ((flags & ImGuiTableFlags_ScrollY) == 0)
  96. flags &= ~ImGuiTableFlags_ScrollFreezeRowsMask_;
  97. // Adjust flags: disable NoHostExtendY if we have any scrolling going on
  98. if ((flags & ImGuiTableFlags_NoHostExtendY) && (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0)
  99. flags &= ~ImGuiTableFlags_NoHostExtendY;
  100. // Adjust flags: we don't support NoClipX with (FreezeColumns > 0), we could with some work but it doesn't appear to be worth the effort
  101. if (flags & ImGuiTableFlags_ScrollFreezeColumnsMask_)
  102. flags &= ~ImGuiTableFlags_NoClipX;
  103. return flags;
  104. }
  105. // About 'outer_size':
  106. // The meaning of outer_size needs to differ slightly depending of if we are using ScrollX/ScrollY flags.
  107. // With ScrollX/ScrollY: using a child window for scrolling:
  108. // - outer_size.y < 0.0f -> bottom align
  109. // - outer_size.y = 0.0f -> bottom align: consistent with BeginChild(), best to preserve (0,0) default arg
  110. // - outer_size.y > 0.0f -> fixed child height
  111. // Without scrolling, we output table directly in parent window:
  112. // - outer_size.y < 0.0f -> bottom align (will auto extend, unless NoHostExtendV is set)
  113. // - outer_size.y = 0.0f -> zero minimum height (will auto extend, unless NoHostExtendV is set)
  114. // - outer_size.y > 0.0f -> minimum height (will auto extend, unless NoHostExtendV is set)
  115. // About: 'inner_width':
  116. // With ScrollX:
  117. // - inner_width < 0.0f -> *illegal* fit in known width (right align from outer_size.x) <-- weird
  118. // - inner_width = 0.0f -> auto enlarge: *only* fixed size columns, which will take space they need (proportional columns becomes fixed columns) <-- desired default :(
  119. // - inner_width > 0.0f -> fit in known width: fixed column take space they need if possible (otherwise shrink down), proportional columns share remaining space.
  120. // Without ScrollX:
  121. // - inner_width < 0.0f -> fit in known width (right align from outer_size.x) <-- desired default
  122. // - inner_width = 0.0f -> auto enlarge: will emit contents size in parent window
  123. // - inner_width > 0.0f -> fit in known width (bypass outer_size.x, permitted but not useful, should instead alter outer_width)
  124. // FIXME-TABLE: This is currently not very useful.
  125. // FIXME-TABLE: Replace enlarge vs fixed width by a flag.
  126. // Even if not really useful, we allow 'inner_scroll_width < outer_size.x' for consistency and to facilitate understanding of what the value does.
  127. bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
  128. {
  129. ImGuiID id = GetID(str_id);
  130. return BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width);
  131. }
  132. bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
  133. {
  134. ImGuiContext& g = *GImGui;
  135. ImGuiWindow* outer_window = GetCurrentWindow();
  136. IM_ASSERT(columns_count > 0 && columns_count < IMGUI_TABLE_MAX_COLUMNS && "Only 0..63 columns allowed!");
  137. if (flags & ImGuiTableFlags_ScrollX)
  138. IM_ASSERT(inner_width >= 0.0f);
  139. const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0;
  140. const ImVec2 avail_size = GetContentRegionAvail();
  141. ImVec2 actual_outer_size = CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f);
  142. ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size);
  143. // If an outer size is specified ahead we will be able to early out when not visible. Exact clipping rules may evolve.
  144. if (use_child_window && IsClippedEx(outer_rect, 0, false))
  145. {
  146. ItemSize(outer_rect);
  147. return false;
  148. }
  149. flags = TableFixFlags(flags);
  150. if (outer_window->Flags & ImGuiWindowFlags_NoSavedSettings)
  151. flags |= ImGuiTableFlags_NoSavedSettings;
  152. // Acquire storage for the table
  153. ImGuiTable* table = g.Tables.GetOrAddByKey(id);
  154. const ImGuiTableFlags table_last_flags = table->Flags;
  155. const int instance_no = (table->LastFrameActive != g.FrameCount) ? 0 : table->InstanceNo + 1;
  156. const ImGuiID instance_id = id + instance_no;
  157. if (instance_no > 0)
  158. IM_ASSERT(table->ColumnsCount == columns_count && "BeginTable(): Cannot change columns count mid-frame while preserving same ID");
  159. // Initialize
  160. table->ID = id;
  161. table->Flags = flags;
  162. table->IsFirstFrame = (table->LastFrameActive == -1);
  163. table->InstanceNo = (ImS16)instance_no;
  164. table->LastFrameActive = g.FrameCount;
  165. table->OuterWindow = table->InnerWindow = outer_window;
  166. table->ColumnsCount = columns_count;
  167. table->ColumnsNames.Buf.resize(0);
  168. table->IsLayoutLocked = false;
  169. table->InnerWidth = inner_width;
  170. table->OuterRect = outer_rect;
  171. table->WorkRect = outer_rect;
  172. if (use_child_window)
  173. {
  174. // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing)
  175. ImVec2 override_content_size(FLT_MAX, FLT_MAX);
  176. if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY))
  177. override_content_size.y = FLT_MIN;
  178. // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and never lead to any scrolling)
  179. // We don't handle inner_width < 0.0f, we could potentially use it to right-align based on the right side of the child window work rect,
  180. // which would require knowing ahead if we are going to have decoration taking horizontal spaces (typically a vertical scrollbar).
  181. if (inner_width != 0.0f)
  182. override_content_size.x = inner_width;
  183. if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX)
  184. 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));
  185. // Create scrolling region (without border = zero window padding)
  186. ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None;
  187. BeginChildEx(name, instance_id, table->OuterRect.GetSize(), false, child_flags);
  188. table->InnerWindow = g.CurrentWindow;
  189. table->WorkRect = table->InnerWindow->WorkRect;
  190. table->OuterRect = table->InnerWindow->Rect();
  191. }
  192. else
  193. {
  194. // WorkRect.Max will grow as we append contents.
  195. PushID(instance_id);
  196. }
  197. const bool has_cell_padding_x = (flags & (ImGuiTableFlags_BordersOuter | ImGuiTableFlags_BordersV)) != 0;
  198. ImGuiWindow* inner_window = table->InnerWindow;
  199. table->CurrentColumn = -1;
  200. table->CurrentRow = -1;
  201. table->RowBgColorCounter = 0;
  202. table->LastRowFlags = ImGuiTableRowFlags_None;
  203. table->CellPaddingX1 = has_cell_padding_x ? g.Style.CellPadding.x + 1.0f : 0.0f;
  204. table->CellPaddingX2 = has_cell_padding_x ? g.Style.CellPadding.x : 0.0f;
  205. table->CellPaddingY = g.Style.CellPadding.y;
  206. table->CellSpacingX = has_cell_padding_x ? 0.0f : g.Style.CellPadding.x;
  207. table->HostClipRect = inner_window->ClipRect;
  208. table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect;
  209. table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width
  210. table->InnerClipRect.ClipWith(table->HostClipRect);
  211. table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? table->WorkRect.Max.y : inner_window->ClipRect.Max.y;
  212. table->BackgroundClipRect = table->InnerClipRect;
  213. table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow
  214. table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow()
  215. table->FreezeRowsRequest = (ImS8)((flags & ImGuiTableFlags_ScrollFreezeRowsMask_) >> ImGuiTableFlags_ScrollFreezeRowsShift_);
  216. table->FreezeRowsCount = (inner_window->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0;
  217. table->FreezeColumnsRequest = (ImS8)((flags & ImGuiTableFlags_ScrollFreezeColumnsMask_) >> ImGuiTableFlags_ScrollFreezeColumnsShift_);
  218. table->FreezeColumnsCount = (inner_window->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0;
  219. table->IsFreezeRowsPassed = (table->FreezeRowsCount == 0);
  220. table->DeclColumnsCount = 0;
  221. table->LastResizedColumn = table->ResizedColumn;
  222. table->HoveredColumnBody = -1;
  223. table->HoveredColumnBorder = -1;
  224. table->RightMostActiveColumn = -1;
  225. table->IsFirstFrame = false;
  226. // FIXME-TABLE FIXME-STYLE: Using opaque colors facilitate overlapping elements of the grid
  227. //table->BorderOuterColor = GetColorU32(ImGuiCol_Separator, 1.00f);
  228. //table->BorderInnerColor = GetColorU32(ImGuiCol_Separator, 0.60f);
  229. table->BorderOuterColor = GetColorU32(ImVec4(0.31f, 0.31f, 0.35f, 1.00f));
  230. table->BorderInnerColor = GetColorU32(ImVec4(0.23f, 0.23f, 0.25f, 1.00f));
  231. //table->BorderOuterColor = IM_COL32(255, 0, 0, 255);
  232. //table->BorderInnerColor = IM_COL32(255, 255, 0, 255);
  233. table->BorderX1 = table->InnerClipRect.Min.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : -1.0f);
  234. table->BorderX2 = table->InnerClipRect.Max.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : +1.0f);
  235. // Make table current
  236. g.CurrentTableStack.push_back(ImGuiPtrOrIndex(g.Tables.GetIndex(table)));
  237. g.CurrentTable = table;
  238. outer_window->DC.CurrentTable = table;
  239. if ((table_last_flags & ImGuiTableFlags_Reorderable) && !(flags & ImGuiTableFlags_Reorderable))
  240. table->IsResetDisplayOrderRequest = true;
  241. // Clear data if columns count changed
  242. if (table->Columns.Size != 0 && table->Columns.Size != columns_count)
  243. {
  244. table->Columns.resize(0);
  245. table->DisplayOrder.resize(0);
  246. }
  247. // Setup default columns state
  248. if (table->Columns.Size == 0)
  249. {
  250. table->IsFirstFrame = true;
  251. table->IsSortSpecsDirty = true;
  252. table->Columns.reserve(columns_count);
  253. table->DisplayOrder.reserve(columns_count);
  254. for (int n = 0; n < columns_count; n++)
  255. {
  256. ImGuiTableColumn column;
  257. column.IndexDisplayOrder = (ImS8)n;
  258. table->Columns.push_back(column);
  259. table->DisplayOrder.push_back(column.IndexDisplayOrder);
  260. }
  261. }
  262. // Load settings
  263. if (table->IsFirstFrame || table->IsSettingsRequestLoad)
  264. TableLoadSettings(table);
  265. // Handle resizing request
  266. // (We process this at the first beginning of the frame)
  267. // FIXME-TABLE: Preserve contents width _while resizing down_ until releasing.
  268. // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling.
  269. if (table->InstanceNo == 0)
  270. {
  271. if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX)
  272. TableSetColumnWidth(table, &table->Columns[table->ResizedColumn], table->ResizedColumnNextWidth);
  273. table->ResizedColumnNextWidth = FLT_MAX;
  274. table->ResizedColumn = -1;
  275. }
  276. // Handle reordering request
  277. // Note: we don't clear ReorderColumn after handling the request.
  278. if (table->InstanceNo == 0)
  279. {
  280. if (table->HeadHeaderColumn == -1 && table->ReorderColumn != -1)
  281. table->ReorderColumn = -1;
  282. table->HeadHeaderColumn = -1;
  283. if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0)
  284. {
  285. IM_ASSERT(table->ReorderColumnDir == -1 || table->ReorderColumnDir == +1);
  286. IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable);
  287. ImGuiTableColumn* dragged_column = &table->Columns[table->ReorderColumn];
  288. ImGuiTableColumn* target_column = &table->Columns[(table->ReorderColumnDir == -1) ? dragged_column->PrevActiveColumn : dragged_column->NextActiveColumn];
  289. ImSwap(table->DisplayOrder[dragged_column->IndexDisplayOrder], table->DisplayOrder[target_column->IndexDisplayOrder]);
  290. ImSwap(dragged_column->IndexDisplayOrder, target_column->IndexDisplayOrder);
  291. table->ReorderColumnDir = 0;
  292. table->IsSettingsDirty = true;
  293. }
  294. }
  295. // Handle display order reset request
  296. if (table->IsResetDisplayOrderRequest)
  297. {
  298. for (int n = 0; n < columns_count; n++)
  299. table->DisplayOrder[n] = table->Columns[n].IndexDisplayOrder = (ImU8)n;
  300. table->IsResetDisplayOrderRequest = false;
  301. table->IsSettingsDirty = true;
  302. }
  303. TableBeginInitVisibility(table);
  304. // Grab a copy of window fields we will modify
  305. table->BackupSkipItems = inner_window->SkipItems;
  306. table->BackupWorkRect = inner_window->WorkRect;
  307. table->BackupCursorMaxPos = inner_window->DC.CursorMaxPos;
  308. if (flags & ImGuiTableFlags_NoClipX)
  309. table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 1);
  310. else
  311. inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false);
  312. return true;
  313. }
  314. void ImGui::TableBeginInitVisibility(ImGuiTable* table)
  315. {
  316. // Setup and lock Active state and order
  317. table->ColumnsActiveCount = 0;
  318. table->IsDefaultDisplayOrder = true;
  319. ImGuiTableColumn* last_active_column = NULL;
  320. bool want_column_auto_fit = false;
  321. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  322. {
  323. const int column_n = table->DisplayOrder[order_n];
  324. if (column_n != order_n)
  325. table->IsDefaultDisplayOrder = false;
  326. ImGuiTableColumn* column = &table->Columns[column_n];
  327. column->NameOffset = -1;
  328. if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide))
  329. column->NextIsActive = true;
  330. if (column->IsActive != column->NextIsActive)
  331. {
  332. column->IsActive = column->NextIsActive;
  333. table->IsSettingsDirty = true;
  334. if (!column->IsActive && column->SortOrder != -1)
  335. table->IsSortSpecsDirty = true;
  336. }
  337. if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_MultiSortable))
  338. table->IsSortSpecsDirty = true;
  339. if (column->AutoFitQueue != 0x00)
  340. want_column_auto_fit = true;
  341. ImU64 index_mask = (ImU64)1 << column_n;
  342. ImU64 display_order_mask = (ImU64)1 << column->IndexDisplayOrder;
  343. if (column->IsActive)
  344. {
  345. column->PrevActiveColumn = column->NextActiveColumn = -1;
  346. if (last_active_column)
  347. {
  348. last_active_column->NextActiveColumn = (ImS8)column_n;
  349. column->PrevActiveColumn = (ImS8)table->Columns.index_from_ptr(last_active_column);
  350. }
  351. column->IndexWithinActiveSet = (ImS8)table->ColumnsActiveCount;
  352. table->ColumnsActiveCount++;
  353. table->ActiveMaskByIndex |= index_mask;
  354. table->ActiveMaskByDisplayOrder |= display_order_mask;
  355. last_active_column = column;
  356. }
  357. else
  358. {
  359. column->IndexWithinActiveSet = -1;
  360. table->ActiveMaskByIndex &= ~index_mask;
  361. table->ActiveMaskByDisplayOrder &= ~display_order_mask;
  362. }
  363. IM_ASSERT(column->IndexWithinActiveSet <= column->IndexDisplayOrder);
  364. }
  365. table->VisibleMaskByIndex = table->ActiveMaskByIndex; // Columns will be masked out by TableUpdateLayout() when Clipped
  366. table->RightMostActiveColumn = (ImS8)(last_active_column ? table->Columns.index_from_ptr(last_active_column) : -1);
  367. // Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid
  368. // the column fitting to wait until the first visible frame of the child container (may or not be a good thing).
  369. if (want_column_auto_fit && table->OuterWindow != table->InnerWindow)
  370. table->InnerWindow->SkipItems = false;
  371. }
  372. void ImGui::TableUpdateDrawChannels(ImGuiTable* table)
  373. {
  374. // Allocate draw channels.
  375. // - We allocate them following the storage order instead of the display order so reordering won't needlessly increase overall dormant memory cost
  376. // - We isolate headers draw commands in their own channels instead of just altering clip rects. This is in order to facilitate merging of draw commands.
  377. // - After crossing FreezeRowsCount, all columns see their current draw channel increased.
  378. // - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged.
  379. // Draw channel allocation (before merging):
  380. // - NoClip --> 1+1 channels: background + foreground (same clip rect == 1 draw call)
  381. // - Clip --> 1+N channels
  382. // - FreezeRows || FreezeColumns --> 1+N*2 (unless scrolling value is zero)
  383. // - FreezeRows && FreezeColunns --> 2+N*2 (unless scrolling value is zero)
  384. const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1;
  385. const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClipX) ? 1 : table->ColumnsActiveCount;
  386. const int channels_for_background = 1;
  387. const int channels_for_dummy = (table->ColumnsActiveCount < table->ColumnsCount || table->VisibleMaskByIndex != table->ActiveMaskByIndex) ? +1 : 0;
  388. const int channels_total = channels_for_background + (channels_for_row * freeze_row_multiplier) + channels_for_dummy;
  389. table->DrawSplitter.Split(table->InnerWindow->DrawList, channels_total);
  390. table->DummyDrawChannel = channels_for_dummy ? (ImS8)(channels_total - 1) : -1;
  391. int draw_channel_current = 1;
  392. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  393. {
  394. ImGuiTableColumn* column = &table->Columns[column_n];
  395. if (!column->IsClipped)
  396. {
  397. column->DrawChannelRowsBeforeFreeze = (ImS8)(draw_channel_current);
  398. column->DrawChannelRowsAfterFreeze = (ImS8)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row : 0));
  399. if (!(table->Flags & ImGuiTableFlags_NoClipX))
  400. draw_channel_current++;
  401. }
  402. else
  403. {
  404. column->DrawChannelRowsBeforeFreeze = column->DrawChannelRowsAfterFreeze = table->DummyDrawChannel;
  405. }
  406. column->DrawChannelCurrent = column->DrawChannelRowsBeforeFreeze;
  407. }
  408. }
  409. // Adjust flags: default width mode + weighted columns are not allowed when auto extending
  410. static ImGuiTableColumnFlags TableFixColumnFlags(ImGuiTable* table, ImGuiTableColumnFlags flags)
  411. {
  412. // Sizing Policy
  413. if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0)
  414. {
  415. if (table->Flags & ImGuiTableFlags_SizingPolicyFixedX)
  416. flags |= ((table->Flags & ImGuiTableFlags_Resizable) && !(flags & ImGuiTableColumnFlags_NoResize)) ? ImGuiTableColumnFlags_WidthFixed : ImGuiTableColumnFlags_WidthAlwaysAutoResize;
  417. else
  418. flags |= ImGuiTableColumnFlags_WidthStretch;
  419. }
  420. IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_WidthMask_)); // Check that only 1 of each set is used.
  421. if ((flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize))// || ((flags & ImGuiTableColumnFlags_WidthStretch) && (table->Flags & ImGuiTableFlags_SizingPolicyStretchX)))
  422. flags |= ImGuiTableColumnFlags_NoResize;
  423. //if ((flags & ImGuiTableColumnFlags_WidthStretch) && (table->Flags & ImGuiTableFlags_SizingPolicyFixedX))
  424. // flags = (flags & ~ImGuiTableColumnFlags_WidthMask_) | ImGuiTableColumnFlags_WidthFixed;
  425. // Sorting
  426. if ((flags & ImGuiTableColumnFlags_NoSortAscending) && (flags & ImGuiTableColumnFlags_NoSortDescending))
  427. flags |= ImGuiTableColumnFlags_NoSort;
  428. // Alignment
  429. //if ((flags & ImGuiTableColumnFlags_AlignMask_) == 0)
  430. // flags |= ImGuiTableColumnFlags_AlignCenter;
  431. //IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_AlignMask_)); // Check that only 1 of each set is used.
  432. return flags;
  433. }
  434. static void TableFixColumnSortDirection(ImGuiTableColumn* column)
  435. {
  436. // Handle NoSortAscending/NoSortDescending
  437. if (column->SortDirection == ImGuiSortDirection_Ascending && (column->Flags & ImGuiTableColumnFlags_NoSortAscending))
  438. column->SortDirection = ImGuiSortDirection_Descending;
  439. else if (column->SortDirection == ImGuiSortDirection_Descending && (column->Flags & ImGuiTableColumnFlags_NoSortDescending))
  440. column->SortDirection = ImGuiSortDirection_Ascending;
  441. }
  442. static float TableGetMinColumnWidth()
  443. {
  444. ImGuiContext& g = *GImGui;
  445. // return g.Style.ColumnsMinSpacing;
  446. return g.Style.FramePadding.x * 3.0f;
  447. }
  448. // Layout columns for the frame
  449. // Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() to be called first.
  450. // FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for WidthAlwaysAutoResize columns,
  451. // increase feedback side-effect with widgets relying on WorkRect.Max.x. Maybe provide a default distribution for WidthAlwaysAutoResize columns?
  452. void ImGui::TableUpdateLayout(ImGuiTable* table)
  453. {
  454. IM_ASSERT(table->IsLayoutLocked == false);
  455. // Compute offset, clip rect for the frame
  456. const ImRect work_rect = table->WorkRect;
  457. const float padding_auto_x = table->CellPaddingX1; // Can't make auto padding larger than what WorkRect knows about so right-alignment matches.
  458. const float min_column_width = TableGetMinColumnWidth();
  459. int count_fixed = 0;
  460. float width_fixed = 0.0f;
  461. float total_weights = 0.0f;
  462. table->LeftMostStretchedColumnDisplayOrder = -1;
  463. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  464. {
  465. if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n)))
  466. continue;
  467. const int column_n = table->DisplayOrder[order_n];
  468. ImGuiTableColumn* column = &table->Columns[column_n];
  469. // Adjust flags: default width mode + weighted columns are not allowed when auto extending
  470. // FIXME-TABLE: Clarify why we need to do this again here and not just in TableSetupColumn()
  471. column->Flags = TableFixColumnFlags(table, column->FlagsIn);
  472. // We have a unusual edge case where if the user doesn't call TableGetSortSpecs() but has sorting enabled
  473. // or varying sorting flags, we still want the sorting arrows to honor those flags.
  474. if (table->Flags & ImGuiTableFlags_Sortable)
  475. TableFixColumnSortDirection(column);
  476. if (column->Flags & (ImGuiTableColumnFlags_WidthAlwaysAutoResize | ImGuiTableColumnFlags_WidthFixed))
  477. {
  478. // Latch initial size for fixed columns
  479. count_fixed += 1;
  480. const bool init_size = (column->AutoFitQueue != 0x00) || (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize);
  481. if (init_size)
  482. {
  483. // Combine width from regular rows + width from headers unless requested not to
  484. float width_request = (float)ImMax(column->ContentWidthRowsFrozen, column->ContentWidthRowsUnfrozen);
  485. if (!(table->Flags & ImGuiTableFlags_NoHeadersWidth) && !(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth))
  486. width_request = ImMax(width_request, (float)column->ContentWidthHeadersDesired);
  487. column->WidthRequested = ImMax(width_request + padding_auto_x, min_column_width);
  488. // FIXME-TABLE: Increase minimum size during init frame so avoid biasing auto-fitting widgets (e.g. TextWrapped) too much.
  489. // Otherwise what tends to happen is that TextWrapped would output a very large height (= first frame scrollbar display very off + clipper would skip lots of items)
  490. // This is merely making the side-effect less extreme, but doesn't properly fixes it.
  491. if (column->AutoFitQueue > 0x01 && table->IsFirstFrame)
  492. column->WidthRequested = ImMax(column->WidthRequested, min_column_width * 4.0f);
  493. }
  494. width_fixed += column->WidthRequested;
  495. }
  496. else
  497. {
  498. IM_ASSERT(column->Flags & ImGuiTableColumnFlags_WidthStretch);
  499. IM_ASSERT(column->ResizeWeight > 0.0f);
  500. total_weights += column->ResizeWeight;
  501. if (table->LeftMostStretchedColumnDisplayOrder == -1)
  502. table->LeftMostStretchedColumnDisplayOrder = (ImS8)column->IndexDisplayOrder;
  503. }
  504. }
  505. // Layout
  506. const float width_spacings = table->CellSpacingX * (table->ColumnsActiveCount - 1);
  507. float width_avail;
  508. if ((table->Flags & ImGuiTableFlags_ScrollX) && (table->InnerWidth == 0.0f))
  509. width_avail = table->InnerClipRect.GetWidth() - width_spacings - 1.0f;
  510. else
  511. width_avail = work_rect.GetWidth() - width_spacings - 1.0f; // Remove -1.0f to cancel out the +1.0f we are doing in EndTable() to make last column line visible
  512. const float width_avail_for_stretched_columns = width_avail - width_fixed;
  513. float width_remaining_for_stretched_columns = width_avail_for_stretched_columns;
  514. // Apply final width based on requested widths
  515. // Mark some columns as not resizable
  516. int count_resizable = 0;
  517. table->ColumnsTotalWidth = width_spacings;
  518. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  519. {
  520. if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n)))
  521. continue;
  522. ImGuiTableColumn* column = &table->Columns[table->DisplayOrder[order_n]];
  523. // Allocate width for stretched/weighted columns
  524. if (column->Flags & ImGuiTableColumnFlags_WidthStretch)
  525. {
  526. float weight_ratio = column->ResizeWeight / total_weights;
  527. column->WidthRequested = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, min_column_width) + 0.01f);
  528. width_remaining_for_stretched_columns -= column->WidthRequested;
  529. // [Resize Rule 2] Resizing from right-side of a weighted column before a fixed column froward sizing to left-side of fixed column
  530. // We also need to copy the NoResize flag..
  531. if (column->NextActiveColumn != -1)
  532. if (ImGuiTableColumn* next_column = &table->Columns[column->NextActiveColumn])
  533. if (next_column->Flags & ImGuiTableColumnFlags_WidthFixed)
  534. column->Flags |= (next_column->Flags & ImGuiTableColumnFlags_NoDirectResize_);
  535. }
  536. // [Resize Rule 1] The right-most active column is not resizable if there is at least one Stretch column (see comments in TableResizeColumn().)
  537. if (column->NextActiveColumn == -1 && table->LeftMostStretchedColumnDisplayOrder != -1)
  538. column->Flags |= ImGuiTableColumnFlags_NoDirectResize_;
  539. if (!(column->Flags & ImGuiTableColumnFlags_NoResize))
  540. count_resizable++;
  541. // Assign final width, record width in case we will need to shrink
  542. column->WidthGiven = ImFloor(ImMax(column->WidthRequested, min_column_width));
  543. table->ColumnsTotalWidth += column->WidthGiven;
  544. }
  545. #if 0
  546. const float width_excess = table->ColumnsTotalWidth - work_rect.GetWidth();
  547. if ((table->Flags & ImGuiTableFlags_SizingPolicyStretchX) && width_excess > 0.0f)
  548. {
  549. // Shrink widths when the total does not fit
  550. // FIXME-TABLE: This is working but confuses/conflicts with manual resizing.
  551. // FIXME-TABLE: Policy to shrink down below below ideal/requested width if there's no room?
  552. g.ShrinkWidthBuffer.resize(table->ColumnsActiveCount);
  553. for (int order_n = 0, active_n = 0; order_n < table->ColumnsCount; order_n++)
  554. {
  555. if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n)))
  556. continue;
  557. const int column_n = table->DisplayOrder[order_n];
  558. g.ShrinkWidthBuffer[active_n].Index = column_n;
  559. g.ShrinkWidthBuffer[active_n].Width = table->Columns[column_n].WidthGiven;
  560. active_n++;
  561. }
  562. ShrinkWidths(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Size, width_excess);
  563. for (int n = 0; n < g.ShrinkWidthBuffer.Size; n++)
  564. table->Columns[g.ShrinkWidthBuffer.Data[n].Index].WidthGiven = ImMax(g.ShrinkWidthBuffer.Data[n].Width, min_column_size);
  565. // FIXME: Need to alter table->ColumnsTotalWidth
  566. }
  567. else
  568. #endif
  569. // Redistribute remainder width due to rounding (remainder width is < 1.0f * number of Stretch column)
  570. // Using right-to-left distribution (more likely to match resizing cursor), could be adjusted depending where the mouse cursor is and/or relative weights.
  571. // FIXME-TABLE: May be simpler to store floating width and floor final positions only
  572. // FIXME-TABLE: Make it optional? User might prefer to preserve pixel perfect same size?
  573. if (width_remaining_for_stretched_columns >= 1.0f)
  574. for (int order_n = table->ColumnsCount - 1; total_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--)
  575. {
  576. if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n)))
  577. continue;
  578. ImGuiTableColumn* column = &table->Columns[table->DisplayOrder[order_n]];
  579. if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch))
  580. continue;
  581. column->WidthRequested += 1.0f;
  582. column->WidthGiven += 1.0f;
  583. width_remaining_for_stretched_columns -= 1.0f;
  584. }
  585. // Setup final position, offset and clipping rectangles
  586. int active_n = 0;
  587. float offset_x = (table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x;
  588. ImRect host_clip_rect = table->InnerClipRect;
  589. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  590. {
  591. const int column_n = table->DisplayOrder[order_n];
  592. ImGuiTableColumn* column = &table->Columns[column_n];
  593. if (table->FreezeColumnsCount > 0 && table->FreezeColumnsCount == active_n)
  594. offset_x += work_rect.Min.x - table->OuterRect.Min.x;
  595. if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n)))
  596. {
  597. // Hidden column: clear a few fields and we are done with it for the remainder of the function.
  598. // We set a zero-width clip rect however we pay attention to set Min.y/Max.y properly to not interfere with the clipper.
  599. column->MinX = column->MaxX = offset_x;
  600. column->StartXRows = column->StartXHeaders = offset_x;
  601. column->WidthGiven = 0.0f;
  602. column->ClipRect.Min.x = offset_x;
  603. column->ClipRect.Min.y = work_rect.Min.y;
  604. column->ClipRect.Max.x = offset_x;
  605. column->ClipRect.Max.y = FLT_MAX;
  606. column->ClipRect.ClipWithFull(host_clip_rect);
  607. column->IsClipped = true;
  608. continue;
  609. }
  610. // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make sure they are all visible.
  611. // Because of this we also know that all of the columns will always fit in table->WorkRect and therefore in table->InnerRect (because ScrollX is off)
  612. if (!(table->Flags & ImGuiTableFlags_ScrollX))
  613. {
  614. float max_x = table->WorkRect.Max.x - (table->ColumnsActiveCount - (column->IndexWithinActiveSet + 1)) * min_column_width;
  615. if (offset_x + column->WidthGiven > max_x)
  616. column->WidthGiven = ImMax(max_x - offset_x, min_column_width);
  617. }
  618. column->MinX = offset_x;
  619. column->MaxX = column->MinX + column->WidthGiven;
  620. //// A one pixel padding on the right side makes clipping more noticeable and contents look less cramped.
  621. column->ClipRect.Min.x = column->MinX;
  622. column->ClipRect.Min.y = work_rect.Min.y;
  623. column->ClipRect.Max.x = column->MaxX;// -1.0f;
  624. column->ClipRect.Max.y = FLT_MAX;
  625. column->ClipRect.ClipWithFull(host_clip_rect);
  626. column->IsClipped = (column->ClipRect.Max.x <= column->ClipRect.Min.x) && (column->AutoFitQueue & 1) == 0 && (column->CannotSkipItemsQueue & 1) == 0;
  627. if (column->IsClipped)
  628. {
  629. // Columns with the _WidthAlwaysAutoResize sizing policy will never be updated then.
  630. table->VisibleMaskByIndex &= ~((ImU64)1 << column_n);
  631. }
  632. else
  633. {
  634. // Starting cursor position
  635. column->StartXRows = column->StartXHeaders = column->MinX + table->CellPaddingX1;
  636. // Alignment
  637. // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in many cases.
  638. // (To be able to honor this we might be able to store a log of cells width, per row, for visible rows, but nav/programmatic scroll would have visible artifacts.)
  639. //if (column->Flags & ImGuiTableColumnFlags_AlignRight)
  640. // column->StartXRows = ImMax(column->StartXRows, column->MaxX - column->WidthContent[0]);
  641. //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter)
  642. // column->StartXRows = ImLerp(column->StartXRows, ImMax(column->StartXRows, column->MaxX - column->WidthContent[0]), 0.5f);
  643. // Reset content width variables
  644. const float initial_max_pos_x = column->MinX + table->CellPaddingX1;
  645. column->ContentMaxPosRowsFrozen = column->ContentMaxPosRowsUnfrozen = initial_max_pos_x;
  646. column->ContentMaxPosHeadersUsed = column->ContentMaxPosHeadersDesired = initial_max_pos_x;
  647. }
  648. // Don't decrement auto-fit counters until container window got a chance to submit its items
  649. if (table->BackupSkipItems == false)
  650. {
  651. column->AutoFitQueue >>= 1;
  652. column->CannotSkipItemsQueue >>= 1;
  653. }
  654. if (active_n < table->FreezeColumnsCount)
  655. host_clip_rect.Min.x = ImMax(host_clip_rect.Min.x, column->MaxX + 2.0f);
  656. offset_x += column->WidthGiven + table->CellSpacingX;
  657. active_n++;
  658. }
  659. // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either because of using _WidthAlwaysAutoResize/_WidthStretch)
  660. // This will hide the resizing option from the context menu.
  661. if (count_resizable == 0 && (table->Flags & ImGuiTableFlags_Resizable))
  662. table->Flags &= ~ImGuiTableFlags_Resizable;
  663. // Allocate draw channels
  664. TableUpdateDrawChannels(table);
  665. // Borders
  666. if (table->Flags & ImGuiTableFlags_Resizable)
  667. TableUpdateBorders(table);
  668. // Reset fields after we used them in TableSetupResize()
  669. table->LastFirstRowHeight = 0.0f;
  670. table->IsLayoutLocked = true;
  671. table->IsUsingHeaders = false;
  672. // Context menu
  673. if (table->IsContextPopupOpen && table->InstanceNo == table->InstanceInteracted)
  674. {
  675. if (BeginPopup("##TableContextMenu"))
  676. {
  677. TableDrawContextMenu(table, table->ContextPopupColumn);
  678. EndPopup();
  679. }
  680. else
  681. {
  682. table->IsContextPopupOpen = false;
  683. }
  684. }
  685. }
  686. // Process interaction on resizing borders. Actual size change will be applied in EndTable()
  687. // - Set table->HoveredColumnBorder with a short delay/timer to reduce feedback noise
  688. // - Submit ahead of table contents and header, use ImGuiButtonFlags_AllowItemOverlap to prioritize widgets overlapping the same area.
  689. void ImGui::TableUpdateBorders(ImGuiTable* table)
  690. {
  691. ImGuiContext& g = *GImGui;
  692. IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable);
  693. // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and use
  694. // the final height from last frame. Because this is only affecting _interaction_ with columns, it is not really problematic.
  695. // (whereas the actual visual will be displayed in EndTable() and using the current frame height)
  696. // Actual columns highlight/render will be performed in EndTable() and not be affected.
  697. const bool borders_full_height = (table->IsUsingHeaders == false) || (table->Flags & ImGuiTableFlags_BordersFullHeight);
  698. const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS;
  699. const float hit_y1 = table->OuterRect.Min.y;
  700. const float hit_y2_full = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight);
  701. const float hit_y2 = borders_full_height ? hit_y2_full : (hit_y1 + table->LastFirstRowHeight);
  702. const float mouse_x_hover_body = (g.IO.MousePos.y >= hit_y1 && g.IO.MousePos.y < hit_y2_full) ? g.IO.MousePos.x : FLT_MAX;
  703. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  704. {
  705. if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n)))
  706. continue;
  707. const int column_n = table->DisplayOrder[order_n];
  708. ImGuiTableColumn* column = &table->Columns[column_n];
  709. // Detect hovered column:
  710. // - we perform an unusually low-level check here.. not using IsMouseHoveringRect() to avoid touch padding.
  711. // - we don't care about the full set of IsItemHovered() feature either.
  712. if (mouse_x_hover_body >= column->MinX && mouse_x_hover_body < column->MaxX)
  713. table->HoveredColumnBody = (ImS8)column_n;
  714. if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_))
  715. continue;
  716. ImGuiID column_id = table->ID + (table->InstanceNo * table->ColumnsCount) + column_n;
  717. ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, hit_y2);
  718. //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100));
  719. KeepAliveID(column_id);
  720. bool hovered = false, held = false;
  721. bool pressed = ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick);
  722. if (pressed && IsMouseDoubleClicked(0) && !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
  723. {
  724. // FIXME-TABLE: Double-clicking on column edge could auto-fit weighted column?
  725. TableSetColumnAutofit(table, column_n);
  726. ClearActiveID();
  727. held = hovered = false;
  728. }
  729. if (held)
  730. {
  731. table->ResizedColumn = (ImS8)column_n;
  732. table->InstanceInteracted = table->InstanceNo;
  733. }
  734. if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held)
  735. {
  736. table->HoveredColumnBorder = (ImS8)column_n;
  737. SetMouseCursor(ImGuiMouseCursor_ResizeEW);
  738. }
  739. }
  740. }
  741. void ImGui::EndTable()
  742. {
  743. ImGuiContext& g = *GImGui;
  744. ImGuiTable* table = g.CurrentTable;
  745. IM_ASSERT(table != NULL);
  746. const ImGuiTableFlags flags = table->Flags;
  747. ImGuiWindow* inner_window = table->InnerWindow;
  748. ImGuiWindow* outer_window = table->OuterWindow;
  749. IM_ASSERT(inner_window == g.CurrentWindow);
  750. IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow);
  751. if (table->IsInsideRow)
  752. TableEndRow(table);
  753. // Finalize table height
  754. inner_window->SkipItems = table->BackupSkipItems;
  755. inner_window->DC.CursorMaxPos = table->BackupCursorMaxPos;
  756. if (inner_window != outer_window)
  757. {
  758. table->OuterRect.Max.y = ImMax(table->OuterRect.Max.y, inner_window->Pos.y + inner_window->Size.y);
  759. inner_window->DC.CursorMaxPos.y = table->RowPosY2;
  760. }
  761. else if (!(flags & ImGuiTableFlags_NoHostExtendY))
  762. {
  763. table->OuterRect.Max.y = ImMax(table->OuterRect.Max.y, inner_window->DC.CursorPos.y);
  764. inner_window->DC.CursorMaxPos.y = table->RowPosY2;
  765. }
  766. table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y);
  767. table->LastOuterHeight = table->OuterRect.GetHeight();
  768. // Store content width reference for each column
  769. float max_pos_x = inner_window->DC.CursorMaxPos.x;
  770. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  771. {
  772. ImGuiTableColumn* column = &table->Columns[column_n];
  773. // Store content width (for both Headers and Rows)
  774. //float ref_x = column->MinX;
  775. float ref_x_rows = column->StartXRows - table->CellPaddingX1;
  776. float ref_x_headers = column->StartXHeaders - table->CellPaddingX1;
  777. column->ContentWidthRowsFrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsFrozen - ref_x_rows);
  778. column->ContentWidthRowsUnfrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosRowsUnfrozen - ref_x_rows);
  779. column->ContentWidthHeadersUsed = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersUsed - ref_x_headers);
  780. column->ContentWidthHeadersDesired = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersDesired - ref_x_headers);
  781. if (table->ActiveMaskByIndex & ((ImU64)1 << column_n))
  782. max_pos_x = ImMax(max_pos_x, column->MaxX);
  783. }
  784. // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge.
  785. inner_window->DC.CursorMaxPos.x = max_pos_x + 1;
  786. if (!(flags & ImGuiTableFlags_NoClipX))
  787. inner_window->DrawList->PopClipRect();
  788. inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back();
  789. // Draw borders
  790. if ((flags & ImGuiTableFlags_Borders) != 0)
  791. TableDrawBorders(table);
  792. // Flatten channels and merge draw calls
  793. table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 0);
  794. TableDrawMergeChannels(table);
  795. // When releasing a column being resized, scroll to keep the resulting column in sight
  796. const float min_column_width = TableGetMinColumnWidth();
  797. if (!(table->Flags & ImGuiTableFlags_ScrollX) && inner_window != outer_window)
  798. {
  799. inner_window->Scroll.x = 0.0f;
  800. }
  801. else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX)
  802. {
  803. ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn];
  804. if (column->MaxX < table->InnerClipRect.Min.x)
  805. SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x - min_column_width, 1.0f);
  806. else if (column->MaxX > table->InnerClipRect.Max.x)
  807. SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x + min_column_width, 1.0f);
  808. }
  809. // Apply resizing/dragging at the end of the frame
  810. if (table->ResizedColumn != -1)
  811. {
  812. ImGuiTableColumn* column = &table->Columns[table->ResizedColumn];
  813. const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + TABLE_RESIZE_SEPARATOR_HALF_THICKNESS);
  814. const float new_width = ImFloor(new_x2 - column->MinX);
  815. table->ResizedColumnNextWidth = new_width;
  816. }
  817. // Layout in outer window
  818. inner_window->WorkRect = table->BackupWorkRect;
  819. inner_window->SkipItems = table->BackupSkipItems;
  820. outer_window->DC.CursorPos = table->OuterRect.Min;
  821. outer_window->DC.ColumnsOffset.x = 0.0f;
  822. if (inner_window != outer_window)
  823. {
  824. // Override EndChild's ItemSize with our own to enable auto-resize on the X axis when possible
  825. float backup_outer_cursor_pos_x = outer_window->DC.CursorPos.x;
  826. EndChild();
  827. outer_window->DC.CursorMaxPos.x = backup_outer_cursor_pos_x + table->ColumnsTotalWidth + 1.0f + inner_window->ScrollbarSizes.x;
  828. }
  829. else
  830. {
  831. PopID();
  832. ImVec2 item_size = table->OuterRect.GetSize();
  833. item_size.x = table->ColumnsTotalWidth;
  834. ItemSize(item_size);
  835. }
  836. // Save settings
  837. if (table->IsSettingsDirty)
  838. TableSaveSettings(table);
  839. // Clear or restore current table, if any
  840. IM_ASSERT(g.CurrentWindow == outer_window);
  841. IM_ASSERT(g.CurrentTable == table);
  842. outer_window->DC.CurrentTable = NULL;
  843. g.CurrentTableStack.pop_back();
  844. g.CurrentTable = g.CurrentTableStack.Size ? g.Tables.GetByIndex(g.CurrentTableStack.back().Index) : NULL;
  845. }
  846. void ImGui::TableDrawBorders(ImGuiTable* table)
  847. {
  848. ImGuiWindow* inner_window = table->InnerWindow;
  849. ImGuiWindow* outer_window = table->OuterWindow;
  850. table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 0);
  851. if (inner_window->Hidden || !table->HostClipRect.Overlaps(table->InnerClipRect))
  852. return;
  853. // Draw inner border and resizing feedback
  854. const float draw_y1 = table->OuterRect.Min.y;
  855. float draw_y2_base = (table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight;
  856. float draw_y2_full = table->OuterRect.Max.y;
  857. ImU32 border_base_col;
  858. if (!table->IsUsingHeaders || (table->Flags & ImGuiTableFlags_BordersFullHeight))
  859. {
  860. draw_y2_base = draw_y2_full;
  861. border_base_col = table->BorderInnerColor;
  862. }
  863. else
  864. {
  865. border_base_col = table->BorderOuterColor;
  866. }
  867. if (table->Flags & ImGuiTableFlags_BordersV)
  868. {
  869. const bool draw_left_most_border = (table->Flags & ImGuiTableFlags_BordersOuter) == 0;
  870. if (draw_left_most_border)
  871. inner_window->DrawList->AddLine(ImVec2(table->OuterRect.Min.x, draw_y1), ImVec2(table->OuterRect.Min.x, draw_y2_base), border_base_col, 1.0f);
  872. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  873. {
  874. if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n)))
  875. continue;
  876. const int column_n = table->DisplayOrder[order_n];
  877. ImGuiTableColumn* column = &table->Columns[column_n];
  878. const bool is_hovered = (table->HoveredColumnBorder == column_n);
  879. const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceNo);
  880. const bool draw_right_border = (column->MaxX <= table->InnerClipRect.Max.x) || (is_resized || is_hovered);
  881. if (draw_right_border && column->MaxX > column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size..
  882. {
  883. // Draw in outer window so right-most column won't be clipped
  884. // Always draw full height border when:
  885. // - not using headers
  886. // - user specify ImGuiTableFlags_BordersFullHeight
  887. // - being interacted with
  888. // - on the delimitation of frozen column scrolling
  889. const ImU32 col = is_resized ? GetColorU32(ImGuiCol_SeparatorActive) : is_hovered ? GetColorU32(ImGuiCol_SeparatorHovered) : border_base_col;
  890. float draw_y2 = draw_y2_base;
  891. if (is_hovered || is_resized || (table->FreezeColumnsCount != -1 && table->FreezeColumnsCount == order_n + 1))
  892. draw_y2 = draw_y2_full;
  893. inner_window->DrawList->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, 1.0f);
  894. }
  895. }
  896. }
  897. // Draw outer border
  898. if (table->Flags & ImGuiTableFlags_BordersOuter)
  899. {
  900. // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call
  901. // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their parent.
  902. // In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part of it in inner window,
  903. // and the part that's over scrollbars in the outer window..)
  904. // Either solution currently won't allow us to use a larger border size: the border would clipped.
  905. ImRect outer_border = table->OuterRect;
  906. if (inner_window != outer_window)
  907. outer_border.Expand(1.0f);
  908. outer_window->DrawList->AddRect(outer_border.Min, outer_border.Max, table->BorderOuterColor); // IM_COL32(255, 0, 0, 255));
  909. }
  910. else if (table->Flags & ImGuiTableFlags_BordersH)
  911. {
  912. // Draw bottom-most border
  913. const float border_y = table->RowPosY2;
  914. if (border_y >= table->BackgroundClipRect.Min.y && border_y < table->BackgroundClipRect.Max.y)
  915. inner_window->DrawList->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderOuterColor);
  916. }
  917. }
  918. static void TableUpdateColumnsWeightFromWidth(ImGuiTable* table)
  919. {
  920. IM_ASSERT(table->LeftMostStretchedColumnDisplayOrder != -1);
  921. // Measure existing quantity
  922. float visible_weight = 0.0f;
  923. float visible_width = 0.0f;
  924. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  925. {
  926. ImGuiTableColumn* column = &table->Columns[column_n];
  927. if (!column->IsActive || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
  928. continue;
  929. visible_weight += column->ResizeWeight;
  930. visible_width += column->WidthRequested;
  931. }
  932. IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f);
  933. // Apply new weights
  934. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  935. {
  936. ImGuiTableColumn* column = &table->Columns[column_n];
  937. if (!column->IsActive || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
  938. continue;
  939. column->ResizeWeight = (column->WidthRequested + 0.0f) / visible_width;
  940. }
  941. }
  942. void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, float column_0_width)
  943. {
  944. // Constraints
  945. float min_width = TableGetMinColumnWidth();
  946. float max_width_0 = FLT_MAX;
  947. if (!(table->Flags & ImGuiTableFlags_ScrollX))
  948. max_width_0 = (table->WorkRect.Max.x - column_0->MinX) - (table->ColumnsActiveCount - (column_0->IndexWithinActiveSet + 1)) * min_width;
  949. column_0_width = ImClamp(column_0_width, min_width, max_width_0);
  950. // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded)
  951. if (column_0->WidthGiven == column_0_width || column_0->WidthRequested == column_0_width)
  952. return;
  953. ImGuiTableColumn* column_1 = (column_0->NextActiveColumn != -1) ? &table->Columns[column_0->NextActiveColumn] : NULL;
  954. // In this surprisingly not simple because of how we support mixing Fixed and Stretch columns.
  955. // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1.
  956. // FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user.
  957. // Scenarios:
  958. // - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset.
  959. // - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered.
  960. // - 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 Weighted column will always be minimal size.
  961. // - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
  962. // - W1 W2 W3 resize from W1| or W2| --> FIXME
  963. // - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
  964. // - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1)
  965. // - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1)
  966. // - W1 W2 F3 resize from W1| or W2| --> ok
  967. // - W1 F2 W3 resize from W1| or F2| --> FIXME
  968. // - F1 W2 F3 resize from W2| --> ok
  969. // - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move. (forwarded by Resize Rule 2)
  970. // - W1 F2 F3 resize from F2| --> FIXME should resize F2, F3 and not have effect on W1 (Stretch columns are _before_ the Fixed column).
  971. // Rules:
  972. // - [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout().
  973. // - [Resize Rule 2] Resizing from right-side of a Stretch column before a fixed column froward sizing to left-side of fixed column.
  974. // - [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to ensure that our left border won't move.
  975. if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed)
  976. {
  977. // [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to
  978. // ensure that our left border won't move, which we can do by making sure column_a/column_b resizes cancels each others.
  979. if (column_1 && (column_1->Flags & ImGuiTableColumnFlags_WidthFixed))
  980. if (table->LeftMostStretchedColumnDisplayOrder != -1 && table->LeftMostStretchedColumnDisplayOrder < column_0->IndexDisplayOrder)
  981. {
  982. // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b)
  983. float column_1_width = ImMax(column_1->WidthRequested - (column_0_width - column_0->WidthRequested), min_width);
  984. column_0_width = column_0->WidthRequested + column_1->WidthRequested - column_1_width;
  985. column_1->WidthRequested = column_1_width;
  986. }
  987. // Apply
  988. //IMGUI_DEBUG_LOG("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthRequested, column_0_width);
  989. column_0->WidthRequested = column_0_width;
  990. }
  991. else if (column_0->Flags & ImGuiTableColumnFlags_WidthStretch)
  992. {
  993. // [Resize Rule 2]
  994. if (column_1 && (column_1->Flags & ImGuiTableColumnFlags_WidthFixed))
  995. {
  996. float off = (column_0->WidthGiven - column_0_width);
  997. float column_1_width = column_1->WidthGiven + off;
  998. column_1->WidthRequested = ImMax(min_width, column_1_width);
  999. return;
  1000. }
  1001. // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b)
  1002. float column_1_width = ImMax(column_1->WidthRequested - (column_0_width - column_0->WidthRequested), min_width);
  1003. column_0_width = column_0->WidthRequested + column_1->WidthRequested - column_1_width;
  1004. column_1->WidthRequested = column_1_width;
  1005. column_0->WidthRequested = column_0_width;
  1006. TableUpdateColumnsWeightFromWidth(table);
  1007. }
  1008. table->IsSettingsDirty = true;
  1009. }
  1010. // Columns where the contents didn't stray off their local clip rectangle can be merged into a same draw command.
  1011. // To achieve this we merge their clip rect and make them contiguous in the channel list so they can be merged.
  1012. // So here we'll reorder the draw cmd which can be merged, by arranging them into a maximum of 4 distinct groups:
  1013. //
  1014. // 1 group: 2 groups: 2 groups: 4 groups:
  1015. // [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze
  1016. // [ .. ] or no scroll [ 1. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll
  1017. //
  1018. // Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled).
  1019. // When the contents of a column didn't stray off its limit, we move its channels into the corresponding group
  1020. // based on its position (within frozen rows/columns set or not).
  1021. // At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect, and they will be merged by the DrawSplitter.Merge() call.
  1022. //
  1023. // Column channels will not be merged into one of the 1-4 groups in the following cases:
  1024. // - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value).
  1025. // Direct ImDrawList calls won't be noticed so if you use them make sure the ImGui:: bounds matches, by e.g. calling SetCursorScreenPos().
  1026. // - The channel uses more than one draw command itself (we drop all our merging stuff here.. we could do better but it's going to be rare)
  1027. //
  1028. // This function is particularly tricky to understand.. take a breath.
  1029. void ImGui::TableDrawMergeChannels(ImGuiTable* table)
  1030. {
  1031. ImGuiContext& g = *GImGui;
  1032. ImDrawListSplitter* splitter = &table->DrawSplitter;
  1033. const bool is_frozen_v = (table->FreezeRowsCount > 0);
  1034. const bool is_frozen_h = (table->FreezeColumnsCount > 0);
  1035. int merge_set_mask = 0;
  1036. int merge_set_channels_count[4] = { 0 };
  1037. ImU64 merge_set_channels_mask[4] = { 0 };
  1038. ImRect merge_set_clip_rect[4];
  1039. for (int n = 0; n < IM_ARRAYSIZE(merge_set_clip_rect); n++)
  1040. merge_set_clip_rect[n] = ImVec4(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
  1041. bool merge_set_all_fit_within_inner_rect = (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0;
  1042. // 1. Scan channels and take note of those who can be merged
  1043. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  1044. {
  1045. if (!(table->ActiveMaskByDisplayOrder & ((ImU64)1 << order_n)))
  1046. continue;
  1047. const int column_n = table->DisplayOrder[order_n];
  1048. ImGuiTableColumn* column = &table->Columns[column_n];
  1049. const int merge_set_sub_count = is_frozen_v ? 2 : 1;
  1050. for (int merge_set_sub_n = 0; merge_set_sub_n < merge_set_sub_count; merge_set_sub_n++)
  1051. {
  1052. const int channel_no = (merge_set_sub_n == 0) ? column->DrawChannelRowsBeforeFreeze : column->DrawChannelRowsAfterFreeze;
  1053. // Don't attempt to merge if there are multiple calls within the column
  1054. ImDrawChannel* src_channel = &splitter->_Channels[channel_no];
  1055. if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0)
  1056. src_channel->_CmdBuffer.pop_back();
  1057. if (src_channel->_CmdBuffer.Size != 1)
  1058. continue;
  1059. // Find out the width of this merge set and check if it will fit in our column.
  1060. float width_contents;
  1061. if (merge_set_sub_count == 1) // No row freeze (same as testing !is_frozen_v)
  1062. width_contents = ImMax(column->ContentWidthRowsUnfrozen, column->ContentWidthHeadersUsed);
  1063. else if (merge_set_sub_n == 0) // Row freeze: use width before freeze
  1064. width_contents = ImMax(column->ContentWidthRowsFrozen, column->ContentWidthHeadersUsed);
  1065. else // Row freeze: use width after freeze
  1066. width_contents = column->ContentWidthRowsUnfrozen;
  1067. if (width_contents > column->WidthGiven && !(column->Flags & ImGuiTableColumnFlags_NoClipX))
  1068. continue;
  1069. const int dst_merge_set_n = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_set_sub_n : 1);
  1070. IM_ASSERT(merge_set_channels_count[dst_merge_set_n] < (int)sizeof(merge_set_channels_mask[dst_merge_set_n]) * 8);
  1071. merge_set_mask |= (1 << dst_merge_set_n);
  1072. merge_set_channels_mask[dst_merge_set_n] |= (ImU64)1 << channel_no;
  1073. merge_set_channels_count[dst_merge_set_n]++;
  1074. merge_set_clip_rect[dst_merge_set_n].Add(src_channel->_CmdBuffer[0].ClipRect);
  1075. // If we end with a single set and hosted by the outer window, we'll attempt to merge our draw command with
  1076. // the existing outer window command. But we can only do so if our columns all fit within the expected clip rect,
  1077. // otherwise clipping will be incorrect when ScrollX is disabled.
  1078. // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column don't fit within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect
  1079. // 2019/10/22: (1) This is breaking table_2_draw_calls but I cannot seem to repro what it is attempting to fix...
  1080. // cf git fce2e8dc "Fixed issue with clipping when outerwindow==innerwindow / support ScrollH without ScrollV."
  1081. // 2019/10/22: (2) Clamping code in TableUpdateLayout() seemingly made this not necessary...
  1082. #if 0
  1083. if (column->MinX < table->InnerClipRect.Min.x || column->MaxX > table->InnerClipRect.Max.x)
  1084. merge_set_all_fit_within_inner_rect = false;
  1085. #endif
  1086. }
  1087. // Invalidate current draw channel (we don't clear DrawChannelBeforeRowFreeze/DrawChannelAfterRowFreeze solely to facilitate debugging)
  1088. column->DrawChannelCurrent = -1;
  1089. }
  1090. // 2. Rewrite channel list in our preferred order
  1091. if (merge_set_mask != 0)
  1092. {
  1093. // Use shared temporary storage so the allocation gets amortized
  1094. g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - 1);
  1095. ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data;
  1096. ImU64 remaining_mask = ((splitter->_Count < 64) ? ((ImU64)1 << splitter->_Count) - 1 : ~(ImU64)0) & ~1;
  1097. const bool may_extend_clip_rect_to_host_rect = ImIsPowerOfTwo(merge_set_mask);
  1098. for (int merge_set_n = 0; merge_set_n < 4; merge_set_n++)
  1099. if (merge_set_channels_count[merge_set_n])
  1100. {
  1101. ImU64 merge_channels_mask = merge_set_channels_mask[merge_set_n];
  1102. ImRect merge_clip_rect = merge_set_clip_rect[merge_set_n];
  1103. if (may_extend_clip_rect_to_host_rect)
  1104. {
  1105. //GetOverlayDrawList()->AddRect(table->HostClipRect.Min, table->HostClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 3.0f);
  1106. //GetOverlayDrawList()->AddRect(table->InnerClipRect.Min, table->InnerClipRect.Max, IM_COL32(0, 255, 0, 200), 0.0f, ~0, 1.0f);
  1107. //GetOverlayDrawList()->AddRect(merge_clip_rect.Min, merge_clip_rect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 2.0f);
  1108. merge_clip_rect.Add(merge_set_all_fit_within_inner_rect ? table->HostClipRect : table->InnerClipRect);
  1109. //GetOverlayDrawList()->AddRect(merge_clip_rect.Min, merge_clip_rect.Max, IM_COL32(0, 255, 0, 200));
  1110. }
  1111. remaining_mask &= ~merge_channels_mask;
  1112. for (int n = 0; n < splitter->_Count && merge_channels_mask != 0; n++)
  1113. {
  1114. // Copy + overwrite new clip rect
  1115. const ImU64 n_mask = (ImU64)1 << n;
  1116. if ((merge_channels_mask & n_mask) == 0)
  1117. continue;
  1118. ImDrawChannel* channel = &splitter->_Channels[n];
  1119. IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect)));
  1120. channel->_CmdBuffer[0].ClipRect = *(ImVec4*)&merge_clip_rect;
  1121. memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));
  1122. merge_channels_mask &= ~n_mask;
  1123. }
  1124. }
  1125. // Append channels that we didn't reorder at the end of the list
  1126. for (int n = 0; n < splitter->_Count && remaining_mask != 0; n++)
  1127. {
  1128. const ImU64 n_mask = (ImU64)1 << n;
  1129. if ((remaining_mask & n_mask) == 0)
  1130. continue;
  1131. ImDrawChannel* channel = &splitter->_Channels[n];
  1132. memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));
  1133. remaining_mask &= ~n_mask;
  1134. }
  1135. IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size);
  1136. memcpy(splitter->_Channels.Data + 1, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - 1) * sizeof(ImDrawChannel));
  1137. }
  1138. // 3. Actually merge (channels using the same clip rect will be contiguous and naturally merged)
  1139. splitter->Merge(table->InnerWindow->DrawList);
  1140. }
  1141. // We use a default parameter of 'init_width_or_weight == -1'
  1142. // ImGuiTableColumnFlags_WidthFixed, width <= 0 --> init width == auto
  1143. // ImGuiTableColumnFlags_WidthFixed, width > 0 --> init width == manual
  1144. // ImGuiTableColumnFlags_WidthStretch, weight < 0 --> init weight == 1.0f
  1145. // ImGuiTableColumnFlags_WidthStretch, weight >= 0 --> init weight == custom
  1146. // Use a different API?
  1147. void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id)
  1148. {
  1149. ImGuiContext& g = *GImGui;
  1150. ImGuiTable* table = g.CurrentTable;
  1151. IM_ASSERT(table != NULL && "Can only call TableSetupColumn() after BeginTable()!");
  1152. IM_ASSERT(!table->IsLayoutLocked && "Can only call TableSetupColumn() before first row!");
  1153. IM_ASSERT(table->DeclColumnsCount >= 0 && table->DeclColumnsCount < table->ColumnsCount && "Called TableSetupColumn() too many times!");
  1154. ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount];
  1155. table->DeclColumnsCount++;
  1156. // When passing a width automatically enforce WidthFixed policy (vs TableFixColumnFlags would default to WidthAlwaysAutoResize)
  1157. // (we write down to FlagsIn which is a little misleading, another solution would be to pass init_width_or_weight to TableFixColumnFlags)
  1158. if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0)
  1159. if ((table->Flags & ImGuiTableFlags_SizingPolicyFixedX) && (init_width_or_weight > 0.0f))
  1160. flags |= ImGuiTableColumnFlags_WidthFixed;
  1161. column->UserID = user_id;
  1162. column->FlagsIn = flags;
  1163. column->Flags = TableFixColumnFlags(table, column->FlagsIn);
  1164. flags = column->Flags;
  1165. // Initialize defaults
  1166. if (table->IsFirstFrame && !table->IsSettingsLoaded)
  1167. {
  1168. // Init width or weight
  1169. // Disable auto-fit if a default fixed width has been specified
  1170. if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f)
  1171. {
  1172. column->WidthRequested = init_width_or_weight;
  1173. column->AutoFitQueue = 0x00;
  1174. }
  1175. if (flags & ImGuiTableColumnFlags_WidthStretch)
  1176. {
  1177. IM_ASSERT(init_width_or_weight < 0.0f || init_width_or_weight > 0.0f);
  1178. column->ResizeWeight = (init_width_or_weight < 0.0f ? 1.0f : init_width_or_weight);
  1179. }
  1180. else
  1181. {
  1182. column->ResizeWeight = 1.0f;
  1183. }
  1184. // Init default visibility/sort state
  1185. if (flags & ImGuiTableColumnFlags_DefaultHide)
  1186. column->IsActive = column->NextIsActive = false;
  1187. if (flags & ImGuiTableColumnFlags_DefaultSort)
  1188. column->SortOrder = 0; // Multiple columns using _DefaultSort will be reordered when building the sort specs.
  1189. }
  1190. // Store name (append with zero-terminator in contiguous buffer)
  1191. IM_ASSERT(column->NameOffset == -1);
  1192. if (label != NULL)
  1193. {
  1194. column->NameOffset = (ImS16)table->ColumnsNames.size();
  1195. table->ColumnsNames.append(label, label + strlen(label) + 1);
  1196. }
  1197. }
  1198. // Starts into the first cell of a new row
  1199. void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float min_row_height)
  1200. {
  1201. ImGuiContext& g = *GImGui;
  1202. ImGuiTable* table = g.CurrentTable;
  1203. if (table->CurrentRow == -1)
  1204. TableUpdateLayout(table);
  1205. else if (table->IsInsideRow)
  1206. TableEndRow(table);
  1207. table->LastRowFlags = table->RowFlags;
  1208. table->RowFlags = row_flags;
  1209. TableBeginRow(table);
  1210. // We honor min_height requested by user, but cannot guarantee per-row maximum height as that would essentially require a unique clipping rectangle per-cell.
  1211. table->RowPosY2 += min_row_height;
  1212. TableBeginCell(table, 0);
  1213. }
  1214. // [Internal]
  1215. void ImGui::TableBeginRow(ImGuiTable* table)
  1216. {
  1217. ImGuiWindow* window = table->InnerWindow;
  1218. IM_ASSERT(!table->IsInsideRow);
  1219. // New row
  1220. table->CurrentRow++;
  1221. table->CurrentColumn = -1;
  1222. table->RowBgColor = IM_COL32_DISABLE;
  1223. table->IsInsideRow = true;
  1224. // Begin frozen rows
  1225. float next_y1 = table->RowPosY2;
  1226. if (table->CurrentRow == 0 && table->FreezeRowsCount > 0)
  1227. next_y1 = window->DC.CursorPos.y = table->OuterRect.Min.y;
  1228. table->RowPosY1 = table->RowPosY2 = next_y1;
  1229. table->RowTextBaseline = 0.0f;
  1230. window->DC.CursorMaxPos.y = next_y1;
  1231. // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging.
  1232. if (table->RowFlags & ImGuiTableRowFlags_Headers)
  1233. {
  1234. table->RowBgColor = GetColorU32(ImGuiCol_TableHeaderBg);
  1235. if (table->CurrentRow == 0)
  1236. table->IsUsingHeaders = true;
  1237. }
  1238. }
  1239. // [Internal]
  1240. void ImGui::TableEndRow(ImGuiTable* table)
  1241. {
  1242. ImGuiContext& g = *GImGui;
  1243. ImGuiWindow* window = g.CurrentWindow;
  1244. IM_ASSERT(window == table->InnerWindow);
  1245. IM_ASSERT(table->IsInsideRow);
  1246. TableEndCell(table);
  1247. table->RowPosY2 += table->CellPaddingY;
  1248. // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation.
  1249. // However it is likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding.
  1250. window->DC.CursorPos.y = table->RowPosY2;
  1251. // Row background fill
  1252. const float bg_y1 = table->RowPosY1;
  1253. const float bg_y2 = table->RowPosY2;
  1254. if (table->CurrentRow == 0)
  1255. table->LastFirstRowHeight = bg_y2 - bg_y1;
  1256. if (table->CurrentRow >= 0 && bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y)
  1257. {
  1258. // Decide of background color for the row
  1259. ImU32 bg_col = 0;
  1260. if (table->RowBgColor != IM_COL32_DISABLE)
  1261. bg_col = table->RowBgColor;
  1262. else if (table->Flags & ImGuiTableFlags_RowBg)
  1263. bg_col = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg);
  1264. // Decide of separating border color
  1265. ImU32 border_col = 0;
  1266. if (table->CurrentRow != 0 || table->InnerWindow == table->OuterWindow)
  1267. {
  1268. if (table->Flags & ImGuiTableFlags_BordersH)
  1269. {
  1270. if (table->CurrentRow == 0 && table->InnerWindow == table->OuterWindow)
  1271. border_col = table->BorderOuterColor;
  1272. else if (!(table->LastRowFlags & ImGuiTableRowFlags_Headers))
  1273. border_col = table->BorderInnerColor;
  1274. }
  1275. else
  1276. {
  1277. if (table->RowFlags & ImGuiTableRowFlags_Headers)
  1278. border_col = table->BorderOuterColor;
  1279. }
  1280. }
  1281. if (bg_col != 0 || border_col != 0)
  1282. table->DrawSplitter.SetCurrentChannel(window->DrawList, 0);
  1283. // Draw background
  1284. // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle
  1285. if (bg_col)
  1286. {
  1287. ImRect bg_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2);
  1288. bg_rect.ClipWith(table->BackgroundClipRect);
  1289. if (bg_rect.Min.y < bg_rect.Max.y)
  1290. window->DrawList->AddRectFilledMultiColor(bg_rect.Min, bg_rect.Max, bg_col, bg_col, bg_col, bg_col);
  1291. }
  1292. // Draw top border
  1293. const float border_y = bg_y1;
  1294. if (border_col && border_y >= table->BackgroundClipRect.Min.y && border_y < table->BackgroundClipRect.Max.y)
  1295. window->DrawList->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), border_col);
  1296. }
  1297. const bool unfreeze_rows = (table->CurrentRow + 1 == table->FreezeRowsCount && table->FreezeRowsCount > 0);
  1298. // Draw bottom border (always strong)
  1299. const bool draw_separating_border = unfreeze_rows || (table->RowFlags & ImGuiTableRowFlags_Headers);
  1300. if (draw_separating_border)
  1301. if (bg_y2 >= table->BackgroundClipRect.Min.y && bg_y2 < table->BackgroundClipRect.Max.y)
  1302. window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderOuterColor);
  1303. // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle)
  1304. // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and get the new cursor position.
  1305. if (unfreeze_rows)
  1306. {
  1307. IM_ASSERT(table->IsFreezeRowsPassed == false);
  1308. table->IsFreezeRowsPassed = true;
  1309. table->DrawSplitter.SetCurrentChannel(window->DrawList, 0);
  1310. ImRect r;
  1311. r.Min.x = table->InnerClipRect.Min.x;
  1312. r.Min.y = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y);
  1313. r.Max.x = table->InnerClipRect.Max.x;
  1314. r.Max.y = window->InnerClipRect.Max.y;
  1315. table->BackgroundClipRect = r;
  1316. float row_height = table->RowPosY2 - table->RowPosY1;
  1317. table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y;
  1318. table->RowPosY1 = table->RowPosY2 - row_height;
  1319. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1320. {
  1321. ImGuiTableColumn* column = &table->Columns[column_n];
  1322. column->DrawChannelCurrent = column->DrawChannelRowsAfterFreeze;
  1323. column->ClipRect.Min.y = r.Min.y;
  1324. }
  1325. }
  1326. if (!(table->RowFlags & ImGuiTableRowFlags_Headers))
  1327. table->RowBgColorCounter++;
  1328. table->IsInsideRow = false;
  1329. }
  1330. // [Internal] This is called a lot, so we need to be mindful of unnecessary overhead!
  1331. void ImGui::TableBeginCell(ImGuiTable* table, int column_no)
  1332. {
  1333. table->CurrentColumn = column_no;
  1334. ImGuiTableColumn* column = &table->Columns[column_no];
  1335. ImGuiWindow* window = table->InnerWindow;
  1336. const float start_x = (table->RowFlags & ImGuiTableRowFlags_Headers) ? column->StartXHeaders : column->StartXRows;
  1337. window->DC.LastItemId = 0;
  1338. window->DC.CursorPos = ImVec2(start_x, table->RowPosY1 + table->CellPaddingY);
  1339. window->DC.CursorMaxPos.x = window->DC.CursorPos.x;
  1340. window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT // FIXME-TABLE: Recurse
  1341. window->DC.CurrLineTextBaseOffset = table->RowTextBaseline;
  1342. window->WorkRect.Min.y = window->DC.CursorPos.y;
  1343. window->WorkRect.Min.x = column->MinX + table->CellPaddingX1;
  1344. window->WorkRect.Max.x = column->MaxX - table->CellPaddingX2;
  1345. // To allow ImGuiListClipper to function we propagate our row height
  1346. if (!column->IsActive)
  1347. window->DC.CursorPos.y = ImMax(window->DC.CursorPos.y, table->RowPosY2);
  1348. // FIXME-COLUMNS: Setup baseline, preserve across columns (how can we obtain first line baseline tho..)
  1349. // window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y);
  1350. window->SkipItems = column->IsClipped ? true : table->BackupSkipItems;
  1351. if (table->Flags & ImGuiTableFlags_NoClipX)
  1352. {
  1353. table->DrawSplitter.SetCurrentChannel(window->DrawList, 1);
  1354. }
  1355. else
  1356. {
  1357. table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
  1358. //window->ClipRect = column->ClipRect;
  1359. //IM_ASSERT(column->ClipRect.Max.x > column->ClipRect.Min.x && column->ClipRect.Max.y > column->ClipRect.Min.y);
  1360. //window->DrawList->_ClipRectStack.back() = ImVec4(column->ClipRect.Min.x, column->ClipRect.Min.y, column->ClipRect.Max.x, column->ClipRect.Max.y);
  1361. //window->DrawList->UpdateClipRect();
  1362. window->DrawList->PopClipRect();
  1363. window->DrawList->PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false);
  1364. //IMGUI_DEBUG_LOG("%d (%.0f,%.0f)(%.0f,%.0f)\n", column_no, column->ClipRect.Min.x, column->ClipRect.Min.y, column->ClipRect.Max.x, column->ClipRect.Max.y);
  1365. window->ClipRect = window->DrawList->_ClipRectStack.back();
  1366. }
  1367. }
  1368. // [Internal]
  1369. void ImGui::TableEndCell(ImGuiTable* table)
  1370. {
  1371. ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
  1372. ImGuiWindow* window = table->InnerWindow;
  1373. // Report maximum position so we can infer content size per column.
  1374. float* p_max_pos_x;
  1375. if (table->RowFlags & ImGuiTableRowFlags_Headers)
  1376. p_max_pos_x = &column->ContentMaxPosHeadersUsed; // Useful in case user submit contents in header row that is not a TableHeader() call
  1377. else
  1378. p_max_pos_x = table->IsFreezeRowsPassed ? &column->ContentMaxPosRowsUnfrozen : &column->ContentMaxPosRowsFrozen;
  1379. *p_max_pos_x = ImMax(*p_max_pos_x, window->DC.CursorMaxPos.x);
  1380. table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y);
  1381. // Propagate text baseline for the entire row
  1382. // FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one.
  1383. table->RowTextBaseline = ImMax(table->RowTextBaseline, window->DC.PrevLineTextBaseOffset);
  1384. }
  1385. // Append into the next cell
  1386. // FIXME-TABLE: Wrapping to next row should be optional?
  1387. bool ImGui::TableNextCell()
  1388. {
  1389. ImGuiContext& g = *GImGui;
  1390. ImGuiTable* table = g.CurrentTable;
  1391. if (table->CurrentColumn != -1 && table->CurrentColumn + 1 < table->ColumnsCount)
  1392. {
  1393. TableEndCell(table);
  1394. TableBeginCell(table, table->CurrentColumn + 1);
  1395. }
  1396. else
  1397. {
  1398. TableNextRow();
  1399. }
  1400. int column_n = table->CurrentColumn;
  1401. return (table->VisibleMaskByIndex & ((ImU64)1 << column_n)) != 0;
  1402. }
  1403. const char* ImGui::TableGetColumnName(int column_n)
  1404. {
  1405. ImGuiContext& g = *GImGui;
  1406. ImGuiTable* table = g.CurrentTable;
  1407. if (!table)
  1408. return NULL;
  1409. if (column_n < 0)
  1410. column_n = table->CurrentColumn;
  1411. return TableGetColumnName(table, column_n);
  1412. }
  1413. bool ImGui::TableGetColumnIsVisible(int column_n)
  1414. {
  1415. ImGuiContext& g = *GImGui;
  1416. ImGuiTable* table = g.CurrentTable;
  1417. if (!table)
  1418. return false;
  1419. if (column_n < 0)
  1420. column_n = table->CurrentColumn;
  1421. return (table->VisibleMaskByIndex & ((ImU64)1 << column_n)) != 0;
  1422. }
  1423. int ImGui::TableGetColumnIndex()
  1424. {
  1425. ImGuiContext& g = *GImGui;
  1426. ImGuiTable* table = g.CurrentTable;
  1427. if (!table)
  1428. return 0;
  1429. return table->CurrentColumn;
  1430. }
  1431. bool ImGui::TableSetColumnIndex(int column_idx)
  1432. {
  1433. ImGuiContext& g = *GImGui;
  1434. ImGuiTable* table = g.CurrentTable;
  1435. if (!table)
  1436. return false;
  1437. if (table->CurrentColumn != column_idx)
  1438. {
  1439. if (table->CurrentColumn != -1)
  1440. TableEndCell(table);
  1441. IM_ASSERT(column_idx >= 0 && table->ColumnsCount);
  1442. TableBeginCell(table, column_idx);
  1443. }
  1444. return (table->VisibleMaskByIndex & ((ImU64)1 << column_idx)) != 0;
  1445. }
  1446. ImRect ImGui::TableGetCellRect()
  1447. {
  1448. ImGuiContext& g = *GImGui;
  1449. ImGuiTable* table = g.CurrentTable;
  1450. ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
  1451. return ImRect(column->MinX, table->RowPosY1, column->MaxX, table->RowPosY2);
  1452. }
  1453. const char* ImGui::TableGetColumnName(ImGuiTable* table, int column_no)
  1454. {
  1455. ImGuiTableColumn* column = &table->Columns[column_no];
  1456. if (column->NameOffset == -1)
  1457. return NULL;
  1458. return &table->ColumnsNames.Buf[column->NameOffset];
  1459. }
  1460. void ImGui::TableSetColumnAutofit(ImGuiTable* table, int column_no)
  1461. {
  1462. // Disable clipping then auto-fit, will take 2 frames
  1463. // (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns)
  1464. ImGuiTableColumn* column = &table->Columns[column_no];
  1465. column->CannotSkipItemsQueue = (1 << 0);
  1466. column->AutoFitQueue = (1 << 1);
  1467. }
  1468. void ImGui::PushTableBackground()
  1469. {
  1470. ImGuiContext& g = *GImGui;
  1471. ImGuiWindow* window = g.CurrentWindow;
  1472. ImGuiTable* table = g.CurrentTable;
  1473. table->DrawSplitter.SetCurrentChannel(window->DrawList, 0);
  1474. PushClipRect(table->HostClipRect.Min, table->HostClipRect.Max, false);
  1475. }
  1476. void ImGui::PopTableBackground()
  1477. {
  1478. ImGuiContext& g = *GImGui;
  1479. ImGuiWindow* window = g.CurrentWindow;
  1480. ImGuiTable* table = g.CurrentTable;
  1481. ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
  1482. table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
  1483. PopClipRect();
  1484. }
  1485. // FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data?
  1486. void ImGui::TableDrawContextMenu(ImGuiTable* table, int selected_column_n)
  1487. {
  1488. ImGuiContext& g = *GImGui;
  1489. ImGuiWindow* window = g.CurrentWindow;
  1490. if (window->SkipItems)
  1491. return;
  1492. bool want_separator = false;
  1493. selected_column_n = ImClamp(selected_column_n, -1, table->ColumnsCount - 1);
  1494. // Sizing
  1495. if (table->Flags & ImGuiTableFlags_Resizable)
  1496. {
  1497. if (ImGuiTableColumn* selected_column = (selected_column_n != -1) ? &table->Columns[selected_column_n] : NULL)
  1498. {
  1499. const bool can_resize = !(selected_column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthStretch)) && selected_column->IsActive;
  1500. if (MenuItem("Size column to fit", NULL, false, can_resize))
  1501. TableSetColumnAutofit(table, selected_column_n);
  1502. }
  1503. if (MenuItem("Size all columns to fit", NULL))
  1504. {
  1505. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1506. {
  1507. ImGuiTableColumn* column = &table->Columns[column_n];
  1508. if (column->IsActive)
  1509. TableSetColumnAutofit(table, column_n);
  1510. }
  1511. }
  1512. want_separator = true;
  1513. }
  1514. // Ordering
  1515. if (table->Flags & ImGuiTableFlags_Reorderable)
  1516. {
  1517. if (MenuItem("Reset order", NULL, false, !table->IsDefaultDisplayOrder))
  1518. table->IsResetDisplayOrderRequest = true;
  1519. want_separator = true;
  1520. }
  1521. // Hiding / Visibility
  1522. if (table->Flags & ImGuiTableFlags_Hideable)
  1523. {
  1524. if (want_separator)
  1525. Separator();
  1526. want_separator = false;
  1527. PushItemFlag(ImGuiItemFlags_SelectableDontClosePopup, true);
  1528. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1529. {
  1530. ImGuiTableColumn* column = &table->Columns[column_n];
  1531. const char* name = TableGetColumnName(table, column_n);
  1532. if (name == NULL)
  1533. name = "<Unknown>";
  1534. // Make sure we can't hide the last active column
  1535. bool menu_item_active = (column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true;
  1536. if (column->IsActive && table->ColumnsActiveCount <= 1)
  1537. menu_item_active = false;
  1538. if (MenuItem(name, NULL, column->IsActive, menu_item_active))
  1539. column->NextIsActive = !column->IsActive;
  1540. }
  1541. PopItemFlag();
  1542. }
  1543. }
  1544. // This is a helper to output headers based on the column names declared in TableSetupColumn()
  1545. // The intent is that advanced users would not need to use this helper and may create their own.
  1546. void ImGui::TableAutoHeaders()
  1547. {
  1548. ImGuiContext& g = *GImGui;
  1549. ImGuiWindow* window = g.CurrentWindow;
  1550. if (window->SkipItems)
  1551. return;
  1552. ImGuiTable* table = g.CurrentTable;
  1553. IM_ASSERT(table && table->CurrentRow == -1);
  1554. int open_context_popup = INT_MAX;
  1555. // This for loop is constructed to not make use of internal functions,
  1556. // as this is intended to be a base template to copy and build from.
  1557. TableNextRow(ImGuiTableRowFlags_Headers, GetTextLineHeight());
  1558. const int columns_count = table->ColumnsCount;
  1559. for (int column_n = 0; column_n < columns_count; column_n++)
  1560. {
  1561. if (!TableSetColumnIndex(column_n))
  1562. continue;
  1563. const char* name = TableGetColumnName(column_n);
  1564. // FIXME-TABLE: Test custom user elements
  1565. #if 0
  1566. if (column_n < 2)
  1567. {
  1568. static bool b[10] = {};
  1569. PushID(column_n);
  1570. PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
  1571. Checkbox("##", &b[column_n]);
  1572. PopStyleVar();
  1573. PopID();
  1574. SameLine(0.0f, g.Style.ItemInnerSpacing.x);
  1575. }
  1576. #endif
  1577. // [DEBUG]
  1578. //if (g.IO.KeyCtrl) { static char buf[32]; name = buf; ImGuiTableColumn* c = &table->Columns[column_n]; if (c->Flags & ImGuiTableColumnFlags_WidthStretch) ImFormatString(buf, 32, "%.3f>%.1f", c->ResizeWeight, c->WidthGiven); else ImFormatString(buf, 32, "%.1f", c->WidthGiven); }
  1579. PushID(table->InstanceNo * table->ColumnsCount + column_n); // Allow unnamed labels (generally accidental, but let's behave nicely with them)
  1580. TableHeader(name);
  1581. PopID();
  1582. // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden
  1583. if (IsMouseReleased(1) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  1584. open_context_popup = column_n;
  1585. }
  1586. // FIXME-TABLE: This is not user-land code any more...
  1587. window->SkipItems = table->BackupSkipItems;
  1588. // Allow opening popup from the right-most section after the last column
  1589. // FIXME-TABLE: This is not user-land code any more... perhaps instead we should expose hovered column.
  1590. // and allow some sort of row-centric IsItemHovered() for full flexibility?
  1591. const float unused_x1 = (table->RightMostActiveColumn != -1) ? table->Columns[table->RightMostActiveColumn].MaxX : table->WorkRect.Min.x;
  1592. if (unused_x1 < table->WorkRect.Max.x)
  1593. {
  1594. // FIXME: We inherit ClipRect/SkipItem from last submitted column (active or not), let's override
  1595. window->ClipRect = table->InnerClipRect;
  1596. ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos;
  1597. window->DC.CursorPos = ImVec2(unused_x1, table->RowPosY1);
  1598. ImVec2 size = ImVec2(table->WorkRect.Max.x - window->DC.CursorPos.x, table->RowPosY2 - table->RowPosY1);
  1599. if (size.x > 0.0f && size.y > 0.0f)
  1600. {
  1601. InvisibleButton("##RemainingSpace", size);
  1602. window->DC.CursorPos.y -= g.Style.ItemSpacing.y;
  1603. window->DC.CursorMaxPos = backup_cursor_max_pos; // Don't feed back into the width of the Header row
  1604. // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden
  1605. if (IsMouseReleased(1) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
  1606. open_context_popup = -1;
  1607. }
  1608. window->ClipRect = window->DrawList->_ClipRectStack.back();
  1609. }
  1610. // Context Menu
  1611. if (open_context_popup != INT_MAX)
  1612. {
  1613. table->IsContextPopupOpen = true;
  1614. table->ContextPopupColumn = (ImS8)open_context_popup;
  1615. table->InstanceInteracted = table->InstanceNo;
  1616. OpenPopup("##TableContextMenu");
  1617. }
  1618. }
  1619. // Emit a column header (text + optional sort order)
  1620. // We cpu-clip text here so that all columns headers can be merged into a same draw call.
  1621. // FIXME-TABLE: Should hold a selection state.
  1622. void ImGui::TableHeader(const char* label)
  1623. {
  1624. ImGuiContext& g = *GImGui;
  1625. ImGuiWindow* window = g.CurrentWindow;
  1626. if (window->SkipItems)
  1627. return;
  1628. ImGuiTable* table = g.CurrentTable;
  1629. IM_ASSERT(table->CurrentColumn != -1);
  1630. const int column_n = table->CurrentColumn;
  1631. ImGuiTableColumn* column = &table->Columns[column_n];
  1632. float row_height = GetTextLineHeight();
  1633. ImRect cell_r = TableGetCellRect();
  1634. ImRect work_r = cell_r;
  1635. work_r.Min.x = window->DC.CursorPos.x;
  1636. work_r.Max.y = work_r.Min.y + row_height;
  1637. // Label
  1638. if (label == NULL)
  1639. label = "";
  1640. const char* label_end = FindRenderedTextEnd(label);
  1641. ImVec2 label_size = CalcTextSize(label, label_end, true);
  1642. ImVec2 label_pos = window->DC.CursorPos;
  1643. float ellipsis_max = work_r.Max.x;
  1644. // Selectable
  1645. PushID(label);
  1646. // FIXME-TABLE: Fix when padding are disabled.
  1647. //window->DC.CursorPos.x = column->MinX + table->CellPadding.x;
  1648. // Keep header highlighted when context menu is open. (FIXME-TABLE: however we cannot assume the ID of said popup if it has been created by the user...)
  1649. const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceNo);
  1650. const bool pressed = Selectable("", selected, ImGuiSelectableFlags_DrawHoveredWhenHeld, ImVec2(0.0f, row_height));
  1651. const bool held = IsItemActive();
  1652. if (held)
  1653. table->HeadHeaderColumn = (ImS8)column_n;
  1654. window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f;
  1655. // Drag and drop: re-order columns. Frozen columns are not reorderable.
  1656. // FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone.
  1657. if (held && (table->Flags & ImGuiTableFlags_Reorderable) && IsMouseDragging(0) && !g.DragDropActive)
  1658. {
  1659. // While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x
  1660. table->ReorderColumn = (ImS8)column_n;
  1661. table->InstanceInteracted = table->InstanceNo;
  1662. if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x)
  1663. if (column->PrevActiveColumn != -1 && (column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (table->Columns[column->PrevActiveColumn].IndexWithinActiveSet < table->FreezeColumnsRequest))
  1664. table->ReorderColumnDir = -1;
  1665. if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x)
  1666. if (column->NextActiveColumn != -1 && (column->IndexWithinActiveSet < table->FreezeColumnsRequest) == (table->Columns[column->NextActiveColumn].IndexWithinActiveSet < table->FreezeColumnsRequest))
  1667. table->ReorderColumnDir = +1;
  1668. }
  1669. // Sort order arrow
  1670. float w_arrow = 0.0f;
  1671. float w_sort_text = 0.0f;
  1672. if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort))
  1673. {
  1674. const float ARROW_SCALE = 0.75f;
  1675. w_arrow = ImFloor(g.FontSize * ARROW_SCALE + g.Style.FramePadding.x);// table->CellPadding.x);
  1676. if (column->SortOrder != -1)
  1677. {
  1678. w_sort_text = 0.0f;
  1679. char sort_order_suf[8];
  1680. if (column->SortOrder > 0)
  1681. {
  1682. ImFormatString(sort_order_suf, IM_ARRAYSIZE(sort_order_suf), "%d", column->SortOrder + 1);
  1683. w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x;
  1684. }
  1685. float x = ImMax(cell_r.Min.x, work_r.Max.x - w_arrow - w_sort_text);
  1686. ellipsis_max -= w_arrow + w_sort_text;
  1687. float y = label_pos.y;
  1688. ImU32 col = GetColorU32(ImGuiCol_Text);
  1689. if (column->SortOrder > 0)
  1690. {
  1691. PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text, 0.70f));
  1692. RenderText(ImVec2(x + g.Style.ItemInnerSpacing.x, y), sort_order_suf);
  1693. PopStyleColor();
  1694. x += w_sort_text;
  1695. }
  1696. RenderArrow(window->DrawList, ImVec2(x, y), col, column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Down : ImGuiDir_Up, ARROW_SCALE);
  1697. }
  1698. // Handle clicking on column header to adjust Sort Order
  1699. if (pressed && table->ReorderColumn != column_n)
  1700. TableSortSpecsClickColumn(table, column, g.IO.KeyShift);
  1701. }
  1702. // Render clipped label
  1703. // Clipping here ensure that in the majority of situations, all our header cells will be merged into a single draw call.
  1704. //window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE);
  1705. RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, label_pos.y + row_height + g.Style.FramePadding.y), ellipsis_max, ellipsis_max, label, label_end, &label_size);
  1706. // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering for merging.
  1707. // FIXME-TABLE: Clarify policies of how label width and potential decorations (arrows) fit into auto-resize of the column
  1708. float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow;
  1709. column->ContentMaxPosHeadersUsed = ImMax(column->ContentMaxPosHeadersUsed, work_r.Max.x);// ImMin(max_pos_x, work_r.Max.x));
  1710. column->ContentMaxPosHeadersDesired = ImMax(column->ContentMaxPosHeadersDesired, max_pos_x);
  1711. PopID();
  1712. }
  1713. void ImGui::TableSortSpecsClickColumn(ImGuiTable* table, ImGuiTableColumn* clicked_column, bool add_to_existing_sort_orders)
  1714. {
  1715. if (!(table->Flags & ImGuiTableFlags_MultiSortable))
  1716. add_to_existing_sort_orders = false;
  1717. ImS8 sort_order_max = 0;
  1718. if (add_to_existing_sort_orders)
  1719. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1720. sort_order_max = ImMax(sort_order_max, table->Columns[column_n].SortOrder);
  1721. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1722. {
  1723. ImGuiTableColumn* column = &table->Columns[column_n];
  1724. if (column == clicked_column)
  1725. {
  1726. // Set new sort direction and sort order
  1727. // - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click.
  1728. // - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op.
  1729. // - Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert
  1730. // the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code.
  1731. if (column->SortOrder == -1)
  1732. column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending);
  1733. else
  1734. column->SortDirection = (ImU8)((column->SortDirection == ImGuiSortDirection_Ascending) ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending);
  1735. if (column->SortOrder == -1 || !add_to_existing_sort_orders)
  1736. column->SortOrder = add_to_existing_sort_orders ? sort_order_max + 1 : 0;
  1737. }
  1738. else
  1739. {
  1740. if (!add_to_existing_sort_orders)
  1741. column->SortOrder = -1;
  1742. }
  1743. TableFixColumnSortDirection(column);
  1744. }
  1745. table->IsSettingsDirty = true;
  1746. table->IsSortSpecsDirty = true;
  1747. }
  1748. // Return NULL if no sort specs.
  1749. // Return ->WantSort == true when the specs have changed since the last query.
  1750. const ImGuiTableSortSpecs* ImGui::TableGetSortSpecs()
  1751. {
  1752. ImGuiContext& g = *GImGui;
  1753. ImGuiTable* table = g.CurrentTable;
  1754. IM_ASSERT(table != NULL);
  1755. if (!(table->Flags & ImGuiTableFlags_Sortable))
  1756. return NULL;
  1757. // Flatten sort specs into user facing data
  1758. const bool was_dirty = table->IsSortSpecsDirty;
  1759. if (was_dirty)
  1760. {
  1761. TableSortSpecsSanitize(table);
  1762. // Write output
  1763. table->SortSpecsData.resize(table->SortSpecsCount);
  1764. table->SortSpecs.ColumnsMask = 0x00;
  1765. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1766. {
  1767. ImGuiTableColumn* column = &table->Columns[column_n];
  1768. if (column->SortOrder == -1)
  1769. continue;
  1770. ImGuiTableSortSpecsColumn* sort_spec = &table->SortSpecsData[column->SortOrder];
  1771. sort_spec->ColumnUserID = column->UserID;
  1772. sort_spec->ColumnIndex = (ImU8)column_n;
  1773. sort_spec->SortOrder = (ImU8)column->SortOrder;
  1774. sort_spec->SortSign = (column->SortDirection == ImGuiSortDirection_Ascending) ? +1 : -1;
  1775. sort_spec->SortDirection = column->SortDirection;
  1776. table->SortSpecs.ColumnsMask |= (ImU64)1 << column_n;
  1777. }
  1778. }
  1779. // User facing data
  1780. table->SortSpecs.Specs = table->SortSpecsData.Data;
  1781. table->SortSpecs.SpecsCount = table->SortSpecsData.Size;
  1782. table->SortSpecs.SpecsChanged = was_dirty;
  1783. table->IsSortSpecsDirty = false;
  1784. return table->SortSpecs.SpecsCount ? &table->SortSpecs : NULL;
  1785. }
  1786. bool ImGui::TableGetColumnIsSorted(int column_n)
  1787. {
  1788. ImGuiContext& g = *GImGui;
  1789. ImGuiTable* table = g.CurrentTable;
  1790. if (!table)
  1791. return false;
  1792. if (column_n < 0)
  1793. column_n = table->CurrentColumn;
  1794. ImGuiTableColumn* column = &table->Columns[column_n];
  1795. return (column->SortOrder != -1);
  1796. }
  1797. void ImGui::TableSortSpecsSanitize(ImGuiTable* table)
  1798. {
  1799. // Clear SortOrder from hidden column and verify that there's no gap or duplicate.
  1800. int sort_order_count = 0;
  1801. ImU64 sort_order_mask = 0x00;
  1802. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1803. {
  1804. ImGuiTableColumn* column = &table->Columns[column_n];
  1805. if (column->SortOrder != -1 && !column->IsActive)
  1806. column->SortOrder = -1;
  1807. if (column->SortOrder == -1)
  1808. continue;
  1809. sort_order_count++;
  1810. sort_order_mask |= ((ImU64)1 << column->SortOrder);
  1811. IM_ASSERT(sort_order_count < (int)sizeof(sort_order_mask) * 8);
  1812. }
  1813. const bool need_fix_linearize = ((ImU64)1 << sort_order_count) != (sort_order_mask + 1);
  1814. const bool need_fix_single_sort_order = (sort_order_count > 1) && !(table->Flags & ImGuiTableFlags_MultiSortable);
  1815. if (need_fix_linearize || need_fix_single_sort_order)
  1816. {
  1817. ImU64 fixed_mask = 0x00;
  1818. for (int sort_n = 0; sort_n < sort_order_count; sort_n++)
  1819. {
  1820. // Fix: Rewrite sort order fields if needed so they have no gap or duplicate.
  1821. // (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1)
  1822. int column_with_smallest_sort_order = -1;
  1823. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1824. if ((fixed_mask & ((ImU64)1 << (ImU64)column_n)) == 0 && table->Columns[column_n].SortOrder != -1)
  1825. if (column_with_smallest_sort_order == -1 || table->Columns[column_n].SortOrder < table->Columns[column_with_smallest_sort_order].SortOrder)
  1826. column_with_smallest_sort_order = column_n;
  1827. IM_ASSERT(column_with_smallest_sort_order != -1);
  1828. fixed_mask |= ((ImU64)1 << column_with_smallest_sort_order);
  1829. table->Columns[column_with_smallest_sort_order].SortOrder = (ImS8)sort_n;
  1830. // Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set.
  1831. if (need_fix_single_sort_order)
  1832. {
  1833. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1834. if (column_n != column_with_smallest_sort_order)
  1835. table->Columns[column_n].SortOrder = -1;
  1836. break;
  1837. }
  1838. }
  1839. }
  1840. // Fallback default sort order (if no column has the ImGuiTableColumnFlags_DefaultSort flag)
  1841. if (sort_order_count == 0 && table->IsFirstFrame)
  1842. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1843. {
  1844. ImGuiTableColumn* column = &table->Columns[column_n];
  1845. if (!(column->Flags & ImGuiTableColumnFlags_NoSort) && column->IsActive)
  1846. {
  1847. sort_order_count = 1;
  1848. column->SortOrder = 0;
  1849. break;
  1850. }
  1851. }
  1852. table->SortSpecsCount = (ImS8)sort_order_count;
  1853. }
  1854. //-------------------------------------------------------------------------
  1855. // TABLE - .ini settings
  1856. //-------------------------------------------------------------------------
  1857. // [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings.
  1858. // [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table.
  1859. // [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty.
  1860. // [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file.
  1861. //-------------------------------------------------------------------------
  1862. static ImGuiTableSettings* CreateTableSettings(ImGuiID id, int columns_count)
  1863. {
  1864. ImGuiContext& g = *GImGui;
  1865. ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings));
  1866. IM_PLACEMENT_NEW(settings) ImGuiTableSettings();
  1867. ImGuiTableColumnSettings* settings_column = settings->GetColumnSettings();
  1868. for (int n = 0; n < columns_count; n++, settings_column++)
  1869. IM_PLACEMENT_NEW(settings_column) ImGuiTableColumnSettings();
  1870. settings->ID = id;
  1871. settings->ColumnsCount = settings->ColumnsCountMax = (ImS8)columns_count;
  1872. return settings;
  1873. }
  1874. static ImGuiTableSettings* FindTableSettingsByID(ImGuiID id)
  1875. {
  1876. // FIXME-OPT: Might want to store a lookup map for this?
  1877. ImGuiContext& g = *GImGui;
  1878. for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
  1879. if (settings->ID == id)
  1880. return settings;
  1881. return NULL;
  1882. }
  1883. ImGuiTableSettings* ImGui::TableFindSettings(ImGuiTable* table)
  1884. {
  1885. if (table->SettingsOffset == -1)
  1886. return NULL;
  1887. ImGuiContext& g = *GImGui;
  1888. ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset);
  1889. IM_ASSERT(settings->ID == table->ID);
  1890. if (settings->ColumnsCountMax < table->ColumnsCount)
  1891. {
  1892. settings->ID = 0; // Ditch storage if we won't fit because of a count change
  1893. return NULL;
  1894. }
  1895. return settings;
  1896. }
  1897. void ImGui::TableSaveSettings(ImGuiTable* table)
  1898. {
  1899. table->IsSettingsDirty = false;
  1900. if (table->Flags & ImGuiTableFlags_NoSavedSettings)
  1901. return;
  1902. // Bind or create settings data
  1903. ImGuiContext& g = *GImGui;
  1904. ImGuiTableSettings* settings = TableFindSettings(table);
  1905. if (settings == NULL)
  1906. {
  1907. settings = CreateTableSettings(table->ID, table->ColumnsCount);
  1908. table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);
  1909. }
  1910. settings->ColumnsCount = (ImS8)table->ColumnsCount;
  1911. // Serialize ImGuiTableSettings/ImGuiTableColumnSettings --> ImGuiTable/ImGuiTableColumn
  1912. IM_ASSERT(settings->ID == table->ID);
  1913. IM_ASSERT(settings->ColumnsCount == table->ColumnsCount && settings->ColumnsCountMax >= settings->ColumnsCount);
  1914. ImGuiTableColumn* column = table->Columns.Data;
  1915. ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
  1916. // FIXME-TABLE: Logic to avoid saving default widths?
  1917. settings->SaveFlags = ImGuiTableFlags_Resizable;
  1918. for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++)
  1919. {
  1920. //column_settings->WidthOrWeight = column->WidthRequested; // FIXME-WIP
  1921. column_settings->Index = (ImS8)n;
  1922. column_settings->DisplayOrder = column->IndexDisplayOrder;
  1923. column_settings->SortOrder = column->SortOrder;
  1924. column_settings->SortDirection = column->SortDirection;
  1925. column_settings->Visible = column->IsActive;
  1926. // We skip saving some data in the .ini file when they are unnecessary to restore our state
  1927. // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet.
  1928. if (column->IndexDisplayOrder != n)
  1929. settings->SaveFlags |= ImGuiTableFlags_Reorderable;;
  1930. if (column_settings->SortOrder != -1)
  1931. settings->SaveFlags |= ImGuiTableFlags_Sortable;
  1932. if (column_settings->Visible != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0))
  1933. settings->SaveFlags |= ImGuiTableFlags_Hideable;
  1934. }
  1935. settings->SaveFlags &= table->Flags;
  1936. MarkIniSettingsDirty();
  1937. }
  1938. void ImGui::TableLoadSettings(ImGuiTable* table)
  1939. {
  1940. ImGuiContext& g = *GImGui;
  1941. table->IsSettingsRequestLoad = false;
  1942. if (table->Flags & ImGuiTableFlags_NoSavedSettings)
  1943. return;
  1944. // Bind settings
  1945. ImGuiTableSettings* settings;
  1946. if (table->SettingsOffset == -1)
  1947. {
  1948. settings = FindTableSettingsByID(table->ID);
  1949. if (settings == NULL)
  1950. return;
  1951. table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);
  1952. }
  1953. else
  1954. {
  1955. settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset);
  1956. }
  1957. table->IsSettingsLoaded = true;
  1958. settings->SaveFlags = table->Flags;
  1959. // Serialize ImGuiTable/ImGuiTableColumn --> ImGuiTableSettings/ImGuiTableColumnSettings
  1960. ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
  1961. for (int data_n = 0; data_n < settings->ColumnsCount; data_n++, column_settings++)
  1962. {
  1963. int column_n = column_settings->Index;
  1964. if (column_n < 0 || column_n >= table->ColumnsCount)
  1965. continue;
  1966. ImGuiTableColumn* column = &table->Columns[column_n];
  1967. //column->WidthRequested = column_settings->WidthOrWeight; // FIXME-WIP
  1968. if (column_settings->DisplayOrder != -1)
  1969. column->IndexDisplayOrder = column_settings->DisplayOrder;
  1970. if (column_settings->SortOrder != -1)
  1971. {
  1972. column->SortOrder = column_settings->SortOrder;
  1973. column->SortDirection = column_settings->SortDirection;
  1974. }
  1975. column->IsActive = column->NextIsActive = column_settings->Visible;
  1976. }
  1977. // FIXME-TABLE: Need to validate .ini data
  1978. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1979. table->DisplayOrder[table->Columns[column_n].IndexDisplayOrder] = (ImU8)column_n;
  1980. }
  1981. void* ImGui::TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  1982. {
  1983. ImGuiID id = 0;
  1984. int columns_count = 0;
  1985. if (sscanf(name, "0x%08X,%d", &id, &columns_count) < 2)
  1986. return NULL;
  1987. return CreateTableSettings(id, columns_count);
  1988. }
  1989. void ImGui::TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
  1990. {
  1991. // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v"
  1992. ImGuiTableSettings* settings = (ImGuiTableSettings*)entry;
  1993. int column_n = 0, r = 0, n = 0;
  1994. if (sscanf(line, "Column %d%n", &column_n, &r) == 1) { line = ImStrSkipBlank(line + r); } else { return; }
  1995. if (column_n < 0 || column_n >= settings->ColumnsCount)
  1996. return;
  1997. char c = 0;
  1998. ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n;
  1999. column->Index = (ImS8)column_n;
  2000. if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r) == 1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; }
  2001. if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); /* .. */ settings->SaveFlags |= ImGuiTableFlags_Resizable; }
  2002. if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->Visible = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; }
  2003. if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImS8)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; }
  2004. if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImS8)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; }
  2005. }
  2006. void ImGui::TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  2007. {
  2008. ImGuiContext& g = *ctx;
  2009. for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
  2010. {
  2011. if (settings->ID == 0) // Skip ditched settings
  2012. continue;
  2013. // TableSaveSettings() may clear some of those flags when we establish that the data can be stripped (e.g. Order was unchanged)
  2014. const bool save_size = (settings->SaveFlags & ImGuiTableFlags_Resizable) != 0;
  2015. const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0;
  2016. const bool save_order = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0;
  2017. const bool save_sort = (settings->SaveFlags & ImGuiTableFlags_Sortable) != 0;
  2018. if (!save_size && !save_visible && !save_order && !save_sort)
  2019. continue;
  2020. buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve
  2021. buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount);
  2022. ImGuiTableColumnSettings* column = settings->GetColumnSettings();
  2023. for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++)
  2024. {
  2025. // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v"
  2026. if (column->UserID != 0)
  2027. buf->appendf("Column %-2d UserID=%08X", column_n, column->UserID);
  2028. else
  2029. buf->appendf("Column %-2d", column_n);
  2030. if (save_size) buf->appendf(" Width=%d", 0);// (int)settings_column->WidthOrWeight); // FIXME-TABLE
  2031. if (save_visible) buf->appendf(" Visible=%d", column->Visible);
  2032. if (save_order) buf->appendf(" Order=%d", column->DisplayOrder);
  2033. if (save_sort && column->SortOrder != -1) buf->appendf(" Sort=%d%c", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^');
  2034. buf->append("\n");
  2035. }
  2036. buf->append("\n");
  2037. }
  2038. }
  2039. //-------------------------------------------------------------------------
  2040. // TABLE - Debugging
  2041. //-------------------------------------------------------------------------
  2042. // - DebugNodeTable() [Internal]
  2043. //-------------------------------------------------------------------------
  2044. #ifndef IMGUI_DISABLE_METRICS_WINDOW
  2045. void ImGui::DebugNodeTable(ImGuiTable* table)
  2046. {
  2047. char buf[256];
  2048. char* p = buf;
  2049. const char* buf_end = buf + IM_ARRAYSIZE(buf);
  2050. ImFormatString(p, buf_end - p, "Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
  2051. bool open = TreeNode(table, "%s", buf);
  2052. if (IsItemHovered())
  2053. GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255));
  2054. if (open)
  2055. {
  2056. for (int n = 0; n < table->ColumnsCount; n++)
  2057. {
  2058. ImGuiTableColumn* column = &table->Columns[n];
  2059. const char* name = TableGetColumnName(table, n);
  2060. BulletText("Column %d order %d name '%s': +%.1f to +%.1f\n"
  2061. "Active: %d, Clipped: %d, DrawChannels: %d,%d\n"
  2062. "WidthGiven/Requested: %.1f/%.1f, Weight: %.2f\n"
  2063. "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..",
  2064. n, column->IndexDisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x,
  2065. column->IsActive, column->IsClipped, column->DrawChannelRowsBeforeFreeze, column->DrawChannelRowsAfterFreeze,
  2066. column->WidthGiven, column->WidthRequested, column->ResizeWeight,
  2067. column->UserID, column->Flags,
  2068. (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "",
  2069. (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "",
  2070. (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize) ? "WidthAlwaysAutoResize " : "",
  2071. (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : "");
  2072. }
  2073. ImGuiTableSettings* settings = TableFindSettings(table);
  2074. if (settings && TreeNode("Settings"))
  2075. {
  2076. BulletText("SaveFlags: 0x%08X", settings->SaveFlags);
  2077. BulletText("ColumnsCount: %d (max %d)", settings->ColumnsCount, settings->ColumnsCountMax);
  2078. for (int n = 0; n < settings->ColumnsCount; n++)
  2079. {
  2080. ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n];
  2081. BulletText("Column %d Order %d SortOrder %d Visible %d UserID 0x%08X WidthOrWeight %.3f",
  2082. n, column_settings->DisplayOrder, column_settings->SortOrder, column_settings->Visible, column_settings->UserID, column_settings->WidthOrWeight);
  2083. }
  2084. TreePop();
  2085. }
  2086. TreePop();
  2087. }
  2088. }
  2089. #endif // #ifndef IMGUI_DISABLE_METRICS_WINDOW
  2090. //-------------------------------------------------------------------------
  2091. //-------------------------------------------------------------------------
  2092. // [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc.
  2093. // (This is a legacy API, prefer using BeginTable/EndTable!)
  2094. //-------------------------------------------------------------------------
  2095. // - SetWindowClipRectBeforeSetChannel() [Internal]
  2096. // - GetColumnIndex()
  2097. // - GetColumnsCount()
  2098. // - GetColumnOffset()
  2099. // - GetColumnWidth()
  2100. // - SetColumnOffset()
  2101. // - SetColumnWidth()
  2102. // - PushColumnClipRect() [Internal]
  2103. // - PushColumnsBackground() [Internal]
  2104. // - PopColumnsBackground() [Internal]
  2105. // - FindOrCreateColumns() [Internal]
  2106. // - GetColumnsID() [Internal]
  2107. // - BeginColumns()
  2108. // - NextColumn()
  2109. // - EndColumns()
  2110. // - Columns()
  2111. //-------------------------------------------------------------------------
  2112. // [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences,
  2113. // they would meddle many times with the underlying ImDrawCmd.
  2114. // Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let
  2115. // the subsequent single call to SetCurrentChannel() does it things once.
  2116. void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect)
  2117. {
  2118. ImVec4 clip_rect_vec4 = clip_rect.ToVec4();
  2119. window->ClipRect = clip_rect;
  2120. window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4;
  2121. window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4;
  2122. }
  2123. int ImGui::GetColumnIndex()
  2124. {
  2125. ImGuiWindow* window = GetCurrentWindowRead();
  2126. return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0;
  2127. }
  2128. int ImGui::GetColumnsCount()
  2129. {
  2130. ImGuiWindow* window = GetCurrentWindowRead();
  2131. return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1;
  2132. }
  2133. float ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm)
  2134. {
  2135. return offset_norm * (columns->OffMaxX - columns->OffMinX);
  2136. }
  2137. float ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset)
  2138. {
  2139. return offset / (columns->OffMaxX - columns->OffMinX);
  2140. }
  2141. static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f;
  2142. static float GetDraggedColumnOffset(ImGuiOldColumns* columns, int column_index)
  2143. {
  2144. // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
  2145. // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
  2146. ImGuiContext& g = *GImGui;
  2147. ImGuiWindow* window = g.CurrentWindow;
  2148. IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
  2149. IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
  2150. float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x;
  2151. x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
  2152. if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths))
  2153. x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
  2154. return x;
  2155. }
  2156. float ImGui::GetColumnOffset(int column_index)
  2157. {
  2158. ImGuiWindow* window = GetCurrentWindowRead();
  2159. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2160. if (columns == NULL)
  2161. return 0.0f;
  2162. if (column_index < 0)
  2163. column_index = columns->Current;
  2164. IM_ASSERT(column_index < columns->Columns.Size);
  2165. const float t = columns->Columns[column_index].OffsetNorm;
  2166. const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t);
  2167. return x_offset;
  2168. }
  2169. static float GetColumnWidthEx(ImGuiOldColumns* columns, int column_index, bool before_resize = false)
  2170. {
  2171. if (column_index < 0)
  2172. column_index = columns->Current;
  2173. float offset_norm;
  2174. if (before_resize)
  2175. offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
  2176. else
  2177. offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
  2178. return ImGui::GetColumnOffsetFromNorm(columns, offset_norm);
  2179. }
  2180. float ImGui::GetColumnWidth(int column_index)
  2181. {
  2182. ImGuiContext& g = *GImGui;
  2183. ImGuiWindow* window = g.CurrentWindow;
  2184. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2185. if (columns == NULL)
  2186. return GetContentRegionAvail().x;
  2187. if (column_index < 0)
  2188. column_index = columns->Current;
  2189. return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
  2190. }
  2191. void ImGui::SetColumnOffset(int column_index, float offset)
  2192. {
  2193. ImGuiContext& g = *GImGui;
  2194. ImGuiWindow* window = g.CurrentWindow;
  2195. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2196. IM_ASSERT(columns != NULL);
  2197. if (column_index < 0)
  2198. column_index = columns->Current;
  2199. IM_ASSERT(column_index < columns->Columns.Size);
  2200. const bool preserve_width = !(columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1);
  2201. const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
  2202. if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow))
  2203. offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
  2204. columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX);
  2205. if (preserve_width)
  2206. SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
  2207. }
  2208. void ImGui::SetColumnWidth(int column_index, float width)
  2209. {
  2210. ImGuiWindow* window = GetCurrentWindowRead();
  2211. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2212. IM_ASSERT(columns != NULL);
  2213. if (column_index < 0)
  2214. column_index = columns->Current;
  2215. SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
  2216. }
  2217. void ImGui::PushColumnClipRect(int column_index)
  2218. {
  2219. ImGuiWindow* window = GetCurrentWindowRead();
  2220. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2221. if (column_index < 0)
  2222. column_index = columns->Current;
  2223. ImGuiOldColumnData* column = &columns->Columns[column_index];
  2224. PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false);
  2225. }
  2226. // Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns)
  2227. void ImGui::PushColumnsBackground()
  2228. {
  2229. ImGuiWindow* window = GetCurrentWindowRead();
  2230. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2231. if (columns->Count == 1)
  2232. return;
  2233. // Optimization: avoid SetCurrentChannel() + PushClipRect()
  2234. columns->HostBackupClipRect = window->ClipRect;
  2235. SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect);
  2236. columns->Splitter.SetCurrentChannel(window->DrawList, 0);
  2237. }
  2238. void ImGui::PopColumnsBackground()
  2239. {
  2240. ImGuiWindow* window = GetCurrentWindowRead();
  2241. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2242. if (columns->Count == 1)
  2243. return;
  2244. // Optimization: avoid PopClipRect() + SetCurrentChannel()
  2245. SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect);
  2246. columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
  2247. }
  2248. ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id)
  2249. {
  2250. // We have few columns per window so for now we don't need bother much with turning this into a faster lookup.
  2251. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  2252. if (window->ColumnsStorage[n].ID == id)
  2253. return &window->ColumnsStorage[n];
  2254. window->ColumnsStorage.push_back(ImGuiOldColumns());
  2255. ImGuiOldColumns* columns = &window->ColumnsStorage.back();
  2256. columns->ID = id;
  2257. return columns;
  2258. }
  2259. ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count)
  2260. {
  2261. ImGuiWindow* window = GetCurrentWindow();
  2262. // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
  2263. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
  2264. PushID(0x11223347 + (str_id ? 0 : columns_count));
  2265. ImGuiID id = window->GetID(str_id ? str_id : "columns");
  2266. PopID();
  2267. return id;
  2268. }
  2269. void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags)
  2270. {
  2271. ImGuiContext& g = *GImGui;
  2272. ImGuiWindow* window = GetCurrentWindow();
  2273. IM_ASSERT(columns_count >= 1);
  2274. IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported
  2275. // Acquire storage for the columns set
  2276. ImGuiID id = GetColumnsID(str_id, columns_count);
  2277. ImGuiOldColumns* columns = FindOrCreateColumns(window, id);
  2278. IM_ASSERT(columns->ID == id);
  2279. columns->Current = 0;
  2280. columns->Count = columns_count;
  2281. columns->Flags = flags;
  2282. window->DC.CurrentColumns = columns;
  2283. columns->HostCursorPosY = window->DC.CursorPos.y;
  2284. columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x;
  2285. columns->HostInitialClipRect = window->ClipRect;
  2286. columns->HostBackupParentWorkRect = window->ParentWorkRect;
  2287. window->ParentWorkRect = window->WorkRect;
  2288. // Set state for first column
  2289. // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect
  2290. const float column_padding = g.Style.ItemSpacing.x;
  2291. const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize));
  2292. const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f);
  2293. const float max_2 = window->WorkRect.Max.x + half_clip_extend_x;
  2294. columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f);
  2295. columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f);
  2296. columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
  2297. // Clear data if columns count changed
  2298. if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
  2299. columns->Columns.resize(0);
  2300. // Initialize default widths
  2301. columns->IsFirstFrame = (columns->Columns.Size == 0);
  2302. if (columns->Columns.Size == 0)
  2303. {
  2304. columns->Columns.reserve(columns_count + 1);
  2305. for (int n = 0; n < columns_count + 1; n++)
  2306. {
  2307. ImGuiOldColumnData column;
  2308. column.OffsetNorm = n / (float)columns_count;
  2309. columns->Columns.push_back(column);
  2310. }
  2311. }
  2312. for (int n = 0; n < columns_count; n++)
  2313. {
  2314. // Compute clipping rectangle
  2315. ImGuiOldColumnData* column = &columns->Columns[n];
  2316. float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n));
  2317. float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
  2318. column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
  2319. column->ClipRect.ClipWithFull(window->ClipRect);
  2320. }
  2321. if (columns->Count > 1)
  2322. {
  2323. columns->Splitter.Split(window->DrawList, 1 + columns->Count);
  2324. columns->Splitter.SetCurrentChannel(window->DrawList, 1);
  2325. PushColumnClipRect(0);
  2326. }
  2327. // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user.
  2328. float offset_0 = GetColumnOffset(columns->Current);
  2329. float offset_1 = GetColumnOffset(columns->Current + 1);
  2330. float width = offset_1 - offset_0;
  2331. PushItemWidth(width * 0.65f);
  2332. window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
  2333. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  2334. window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
  2335. }
  2336. void ImGui::NextColumn()
  2337. {
  2338. ImGuiWindow* window = GetCurrentWindow();
  2339. if (window->SkipItems || window->DC.CurrentColumns == NULL)
  2340. return;
  2341. ImGuiContext& g = *GImGui;
  2342. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2343. if (columns->Count == 1)
  2344. {
  2345. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  2346. IM_ASSERT(columns->Current == 0);
  2347. return;
  2348. }
  2349. // Next column
  2350. if (++columns->Current == columns->Count)
  2351. columns->Current = 0;
  2352. PopItemWidth();
  2353. // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect()
  2354. // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them),
  2355. ImGuiOldColumnData* column = &columns->Columns[columns->Current];
  2356. SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
  2357. columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
  2358. const float column_padding = g.Style.ItemSpacing.x;
  2359. columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
  2360. if (columns->Current > 0)
  2361. {
  2362. // Columns 1+ ignore IndentX (by canceling it out)
  2363. // FIXME-COLUMNS: Unnecessary, could be locked?
  2364. window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding;
  2365. }
  2366. else
  2367. {
  2368. // New row/line: column 0 honor IndentX.
  2369. window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
  2370. columns->LineMinY = columns->LineMaxY;
  2371. }
  2372. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  2373. window->DC.CursorPos.y = columns->LineMinY;
  2374. window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
  2375. window->DC.CurrLineTextBaseOffset = 0.0f;
  2376. // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup.
  2377. float offset_0 = GetColumnOffset(columns->Current);
  2378. float offset_1 = GetColumnOffset(columns->Current + 1);
  2379. float width = offset_1 - offset_0;
  2380. PushItemWidth(width * 0.65f);
  2381. window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
  2382. }
  2383. void ImGui::EndColumns()
  2384. {
  2385. ImGuiContext& g = *GImGui;
  2386. ImGuiWindow* window = GetCurrentWindow();
  2387. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2388. IM_ASSERT(columns != NULL);
  2389. PopItemWidth();
  2390. if (columns->Count > 1)
  2391. {
  2392. PopClipRect();
  2393. columns->Splitter.Merge(window->DrawList);
  2394. }
  2395. const ImGuiOldColumnFlags flags = columns->Flags;
  2396. columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
  2397. window->DC.CursorPos.y = columns->LineMaxY;
  2398. if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize))
  2399. window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent
  2400. // Draw columns borders and handle resize
  2401. // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy
  2402. bool is_being_resized = false;
  2403. if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems)
  2404. {
  2405. // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.
  2406. const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y);
  2407. const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y);
  2408. int dragging_column = -1;
  2409. for (int n = 1; n < columns->Count; n++)
  2410. {
  2411. ImGuiOldColumnData* column = &columns->Columns[n];
  2412. float x = window->Pos.x + GetColumnOffset(n);
  2413. const ImGuiID column_id = columns->ID + ImGuiID(n);
  2414. const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH;
  2415. const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2));
  2416. KeepAliveID(column_id);
  2417. if (IsClippedEx(column_hit_rect, column_id, false))
  2418. continue;
  2419. bool hovered = false, held = false;
  2420. if (!(flags & ImGuiOldColumnFlags_NoResize))
  2421. {
  2422. ButtonBehavior(column_hit_rect, column_id, &hovered, &held);
  2423. if (hovered || held)
  2424. g.MouseCursor = ImGuiMouseCursor_ResizeEW;
  2425. if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize))
  2426. dragging_column = n;
  2427. }
  2428. // Draw column
  2429. const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
  2430. const float xi = IM_FLOOR(x);
  2431. window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col);
  2432. }
  2433. // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
  2434. if (dragging_column != -1)
  2435. {
  2436. if (!columns->IsBeingResized)
  2437. for (int n = 0; n < columns->Count + 1; n++)
  2438. columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
  2439. columns->IsBeingResized = is_being_resized = true;
  2440. float x = GetDraggedColumnOffset(columns, dragging_column);
  2441. SetColumnOffset(dragging_column, x);
  2442. }
  2443. }
  2444. columns->IsBeingResized = is_being_resized;
  2445. window->WorkRect = window->ParentWorkRect;
  2446. window->ParentWorkRect = columns->HostBackupParentWorkRect;
  2447. window->DC.CurrentColumns = NULL;
  2448. window->DC.ColumnsOffset.x = 0.0f;
  2449. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  2450. }
  2451. void ImGui::Columns(int columns_count, const char* id, bool border)
  2452. {
  2453. ImGuiWindow* window = GetCurrentWindow();
  2454. IM_ASSERT(columns_count >= 1);
  2455. ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder);
  2456. //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior
  2457. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2458. if (columns != NULL && columns->Count == columns_count && columns->Flags == flags)
  2459. return;
  2460. if (columns != NULL)
  2461. EndColumns();
  2462. if (columns_count != 1)
  2463. BeginColumns(id, columns_count, flags);
  2464. }
  2465. //-------------------------------------------------------------------------
  2466. #endif // #ifndef IMGUI_DISABLE