imgui_tables.cpp 163 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336
  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. //-----------------------------------------------------------------------------
  55. // Typical call flow: (root level is public API):
  56. // - BeginTable() user begin into a table
  57. // | BeginChild() - (if ScrollX/ScrollY is set)
  58. // | TableBeginUpdateColumns() - apply resize/order requests, lock columns active state, order
  59. // | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame)
  60. // | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width
  61. // - TableSetupColumn() user submit columns details (optional)
  62. // - TableSetupScrollFreeze() user submit scroll freeze information (optional)
  63. // - TableUpdateLayout() [Internal] automatically called by the FIRST call to TableNextRow() or Table*Header(): lock all widths, columns positions, clipping rectangles
  64. // | TableUpdateDrawChannels() - setup ImDrawList channels
  65. // | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission
  66. // | TableDrawContextMenu() - draw right-click context menu
  67. //-----------------------------------------------------------------------------
  68. // - TableHeadersRow() or TableHeader() user submit a headers row (optional)
  69. // | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction
  70. // | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu
  71. // - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers)
  72. // - TableNextRow() / TableNextColumn() user begin into the first row, also automatically called by TableHeadersRow()
  73. // | TableEndCell() - close existing cell if not the first time
  74. // | TableBeginCell() - enter into current cell
  75. // - [...] user emit contents
  76. //-----------------------------------------------------------------------------
  77. // - EndTable() user ends the table
  78. // | TableDrawBorders() - draw outer borders, inner vertical borders
  79. // | TableReorderDrawChannelsForMerge() - merge draw channels if clipping isn't required
  80. // | EndChild() - (if ScrollX/ScrollY is set)
  81. //-----------------------------------------------------------------------------
  82. // Configuration
  83. static const float TABLE_BORDER_SIZE = 1.0f; // FIXME-TABLE: Currently hard-coded.
  84. static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders.
  85. 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.
  86. // Helper
  87. inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags, ImGuiWindow* outer_window)
  88. {
  89. // Adjust flags: set default sizing policy
  90. if ((flags & ImGuiTableFlags_SizingPolicyMaskX_) == 0)
  91. flags |= (flags & ImGuiTableFlags_ScrollX) ? ImGuiTableFlags_SizingPolicyFixedX : ImGuiTableFlags_SizingPolicyStretchX;
  92. // Adjust flags: MultiSortable automatically enable Sortable
  93. if (flags & ImGuiTableFlags_MultiSortable)
  94. flags |= ImGuiTableFlags_Sortable;
  95. // Adjust flags: disable saved settings if there's nothing to save
  96. if ((flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Sortable)) == 0)
  97. flags |= ImGuiTableFlags_NoSavedSettings;
  98. // Adjust flags: enforce borders when resizable
  99. if (flags & ImGuiTableFlags_Resizable)
  100. flags |= ImGuiTableFlags_BordersInnerV;
  101. // Adjust flags: disable NoHostExtendY if we have any scrolling going on
  102. if ((flags & ImGuiTableFlags_NoHostExtendY) && (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0)
  103. flags &= ~ImGuiTableFlags_NoHostExtendY;
  104. // Adjust flags: NoBordersInBodyUntilResize takes priority over NoBordersInBody
  105. if (flags & ImGuiTableFlags_NoBordersInBodyUntilResize)
  106. flags &= ~ImGuiTableFlags_NoBordersInBody;
  107. // Inherit _NoSavedSettings from top-level window (child windows always have _NoSavedSettings set)
  108. #ifdef IMGUI_HAS_DOCK
  109. ImGuiWindow* window_for_settings = outer_window->RootWindowDockStop;
  110. #else
  111. ImGuiWindow* window_for_settings = outer_window->RootWindow;
  112. #endif
  113. if (window_for_settings->Flags & ImGuiWindowFlags_NoSavedSettings)
  114. flags |= ImGuiTableFlags_NoSavedSettings;
  115. return flags;
  116. }
  117. ImGuiTable* ImGui::FindTableByID(ImGuiID id)
  118. {
  119. ImGuiContext& g = *GImGui;
  120. return g.Tables.GetByKey(id);
  121. }
  122. // (Read carefully because this is subtle but it does make sense!)
  123. // About 'outer_size', its meaning needs to differ slightly depending of if we are using ScrollX/ScrollY flags:
  124. // X:
  125. // - outer_size.x < 0.0f -> right align from window/work-rect maximum x edge.
  126. // - outer_size.x = 0.0f -> auto enlarge, use all available space.
  127. // - outer_size.x > 0.0f -> fixed width
  128. // Y with ScrollX/ScrollY: using a child window for scrolling:
  129. // - outer_size.y < 0.0f -> bottom align
  130. // - outer_size.y = 0.0f -> bottom align, consistent with BeginChild(). not recommended unless table is last item in parent window.
  131. // - outer_size.y > 0.0f -> fixed child height. recommended when using Scrolling on any axis.
  132. // Y without scrolling, we output table directly in parent window:
  133. // - outer_size.y < 0.0f -> bottom align (will auto extend, unless NoHostExtendV is set)
  134. // - outer_size.y = 0.0f -> zero minimum height (will auto extend, unless NoHostExtendV is set)
  135. // - outer_size.y > 0.0f -> minimum height (will auto extend, unless NoHostExtendV is set)
  136. // About 'inner_width':
  137. // With ScrollX:
  138. // - inner_width < 0.0f -> *illegal* fit in known width (right align from outer_size.x) <-- weird
  139. // - inner_width = 0.0f -> fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns.
  140. // - inner_width > 0.0f -> override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space!
  141. // Without ScrollX:
  142. // - inner_width -> *ignored*
  143. // Details:
  144. // - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept
  145. // of "available space" doesn't make sense.
  146. // - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding
  147. // of what the value does.
  148. bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
  149. {
  150. ImGuiID id = GetID(str_id);
  151. return BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width);
  152. }
  153. // For reference, the total _allocation count_ for a table is:
  154. // + 0 (for ImGuiTable instance, we sharing allocation in g.Tables pool)
  155. // + 1 (for table->RawData allocated below)
  156. // + 1 (for table->Splitter._Channels)
  157. // + 2 * active_channels_count (for ImDrawCmd and ImDrawIdx buffers inside channels)
  158. // Where active_channels_count is variable but often == columns_count or columns_count + 1, see TableUpdateDrawChannels() for details.
  159. // Unused channels don't perform their +2 allocations.
  160. static void TableBeginInitMemory(ImGuiTable* table, int columns_count)
  161. {
  162. // Allocate single buffer for our arrays
  163. ImSpanAllocator<3> span_allocator;
  164. span_allocator.ReserveBytes(0, columns_count * sizeof(ImGuiTableColumn));
  165. span_allocator.ReserveBytes(1, columns_count * sizeof(ImS8));
  166. span_allocator.ReserveBytes(2, columns_count * sizeof(ImGuiTableCellData));
  167. table->RawData.resize(span_allocator.GetArenaSizeInBytes());
  168. span_allocator.SetArenaBasePtr(table->RawData.Data);
  169. span_allocator.GetSpan(0, &table->Columns);
  170. span_allocator.GetSpan(1, &table->DisplayOrderToIndex);
  171. span_allocator.GetSpan(2, &table->RowCellData);
  172. for (int n = 0; n < columns_count; n++)
  173. {
  174. table->Columns[n] = ImGuiTableColumn();
  175. table->Columns[n].DisplayOrder = table->DisplayOrderToIndex[n] = (ImS8)n;
  176. }
  177. table->IsInitializing = table->IsSettingsRequestLoad = table->IsSortSpecsDirty = true;
  178. }
  179. bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
  180. {
  181. ImGuiContext& g = *GImGui;
  182. ImGuiWindow* outer_window = GetCurrentWindow();
  183. if (outer_window->SkipItems) // Consistent with other tables + beneficial side effect that assert on miscalling EndTable() will be more visible.
  184. return false;
  185. // Sanity checks
  186. IM_ASSERT(columns_count > 0 && columns_count <= IMGUI_TABLE_MAX_COLUMNS && "Only 1..64 columns allowed!");
  187. if (flags & ImGuiTableFlags_ScrollX)
  188. IM_ASSERT(inner_width >= 0.0f);
  189. // If an outer size is specified ahead we will be able to early out when not visible. Exact clipping rules may evolve.
  190. const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0;
  191. const ImVec2 avail_size = GetContentRegionAvail();
  192. ImVec2 actual_outer_size = CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f);
  193. ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size);
  194. if (use_child_window && IsClippedEx(outer_rect, 0, false))
  195. {
  196. ItemSize(outer_rect);
  197. return false;
  198. }
  199. // Acquire storage for the table
  200. ImGuiTable* table = g.Tables.GetOrAddByKey(id);
  201. const int instance_no = (table->LastFrameActive != g.FrameCount) ? 0 : table->InstanceCurrent + 1;
  202. const ImGuiID instance_id = id + instance_no;
  203. const ImGuiTableFlags table_last_flags = table->Flags;
  204. if (instance_no > 0)
  205. IM_ASSERT(table->ColumnsCount == columns_count && "BeginTable(): Cannot change columns count mid-frame while preserving same ID");
  206. // Fix flags
  207. flags = TableFixFlags(flags, outer_window);
  208. // Initialize
  209. table->ID = id;
  210. table->Flags = flags;
  211. table->InstanceCurrent = (ImS16)instance_no;
  212. table->LastFrameActive = g.FrameCount;
  213. table->OuterWindow = table->InnerWindow = outer_window;
  214. table->ColumnsCount = columns_count;
  215. table->ColumnsNames.Buf.resize(0);
  216. table->IsInitializing = false;
  217. table->IsLayoutLocked = false;
  218. table->InnerWidth = inner_width;
  219. table->OuterRect = outer_rect;
  220. table->WorkRect = outer_rect;
  221. // When not using a child window, WorkRect.Max will grow as we append contents.
  222. if (use_child_window)
  223. {
  224. // Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent
  225. // (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing)
  226. ImVec2 override_content_size(FLT_MAX, FLT_MAX);
  227. if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY))
  228. override_content_size.y = FLT_MIN;
  229. // Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and
  230. // never lead to any scrolling). We don't handle inner_width < 0.0f, we could potentially use it to right-align
  231. // based on the right side of the child window work rect, which would require knowing ahead if we are going to
  232. // have decoration taking horizontal spaces (typically a vertical scrollbar).
  233. if ((flags & ImGuiTableFlags_ScrollX) && inner_width > 0.0f)
  234. override_content_size.x = inner_width;
  235. if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX)
  236. 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));
  237. // Create scrolling region (without border and zero window padding)
  238. ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None;
  239. BeginChildEx(name, instance_id, table->OuterRect.GetSize(), false, child_flags);
  240. table->InnerWindow = g.CurrentWindow;
  241. table->WorkRect = table->InnerWindow->WorkRect;
  242. table->OuterRect = table->InnerWindow->Rect();
  243. IM_ASSERT(table->InnerWindow->WindowPadding.x == 0.0f && table->InnerWindow->WindowPadding.y == 0.0f && table->InnerWindow->WindowBorderSize == 0.0f);
  244. }
  245. // Push a standardized ID for both child-using and not-child-using tables
  246. PushOverrideID(instance_id);
  247. // Backup a copy of host window members we will modify
  248. ImGuiWindow* inner_window = table->InnerWindow;
  249. table->HostIndentX = inner_window->DC.Indent.x;
  250. table->HostClipRect = inner_window->ClipRect;
  251. table->HostSkipItems = inner_window->SkipItems;
  252. table->HostBackupParentWorkRect = inner_window->ParentWorkRect;
  253. table->HostBackupColumnsOffset = outer_window->DC.ColumnsOffset;
  254. table->HostCursorMaxPos = inner_window->DC.CursorMaxPos;
  255. inner_window->ParentWorkRect = inner_window->WorkRect;
  256. // Borders
  257. // - None ........Content..... Pad .....Content........
  258. // - OuterV | Pad ..Content..... Pad .....Content.. Pad | // FIXME-TABLE: Not handled properly
  259. // - InnerV ........Content.. Pad | Pad ..Content........ // FIXME-TABLE: Not handled properly
  260. // - OuterV+InnerV | Pad ..Content.. Pad | Pad ..Content.. Pad |
  261. const bool has_cell_padding_x = (flags & ImGuiTableFlags_BordersOuterV) != 0;
  262. table->CellPaddingX1 = has_cell_padding_x ? g.Style.CellPadding.x + 1.0f : 0.0f;
  263. table->CellPaddingX2 = has_cell_padding_x ? g.Style.CellPadding.x : 0.0f;
  264. table->CellPaddingY = g.Style.CellPadding.y;
  265. table->CellSpacingX = has_cell_padding_x ? 0.0f : g.Style.CellPadding.x;
  266. table->CurrentColumn = -1;
  267. table->CurrentRow = -1;
  268. table->RowBgColorCounter = 0;
  269. table->LastRowFlags = ImGuiTableRowFlags_None;
  270. table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect;
  271. table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width
  272. table->InnerClipRect.ClipWith(table->HostClipRect);
  273. table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : inner_window->ClipRect.Max.y;
  274. table->BackgroundClipRect = table->InnerClipRect;
  275. table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow
  276. table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow()
  277. table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any
  278. table->FreezeColumnsRequest = table->FreezeColumnsCount = 0;
  279. table->IsFreezeRowsPassed = true;
  280. table->DeclColumnsCount = 0;
  281. table->RightMostVisibleColumn = -1;
  282. // Using opaque colors facilitate overlapping elements of the grid
  283. table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong);
  284. table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight);
  285. table->BorderX1 = table->InnerClipRect.Min.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : -1.0f);
  286. table->BorderX2 = table->InnerClipRect.Max.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : +1.0f);
  287. // Make table current
  288. const int table_idx = g.Tables.GetIndex(table);
  289. g.CurrentTableStack.push_back(ImGuiPtrOrIndex(table_idx));
  290. g.CurrentTable = table;
  291. outer_window->DC.CurrentTableIdx = table_idx;
  292. if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly.
  293. inner_window->DC.CurrentTableIdx = table_idx;
  294. if ((table_last_flags & ImGuiTableFlags_Reorderable) && !(flags & ImGuiTableFlags_Reorderable))
  295. table->IsResetDisplayOrderRequest = true;
  296. // Setup memory buffer (clear data if columns count changed)
  297. const int stored_size = table->Columns.size();
  298. if (stored_size != 0 && stored_size != columns_count)
  299. table->RawData.resize(0);
  300. if (table->RawData.Size == 0)
  301. TableBeginInitMemory(table, columns_count);
  302. // Load settings
  303. if (table->IsSettingsRequestLoad)
  304. TableLoadSettings(table);
  305. // Handle DPI/font resize
  306. // This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well.
  307. // It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition.
  308. // FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory.
  309. // This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path.
  310. const float new_ref_scale_unit = g.FontSize; // g.Font->GetCharAdvance('A') ?
  311. if (table->RefScale != 0.0f && table->RefScale != new_ref_scale_unit)
  312. {
  313. const float scale_factor = new_ref_scale_unit / table->RefScale;
  314. //IMGUI_DEBUG_LOG("[table] %08X RefScaleUnit %.3f -> %.3f, scaling width by %.3f\n", table->ID, table->RefScaleUnit, new_ref_scale_unit, scale_factor);
  315. for (int n = 0; n < columns_count; n++)
  316. table->Columns[n].WidthRequest = table->Columns[n].WidthRequest * scale_factor;
  317. }
  318. table->RefScale = new_ref_scale_unit;
  319. // Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call..
  320. // This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user.
  321. // Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option.
  322. inner_window->SkipItems = true;
  323. // Update/lock which columns will be Visible for the frame
  324. TableBeginUpdateColumns(table);
  325. return true;
  326. }
  327. void ImGui::TableBeginUpdateColumns(ImGuiTable* table)
  328. {
  329. // Handle resizing request
  330. // (We process this at the first TableBegin of the frame)
  331. // FIXME-TABLE: Preserve contents width _while resizing down_ until releasing.
  332. // FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling.
  333. if (table->InstanceCurrent == 0)
  334. {
  335. if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX)
  336. TableSetColumnWidth(table, &table->Columns[table->ResizedColumn], table->ResizedColumnNextWidth);
  337. table->LastResizedColumn = table->ResizedColumn;
  338. table->ResizedColumnNextWidth = FLT_MAX;
  339. table->ResizedColumn = -1;
  340. }
  341. // Handle reordering request
  342. // Note: we don't clear ReorderColumn after handling the request.
  343. if (table->InstanceCurrent == 0)
  344. {
  345. if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1)
  346. table->ReorderColumn = -1;
  347. table->HeldHeaderColumn = -1;
  348. if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0)
  349. {
  350. // We need to handle reordering across hidden columns.
  351. // In the configuration below, moving C to the right of E will lead to:
  352. // ... C [D] E ---> ... [D] E C (Column name/index)
  353. // ... 2 3 4 ... 2 3 4 (Display order)
  354. const int reorder_dir = table->ReorderColumnDir;
  355. IM_ASSERT(reorder_dir == -1 || reorder_dir == +1);
  356. IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable);
  357. ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn];
  358. ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevVisibleColumn : src_column->NextVisibleColumn];
  359. IM_UNUSED(dst_column);
  360. const int src_order = src_column->DisplayOrder;
  361. const int dst_order = dst_column->DisplayOrder;
  362. src_column->DisplayOrder = (ImS8)dst_order;
  363. for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir)
  364. table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImS8)reorder_dir;
  365. IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir);
  366. // Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[],
  367. // rebuild the later from the former.
  368. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  369. table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImS8)column_n;
  370. table->ReorderColumnDir = 0;
  371. table->IsSettingsDirty = true;
  372. }
  373. }
  374. // Handle display order reset request
  375. if (table->IsResetDisplayOrderRequest)
  376. {
  377. for (int n = 0; n < table->ColumnsCount; n++)
  378. table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImS8)n;
  379. table->IsResetDisplayOrderRequest = false;
  380. table->IsSettingsDirty = true;
  381. }
  382. // Setup and lock Visible state and order
  383. table->ColumnsVisibleCount = 0;
  384. table->IsDefaultDisplayOrder = true;
  385. ImGuiTableColumn* last_visible_column = NULL;
  386. bool want_column_auto_fit = false;
  387. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  388. {
  389. const int column_n = table->DisplayOrderToIndex[order_n];
  390. if (column_n != order_n)
  391. table->IsDefaultDisplayOrder = false;
  392. ImGuiTableColumn* column = &table->Columns[column_n];
  393. column->NameOffset = -1;
  394. if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide))
  395. column->IsVisibleNextFrame = true;
  396. if (column->IsVisible != column->IsVisibleNextFrame)
  397. {
  398. column->IsVisible = column->IsVisibleNextFrame;
  399. table->IsSettingsDirty = true;
  400. if (!column->IsVisible && column->SortOrder != -1)
  401. table->IsSortSpecsDirty = true;
  402. }
  403. if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_MultiSortable))
  404. table->IsSortSpecsDirty = true;
  405. if (column->AutoFitQueue != 0x00)
  406. want_column_auto_fit = true;
  407. ImU64 index_mask = (ImU64)1 << column_n;
  408. ImU64 display_order_mask = (ImU64)1 << column->DisplayOrder;
  409. if (column->IsVisible)
  410. {
  411. column->PrevVisibleColumn = column->NextVisibleColumn = -1;
  412. if (last_visible_column)
  413. {
  414. last_visible_column->NextVisibleColumn = (ImS8)column_n;
  415. column->PrevVisibleColumn = (ImS8)table->Columns.index_from_ptr(last_visible_column);
  416. }
  417. column->IndexWithinVisibleSet = (ImS8)table->ColumnsVisibleCount;
  418. table->ColumnsVisibleCount++;
  419. table->VisibleMaskByIndex |= index_mask;
  420. table->VisibleMaskByDisplayOrder |= display_order_mask;
  421. last_visible_column = column;
  422. }
  423. else
  424. {
  425. column->IndexWithinVisibleSet = -1;
  426. table->VisibleMaskByIndex &= ~index_mask;
  427. table->VisibleMaskByDisplayOrder &= ~display_order_mask;
  428. }
  429. IM_ASSERT(column->IndexWithinVisibleSet <= column->DisplayOrder);
  430. }
  431. table->VisibleUnclippedMaskByIndex = table->VisibleMaskByIndex; // Columns will be masked out by TableUpdateLayout() when Clipped
  432. table->RightMostVisibleColumn = (ImS8)(last_visible_column ? table->Columns.index_from_ptr(last_visible_column) : -1);
  433. // Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible to avoid
  434. // the column fitting to wait until the first visible frame of the child container (may or not be a good thing).
  435. if (want_column_auto_fit && table->OuterWindow != table->InnerWindow)
  436. table->InnerWindow->SkipItems = false;
  437. }
  438. void ImGui::TableSetupScrollFreeze(int columns, int rows)
  439. {
  440. ImGuiContext& g = *GImGui;
  441. ImGuiTable* table = g.CurrentTable;
  442. IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!");
  443. IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!");
  444. IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS);
  445. IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit
  446. table->FreezeColumnsRequest = (table->Flags & ImGuiTableFlags_ScrollX) ? (ImS8)columns : 0;
  447. table->FreezeColumnsCount = (table->InnerWindow->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0;
  448. table->FreezeRowsRequest = (table->Flags & ImGuiTableFlags_ScrollY) ? (ImS8)rows : 0;
  449. table->FreezeRowsCount = (table->InnerWindow->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0;
  450. table->IsFreezeRowsPassed = (table->FreezeRowsCount == 0); // Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it.b
  451. }
  452. void ImGui::TableUpdateDrawChannels(ImGuiTable* table)
  453. {
  454. // Allocate draw channels.
  455. // - We allocate them following storage order instead of display order so reordering columns won't needlessly
  456. // increase overall dormant memory cost.
  457. // - We isolate headers draw commands in their own channels instead of just altering clip rects.
  458. // This is in order to facilitate merging of draw commands.
  459. // - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels.
  460. // - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other
  461. // channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged.
  462. // Draw channel allocation (before merging):
  463. // - NoClip --> 1+1 channels: background + foreground (same clip rect == 1 draw call)
  464. // - Clip --> 1+N channels
  465. // - FreezeRows || FreezeColumns --> 1+N*2 (unless scrolling value is zero)
  466. // - FreezeRows && FreezeColunns --> 2+N*2 (unless scrolling value is zero)
  467. const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1;
  468. const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClip) ? 1 : table->ColumnsVisibleCount;
  469. const int channels_for_background = 1;
  470. const int channels_for_dummy = (table->ColumnsVisibleCount < table->ColumnsCount || table->VisibleUnclippedMaskByIndex != table->VisibleMaskByIndex) ? +1 : 0;
  471. const int channels_total = channels_for_background + (channels_for_row * freeze_row_multiplier) + channels_for_dummy;
  472. table->DrawSplitter.Split(table->InnerWindow->DrawList, channels_total);
  473. table->DummyDrawChannel = channels_for_dummy ? (ImS8)(channels_total - 1) : -1;
  474. int draw_channel_current = 1;
  475. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  476. {
  477. ImGuiTableColumn* column = &table->Columns[column_n];
  478. if (!column->IsClipped)
  479. {
  480. column->DrawChannelFrozen = (ImS8)(draw_channel_current);
  481. column->DrawChannelUnfrozen = (ImS8)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row : 0));
  482. if (!(table->Flags & ImGuiTableFlags_NoClip))
  483. draw_channel_current++;
  484. }
  485. else
  486. {
  487. column->DrawChannelFrozen = column->DrawChannelUnfrozen = table->DummyDrawChannel;
  488. }
  489. column->DrawChannelCurrent = column->DrawChannelFrozen;
  490. }
  491. }
  492. // Adjust flags: default width mode + stretch columns are not allowed when auto extending
  493. static ImGuiTableColumnFlags TableFixColumnFlags(ImGuiTable* table, ImGuiTableColumnFlags flags)
  494. {
  495. // Sizing Policy
  496. if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0)
  497. {
  498. // FIXME-TABLE: Inconsistent to promote columns to WidthAlwaysAutoResize
  499. if (table->Flags & ImGuiTableFlags_SizingPolicyFixedX)
  500. flags |= ((table->Flags & ImGuiTableFlags_Resizable) && !(flags & ImGuiTableColumnFlags_NoResize)) ? ImGuiTableColumnFlags_WidthFixed : ImGuiTableColumnFlags_WidthAlwaysAutoResize;
  501. else
  502. flags |= ImGuiTableColumnFlags_WidthStretch;
  503. }
  504. IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_WidthMask_)); // Check that only 1 of each set is used.
  505. if ((flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize))// || ((flags & ImGuiTableColumnFlags_WidthStretch) && (table->Flags & ImGuiTableFlags_SizingPolicyStretchX)))
  506. flags |= ImGuiTableColumnFlags_NoResize;
  507. //if ((flags & ImGuiTableColumnFlags_WidthStretch) && (table->Flags & ImGuiTableFlags_SizingPolicyFixedX))
  508. // flags = (flags & ~ImGuiTableColumnFlags_WidthMask_) | ImGuiTableColumnFlags_WidthFixed;
  509. // Sorting
  510. if ((flags & ImGuiTableColumnFlags_NoSortAscending) && (flags & ImGuiTableColumnFlags_NoSortDescending))
  511. flags |= ImGuiTableColumnFlags_NoSort;
  512. // Alignment
  513. //if ((flags & ImGuiTableColumnFlags_AlignMask_) == 0)
  514. // flags |= ImGuiTableColumnFlags_AlignCenter;
  515. //IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_AlignMask_)); // Check that only 1 of each set is used.
  516. return flags;
  517. }
  518. static void TableFixColumnSortDirection(ImGuiTableColumn* column)
  519. {
  520. // Initial sort state
  521. if (column->SortDirection == ImGuiSortDirection_None)
  522. column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending);
  523. // Handle NoSortAscending/NoSortDescending
  524. if (column->SortDirection == ImGuiSortDirection_Ascending && (column->Flags & ImGuiTableColumnFlags_NoSortAscending))
  525. column->SortDirection = ImGuiSortDirection_Descending;
  526. else if (column->SortDirection == ImGuiSortDirection_Descending && (column->Flags & ImGuiTableColumnFlags_NoSortDescending))
  527. column->SortDirection = ImGuiSortDirection_Ascending;
  528. }
  529. static float TableGetMinColumnWidth()
  530. {
  531. ImGuiContext& g = *GImGui;
  532. // return g.Style.ColumnsMinSpacing;
  533. return g.Style.FramePadding.x * 3.0f;
  534. }
  535. // Layout columns for the frame
  536. // Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() to be called first.
  537. // FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for WidthAlwaysAutoResize
  538. // columns, increase feedback side-effect with widgets relying on WorkRect.Max.x. Maybe provide a default distribution
  539. // for WidthAlwaysAutoResize columns?
  540. void ImGui::TableUpdateLayout(ImGuiTable* table)
  541. {
  542. ImGuiContext& g = *GImGui;
  543. IM_ASSERT(table->IsLayoutLocked == false);
  544. table->HoveredColumnBody = -1;
  545. table->HoveredColumnBorder = -1;
  546. // Compute offset, clip rect for the frame
  547. // (can't make auto padding larger than what WorkRect knows about so right-alignment matches)
  548. const ImRect work_rect = table->WorkRect;
  549. const float padding_auto_x = table->CellPaddingX2;
  550. const float min_column_width = TableGetMinColumnWidth();
  551. int count_fixed = 0;
  552. float sum_weights_stretched = 0.0f; // Sum of all weights for weighted columns.
  553. float sum_width_fixed_requests = 0.0f; // Sum of all width for fixed and auto-resize columns, excluding width contributed by Stretch columns.
  554. table->LeftMostStretchedColumnDisplayOrder = -1;
  555. table->ColumnsAutoFitWidth = 0.0f;
  556. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  557. {
  558. if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n)))
  559. continue;
  560. const int column_n = table->DisplayOrderToIndex[order_n];
  561. ImGuiTableColumn* column = &table->Columns[column_n];
  562. // Adjust flags: default width mode + weighted columns are not allowed when auto extending
  563. // FIXME-TABLE: Clarify why we need to do this again here and not just in TableSetupColumn()
  564. column->Flags = TableFixColumnFlags(table, column->FlagsIn);
  565. if ((column->Flags & ImGuiTableColumnFlags_IndentMask_) == 0)
  566. column->Flags |= (column_n == 0) ? ImGuiTableColumnFlags_IndentEnable : ImGuiTableColumnFlags_IndentDisable;
  567. // We have a unusual edge case where if the user doesn't call TableGetSortSpecs() but has sorting enabled
  568. // or varying sorting flags, we still want the sorting arrows to honor those flags.
  569. if (table->Flags & ImGuiTableFlags_Sortable)
  570. TableFixColumnSortDirection(column);
  571. // Calculate "ideal" column width for nothing to be clipped.
  572. // Combine width from regular rows + width from headers unless requested not to.
  573. const float column_content_width_rows = (float)ImMax(column->ContentWidthFrozen, column->ContentWidthUnfrozen);
  574. const float column_content_width_headers = (float)column->ContentWidthHeadersIdeal;
  575. float column_width_ideal = column_content_width_rows;
  576. if (!(table->Flags & ImGuiTableFlags_NoHeadersWidth) && !(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth))
  577. column_width_ideal = ImMax(column_width_ideal, column_content_width_headers);
  578. column_width_ideal = ImMax(column_width_ideal + padding_auto_x, min_column_width);
  579. // Non-resizable columns also submit their requested width
  580. if (column->Flags & ImGuiTableColumnFlags_WidthFixed)
  581. if (column->WidthOrWeightInitValue > 0.0f)
  582. if (!(table->Flags & ImGuiTableFlags_Resizable) || !(column->Flags & ImGuiTableColumnFlags_NoResize))
  583. column_width_ideal = ImMax(column_width_ideal, column->WidthOrWeightInitValue);
  584. // CellSpacingX is >0.0f when there's no vertical border
  585. table->ColumnsAutoFitWidth += column_width_ideal;
  586. if (column->PrevVisibleColumn != -1)
  587. table->ColumnsAutoFitWidth += table->CellSpacingX;
  588. if (column->Flags & (ImGuiTableColumnFlags_WidthAlwaysAutoResize | ImGuiTableColumnFlags_WidthFixed))
  589. {
  590. // Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!)
  591. count_fixed += 1;
  592. if ((column->AutoFitQueue != 0x00) || ((column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize) && !column->IsClipped))
  593. column->WidthRequest = column_width_ideal;
  594. // FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets
  595. // (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very
  596. // large height (= first frame scrollbar display very off + clipper would skip lots of items).
  597. // This is merely making the side-effect less extreme, but doesn't properly fixes it.
  598. // FIXME: Move this to ->WidthGiven to avoid temporary lossyless?
  599. if (column->AutoFitQueue > 0x01 && table->IsInitializing)
  600. column->WidthRequest = ImMax(column->WidthRequest, min_column_width * 4.0f);
  601. sum_width_fixed_requests += column->WidthRequest;
  602. }
  603. else
  604. {
  605. IM_ASSERT(column->Flags & ImGuiTableColumnFlags_WidthStretch);
  606. const int init_size = (column->WidthStretchWeight < 0.0f);
  607. if (init_size)
  608. column->WidthStretchWeight = 1.0f;
  609. sum_weights_stretched += column->WidthStretchWeight;
  610. if (table->LeftMostStretchedColumnDisplayOrder == -1)
  611. table->LeftMostStretchedColumnDisplayOrder = (ImS8)column->DisplayOrder;
  612. }
  613. }
  614. // Layout
  615. const float width_spacings = table->CellSpacingX * (table->ColumnsVisibleCount - 1);
  616. float width_avail;
  617. if ((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f)
  618. width_avail = table->InnerClipRect.GetWidth() - width_spacings;
  619. else
  620. width_avail = work_rect.GetWidth() - width_spacings;
  621. const float width_avail_for_stretched_columns = width_avail - sum_width_fixed_requests;
  622. float width_remaining_for_stretched_columns = width_avail_for_stretched_columns;
  623. // Apply final width based on requested widths
  624. // Mark some columns as not resizable
  625. int count_resizable = 0;
  626. table->ColumnsTotalWidth = width_spacings;
  627. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  628. {
  629. if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n)))
  630. continue;
  631. ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]];
  632. // Allocate width for stretched/weighted columns
  633. if (column->Flags & ImGuiTableColumnFlags_WidthStretch)
  634. {
  635. // WidthStretchWeight gets converted into WidthRequest
  636. float weight_ratio = column->WidthStretchWeight / sum_weights_stretched;
  637. column->WidthRequest = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, min_column_width) + 0.01f);
  638. width_remaining_for_stretched_columns -= column->WidthRequest;
  639. // [Resize Rule 2] Resizing from right-side of a stretch column preceding a fixed column
  640. // needs to forward resizing to left-side of fixed column. We also need to copy the NoResize flag..
  641. if (column->NextVisibleColumn != -1)
  642. if (ImGuiTableColumn* next_column = &table->Columns[column->NextVisibleColumn])
  643. if (next_column->Flags & ImGuiTableColumnFlags_WidthFixed)
  644. column->Flags |= (next_column->Flags & ImGuiTableColumnFlags_NoDirectResize_);
  645. }
  646. // [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column
  647. // (see comments in TableResizeColumn())
  648. if (column->NextVisibleColumn == -1 && table->LeftMostStretchedColumnDisplayOrder != -1)
  649. column->Flags |= ImGuiTableColumnFlags_NoDirectResize_;
  650. if (!(column->Flags & ImGuiTableColumnFlags_NoResize))
  651. count_resizable++;
  652. // Assign final width, record width in case we will need to shrink
  653. column->WidthGiven = ImFloor(ImMax(column->WidthRequest, min_column_width));
  654. table->ColumnsTotalWidth += column->WidthGiven;
  655. }
  656. #if 0
  657. const float width_excess = table->ColumnsTotalWidth - work_rect.GetWidth();
  658. if ((table->Flags & ImGuiTableFlags_SizingPolicyStretchX) && width_excess > 0.0f)
  659. {
  660. // Shrink widths when the total does not fit
  661. // FIXME-TABLE: This is working but confuses/conflicts with manual resizing.
  662. // FIXME-TABLE: Policy to shrink down below below ideal/requested width if there's no room?
  663. g.ShrinkWidthBuffer.resize(table->ColumnsVisibleCount);
  664. for (int order_n = 0, visible_n = 0; order_n < table->ColumnsCount; order_n++)
  665. {
  666. if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n)))
  667. continue;
  668. const int column_n = table->DisplayOrder[order_n];
  669. g.ShrinkWidthBuffer[visible_n].Index = column_n;
  670. g.ShrinkWidthBuffer[visible_n].Width = table->Columns[column_n].WidthGiven;
  671. visible_n++;
  672. }
  673. ShrinkWidths(g.ShrinkWidthBuffer.Data, g.ShrinkWidthBuffer.Size, width_excess);
  674. for (int n = 0; n < g.ShrinkWidthBuffer.Size; n++)
  675. table->Columns[g.ShrinkWidthBuffer.Data[n].Index].WidthGiven = ImMax(g.ShrinkWidthBuffer.Data[n].Width, min_column_size);
  676. // FIXME: Need to alter table->ColumnsTotalWidth
  677. }
  678. else
  679. #endif
  680. // Redistribute remainder width due to rounding (remainder width is < 1.0f * number of Stretch column).
  681. // Using right-to-left distribution (more likely to match resizing cursor), could be adjusted depending
  682. // on where the mouse cursor is and/or relative weights.
  683. // FIXME-TABLE: May be simpler to store floating width and floor final positions only
  684. // FIXME-TABLE: Make it optional? User might prefer to preserve pixel perfect same size?
  685. if (width_remaining_for_stretched_columns >= 1.0f)
  686. for (int order_n = table->ColumnsCount - 1; sum_weights_stretched > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--)
  687. {
  688. if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n)))
  689. continue;
  690. ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]];
  691. if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch))
  692. continue;
  693. column->WidthRequest += 1.0f;
  694. column->WidthGiven += 1.0f;
  695. width_remaining_for_stretched_columns -= 1.0f;
  696. }
  697. // Detect hovered column
  698. const ImRect mouse_hit_rect(table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.Max.x, ImMax(table->OuterRect.Max.y, table->OuterRect.Min.y + table->LastOuterHeight));
  699. const bool is_hovering_table = ItemHoverable(mouse_hit_rect, 0);
  700. // Setup final position, offset and clipping rectangles
  701. int visible_n = 0;
  702. float offset_x = (table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x;
  703. ImRect host_clip_rect = table->InnerClipRect;
  704. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  705. {
  706. const int column_n = table->DisplayOrderToIndex[order_n];
  707. ImGuiTableColumn* column = &table->Columns[column_n];
  708. column->NavLayerCurrent = (table->FreezeRowsCount > 0 || column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main;
  709. if (table->FreezeColumnsCount > 0 && table->FreezeColumnsCount == visible_n)
  710. offset_x += work_rect.Min.x - table->OuterRect.Min.x;
  711. if ((table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n)) == 0)
  712. {
  713. // Hidden column: clear a few fields and we are done with it for the remainder of the function.
  714. // We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper.
  715. column->MinX = column->MaxX = offset_x;
  716. column->StartX = offset_x;
  717. column->WidthGiven = 0.0f;
  718. column->ClipRect.Min.x = offset_x;
  719. column->ClipRect.Min.y = work_rect.Min.y;
  720. column->ClipRect.Max.x = offset_x;
  721. column->ClipRect.Max.y = FLT_MAX;
  722. column->ClipRect.ClipWithFull(host_clip_rect);
  723. column->IsClipped = column->SkipItems = true;
  724. continue;
  725. }
  726. float max_x = FLT_MAX;
  727. if (table->Flags & ImGuiTableFlags_ScrollX)
  728. {
  729. // Frozen columns can't reach beyond visible width else scrolling will naturally break.
  730. if (order_n < table->FreezeColumnsRequest)
  731. max_x = table->InnerClipRect.Max.x - (table->FreezeColumnsRequest - order_n) * min_column_width;
  732. }
  733. else
  734. {
  735. // If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make
  736. // sure they are all visible. Because of this we also know that all of the columns will always fit in
  737. // table->WorkRect and therefore in table->InnerRect (because ScrollX is off)
  738. if (!(table->Flags & ImGuiTableFlags_NoKeepColumnsVisible))
  739. max_x = table->WorkRect.Max.x - (table->ColumnsVisibleCount - (column->IndexWithinVisibleSet + 1)) * min_column_width;
  740. }
  741. if (offset_x + column->WidthGiven > max_x)
  742. column->WidthGiven = ImMax(max_x - offset_x, min_column_width);
  743. column->MinX = offset_x;
  744. column->MaxX = column->MinX + column->WidthGiven;
  745. //// A one pixel padding on the right side makes clipping more noticeable and contents look less cramped.
  746. column->ClipRect.Min.x = column->MinX;
  747. column->ClipRect.Min.y = work_rect.Min.y;
  748. column->ClipRect.Max.x = column->MaxX;// -1.0f;
  749. column->ClipRect.Max.y = FLT_MAX;
  750. column->ClipRect.ClipWithFull(host_clip_rect);
  751. column->IsClipped = (column->ClipRect.Max.x <= column->ClipRect.Min.x) && (column->AutoFitQueue & 1) == 0 && (column->CannotSkipItemsQueue & 1) == 0;
  752. if (column->IsClipped)
  753. table->VisibleUnclippedMaskByIndex &= ~((ImU64)1 << column_n); // Columns with the _WidthAlwaysAutoResize sizing policy will never be updated then.
  754. column->SkipItems = !column->IsVisible || table->HostSkipItems;
  755. // Detect hovered column
  756. if (is_hovering_table && g.IO.MousePos.x >= column->ClipRect.Min.x && g.IO.MousePos.x < column->ClipRect.Max.x)
  757. table->HoveredColumnBody = (ImS8)column_n;
  758. // Starting cursor position
  759. column->StartX = column->MinX + table->CellPaddingX1;
  760. // Alignment
  761. // FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in
  762. // many cases (to be able to honor this we might be able to store a log of cells width, per row, for
  763. // visible rows, but nav/programmatic scroll would have visible artifacts.)
  764. //if (column->Flags & ImGuiTableColumnFlags_AlignRight)
  765. // column->StartX = ImMax(column->StartX, column->MaxX - column->ContentWidthRowsUnfrozen);
  766. //else if (column->Flags & ImGuiTableColumnFlags_AlignCenter)
  767. // column->StartX = ImLerp(column->StartX, ImMax(column->StartX, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f);
  768. // Reset content width variables
  769. const float initial_max_pos_x = column->MinX + table->CellPaddingX1;
  770. column->ContentMaxPosFrozen = column->ContentMaxPosUnfrozen = initial_max_pos_x;
  771. column->ContentMaxPosHeadersUsed = column->ContentMaxPosHeadersIdeal = initial_max_pos_x;
  772. // Don't decrement auto-fit counters until container window got a chance to submit its items
  773. if (table->HostSkipItems == false)
  774. {
  775. column->AutoFitQueue >>= 1;
  776. column->CannotSkipItemsQueue >>= 1;
  777. }
  778. if (visible_n < table->FreezeColumnsCount)
  779. host_clip_rect.Min.x = ImMax(host_clip_rect.Min.x, column->MaxX + 2.0f);
  780. offset_x += column->WidthGiven + table->CellSpacingX;
  781. visible_n++;
  782. }
  783. // Detect/store when we are hovering the unused space after the right-most column (so e.g. context menus can react on it)
  784. if (is_hovering_table && table->HoveredColumnBody == -1)
  785. {
  786. float unused_x1 = table->WorkRect.Min.x;
  787. if (table->RightMostVisibleColumn != -1)
  788. unused_x1 = ImMax(unused_x1, table->Columns[table->RightMostVisibleColumn].ClipRect.Max.x);
  789. if (g.IO.MousePos.x >= unused_x1)
  790. table->HoveredColumnBody = (ImS8)table->ColumnsCount;
  791. }
  792. // Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag,
  793. // either because of using _WidthAlwaysAutoResize/_WidthStretch).
  794. // This will hide the resizing option from the context menu.
  795. if (count_resizable == 0 && (table->Flags & ImGuiTableFlags_Resizable))
  796. table->Flags &= ~ImGuiTableFlags_Resizable;
  797. // Allocate draw channels
  798. TableUpdateDrawChannels(table);
  799. // Borders
  800. if (table->Flags & ImGuiTableFlags_Resizable)
  801. TableUpdateBorders(table);
  802. // Reset fields after we used them in TableSetupResize()
  803. table->LastFirstRowHeight = 0.0f;
  804. table->IsLayoutLocked = true;
  805. table->IsUsingHeaders = false;
  806. // Context menu
  807. if (table->IsContextPopupOpen && table->InstanceCurrent == table->InstanceInteracted)
  808. {
  809. const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID);
  810. if (BeginPopupEx(context_menu_id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings))
  811. {
  812. TableDrawContextMenu(table);
  813. EndPopup();
  814. }
  815. else
  816. {
  817. table->IsContextPopupOpen = false;
  818. }
  819. }
  820. // Initial state
  821. ImGuiWindow* inner_window = table->InnerWindow;
  822. if (table->Flags & ImGuiTableFlags_NoClip)
  823. table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 1);
  824. else
  825. inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false);
  826. // Sanitize and build sort specs before we have a change to use them for display.
  827. // This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change)
  828. if (table->IsSortSpecsDirty && (table->Flags & ImGuiTableFlags_Sortable))
  829. TableSortSpecsBuild(table);
  830. }
  831. // Process interaction on resizing borders. Actual size change will be applied in EndTable()
  832. // - Set table->HoveredColumnBorder with a short delay/timer to reduce feedback noise
  833. // - Submit ahead of table contents and header, use ImGuiButtonFlags_AllowItemOverlap to prioritize widgets
  834. // overlapping the same area.
  835. void ImGui::TableUpdateBorders(ImGuiTable* table)
  836. {
  837. ImGuiContext& g = *GImGui;
  838. IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable);
  839. // At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and
  840. // use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not
  841. // really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height).
  842. // Actual columns highlight/render will be performed in EndTable() and not be affected.
  843. const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS;
  844. const float hit_y1 = table->OuterRect.Min.y;
  845. const float hit_y2_body = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight);
  846. const float hit_y2_head = hit_y1 + table->LastFirstRowHeight;
  847. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  848. {
  849. if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n)))
  850. continue;
  851. const int column_n = table->DisplayOrderToIndex[order_n];
  852. ImGuiTableColumn* column = &table->Columns[column_n];
  853. if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_))
  854. continue;
  855. // ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders()
  856. const float border_y2_hit = (table->Flags & ImGuiTableFlags_NoBordersInBody) ? hit_y2_head : hit_y2_body;
  857. if ((table->Flags & ImGuiTableFlags_NoBordersInBody) && table->IsUsingHeaders == false)
  858. continue;
  859. ImGuiID column_id = TableGetColumnResizeID(table, column_n, table->InstanceCurrent);
  860. ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, border_y2_hit);
  861. //GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100));
  862. KeepAliveID(column_id);
  863. bool hovered = false, held = false;
  864. bool pressed = ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick);
  865. if (pressed && IsMouseDoubleClicked(0) && !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
  866. {
  867. // FIXME-TABLE: Double-clicking on column edge could auto-fit Stretch column?
  868. TableSetColumnAutofit(table, column_n);
  869. ClearActiveID();
  870. held = hovered = false;
  871. }
  872. if (held)
  873. {
  874. table->ResizedColumn = (ImS8)column_n;
  875. table->InstanceInteracted = table->InstanceCurrent;
  876. }
  877. if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held)
  878. {
  879. table->HoveredColumnBorder = (ImS8)column_n;
  880. SetMouseCursor(ImGuiMouseCursor_ResizeEW);
  881. }
  882. }
  883. }
  884. void ImGui::EndTable()
  885. {
  886. ImGuiContext& g = *GImGui;
  887. ImGuiTable* table = g.CurrentTable;
  888. IM_ASSERT(table != NULL && "Only call EndTable() if BeginTable() returns true!");
  889. // This assert would be very useful to catch a common error... unfortunately it would probably trigger in some
  890. // cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border)
  891. //IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?");
  892. // If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our
  893. // code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc.
  894. if (!table->IsLayoutLocked)
  895. TableUpdateLayout(table);
  896. const ImGuiTableFlags flags = table->Flags;
  897. ImGuiWindow* inner_window = table->InnerWindow;
  898. ImGuiWindow* outer_window = table->OuterWindow;
  899. IM_ASSERT(inner_window == g.CurrentWindow);
  900. IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow);
  901. if (table->IsInsideRow)
  902. TableEndRow(table);
  903. // Context menu in columns body
  904. if (flags & ImGuiTableFlags_ContextMenuInBody)
  905. if (table->HoveredColumnBody != -1 && !ImGui::IsAnyItemHovered() && ImGui::IsMouseReleased(ImGuiMouseButton_Right))
  906. TableOpenContextMenu((int)table->HoveredColumnBody);
  907. // Finalize table height
  908. inner_window->SkipItems = table->HostSkipItems;
  909. inner_window->DC.CursorMaxPos = table->HostCursorMaxPos;
  910. if (inner_window != outer_window)
  911. {
  912. table->OuterRect.Max.y = ImMax(table->OuterRect.Max.y, inner_window->Pos.y + inner_window->Size.y);
  913. inner_window->DC.CursorMaxPos.y = table->RowPosY2;
  914. }
  915. else if (!(flags & ImGuiTableFlags_NoHostExtendY))
  916. {
  917. table->OuterRect.Max.y = ImMax(table->OuterRect.Max.y, inner_window->DC.CursorPos.y);
  918. inner_window->DC.CursorMaxPos.y = table->RowPosY2;
  919. }
  920. table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y);
  921. table->LastOuterHeight = table->OuterRect.GetHeight();
  922. if (!(flags & ImGuiTableFlags_NoClip))
  923. inner_window->DrawList->PopClipRect();
  924. inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back();
  925. // Draw borders
  926. if ((flags & ImGuiTableFlags_Borders) != 0)
  927. TableDrawBorders(table);
  928. // Store content width reference for each column (before attempting to merge draw calls)
  929. const float backup_outer_cursor_pos_x = outer_window->DC.CursorPos.x;
  930. const float backup_outer_max_pos_x = outer_window->DC.CursorMaxPos.x;
  931. const float backup_inner_max_pos_x = inner_window->DC.CursorMaxPos.x;
  932. float max_pos_x = backup_inner_max_pos_x;
  933. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  934. {
  935. ImGuiTableColumn* column = &table->Columns[column_n];
  936. // Store content width (for both Headers and Rows)
  937. float ref_x = column->StartX - table->CellPaddingX1;
  938. column->ContentWidthFrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosFrozen - ref_x);
  939. column->ContentWidthUnfrozen = (ImS16)ImMax(0.0f, column->ContentMaxPosUnfrozen - ref_x);
  940. column->ContentWidthHeadersUsed = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersUsed - ref_x);
  941. column->ContentWidthHeadersIdeal = (ImS16)ImMax(0.0f, column->ContentMaxPosHeadersIdeal - ref_x);
  942. // Add an extra 1 pixel so we can see the last column vertical line if it lies on the right-most edge.
  943. if (table->VisibleMaskByIndex & ((ImU64)1 << column_n))
  944. max_pos_x = ImMax(max_pos_x, column->MaxX);
  945. }
  946. // Flatten channels and merge draw calls
  947. table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 0);
  948. if ((table->Flags & ImGuiTableFlags_NoClip) == 0)
  949. TableReorderDrawChannelsForMerge(table);
  950. table->DrawSplitter.Merge(inner_window->DrawList);
  951. // When releasing a column being resized, scroll to keep the resulting column in sight
  952. const float min_column_width = TableGetMinColumnWidth();
  953. if (!(table->Flags & ImGuiTableFlags_ScrollX) && inner_window != outer_window)
  954. {
  955. inner_window->Scroll.x = 0.0f;
  956. }
  957. else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceCurrent)
  958. {
  959. ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn];
  960. if (column->MaxX < table->InnerClipRect.Min.x)
  961. SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x - min_column_width, 1.0f);
  962. else if (column->MaxX > table->InnerClipRect.Max.x)
  963. SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x + min_column_width, 1.0f);
  964. }
  965. // Apply resizing/dragging at the end of the frame
  966. if (table->ResizedColumn != -1)
  967. {
  968. ImGuiTableColumn* column = &table->Columns[table->ResizedColumn];
  969. const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + TABLE_RESIZE_SEPARATOR_HALF_THICKNESS);
  970. const float new_width = ImFloor(new_x2 - column->MinX);
  971. table->ResizedColumnNextWidth = new_width;
  972. }
  973. // Layout in outer window
  974. IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table->ID + table->InstanceCurrent, "Mismatching PushID/PopID!");
  975. PopID();
  976. inner_window->WorkRect = inner_window->ParentWorkRect;
  977. inner_window->ParentWorkRect = table->HostBackupParentWorkRect;
  978. inner_window->SkipItems = table->HostSkipItems;
  979. outer_window->DC.CursorPos = table->OuterRect.Min;
  980. outer_window->DC.ColumnsOffset = table->HostBackupColumnsOffset;
  981. if (inner_window != outer_window)
  982. {
  983. EndChild();
  984. }
  985. else
  986. {
  987. ImVec2 item_size = table->OuterRect.GetSize();
  988. item_size.x = table->ColumnsTotalWidth;
  989. ItemSize(item_size);
  990. }
  991. // Override EndChild/ItemSize max extent with our own to enable auto-resize on the X axis when possible
  992. // FIXME-TABLE: This can be improved (e.g. for Fixed columns we don't want to auto AutoFitWidth? or propagate window auto-fit to table?)
  993. if (table->Flags & ImGuiTableFlags_ScrollX)
  994. {
  995. inner_window->DC.CursorMaxPos.x = max_pos_x; // Set contents width for scrolling
  996. outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos_x, backup_outer_cursor_pos_x + table->ColumnsTotalWidth + inner_window->ScrollbarSizes.x); // For auto-fit
  997. }
  998. else
  999. {
  1000. outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos_x, table->WorkRect.Min.x + table->ColumnsAutoFitWidth); // For auto-fit
  1001. }
  1002. // Save settings
  1003. if (table->IsSettingsDirty)
  1004. TableSaveSettings(table);
  1005. // Clear or restore current table, if any
  1006. IM_ASSERT(g.CurrentWindow == outer_window);
  1007. IM_ASSERT(g.CurrentTable == table);
  1008. g.CurrentTableStack.pop_back();
  1009. g.CurrentTable = g.CurrentTableStack.Size ? g.Tables.GetByIndex(g.CurrentTableStack.back().Index) : NULL;
  1010. outer_window->DC.CurrentTableIdx = g.CurrentTable ? g.Tables.GetIndex(g.CurrentTable) : -1;
  1011. }
  1012. // FIXME-TABLE: This is a mess, need to redesign how we render borders.
  1013. void ImGui::TableDrawBorders(ImGuiTable* table)
  1014. {
  1015. ImGuiWindow* inner_window = table->InnerWindow;
  1016. ImGuiWindow* outer_window = table->OuterWindow;
  1017. table->DrawSplitter.SetCurrentChannel(inner_window->DrawList, 0);
  1018. if (inner_window->Hidden || !table->HostClipRect.Overlaps(table->InnerClipRect))
  1019. return;
  1020. ImDrawList* inner_drawlist = inner_window->DrawList;
  1021. ImDrawList* outer_drawlist = outer_window->DrawList;
  1022. // Draw inner border and resizing feedback
  1023. const float border_size = TABLE_BORDER_SIZE;
  1024. const float draw_y1 = table->OuterRect.Min.y;
  1025. const float draw_y2_body = table->OuterRect.Max.y;
  1026. const float draw_y2_head = table->IsUsingHeaders ? ((table->FreezeRowsCount >= 1 ? table->OuterRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight) : draw_y1;
  1027. if (table->Flags & ImGuiTableFlags_BordersInnerV)
  1028. {
  1029. for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
  1030. {
  1031. if (!(table->VisibleMaskByDisplayOrder & ((ImU64)1 << order_n)))
  1032. continue;
  1033. const int column_n = table->DisplayOrderToIndex[order_n];
  1034. ImGuiTableColumn* column = &table->Columns[column_n];
  1035. const bool is_hovered = (table->HoveredColumnBorder == column_n);
  1036. const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent);
  1037. const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0;
  1038. if (column->MaxX > table->InnerClipRect.Max.x && !is_resized && is_hovered)
  1039. continue;
  1040. if (column->NextVisibleColumn == -1 && !is_resizable)
  1041. continue;
  1042. if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size..
  1043. continue;
  1044. // Draw in outer window so right-most column won't be clipped
  1045. // Always draw full height border when being resized/hovered, or on the delimitation of frozen column scrolling.
  1046. ImU32 col;
  1047. float draw_y2;
  1048. if (is_hovered || is_resized || (table->FreezeColumnsCount != -1 && table->FreezeColumnsCount == order_n + 1))
  1049. {
  1050. draw_y2 = draw_y2_body;
  1051. col = is_resized ? GetColorU32(ImGuiCol_SeparatorActive) : is_hovered ? GetColorU32(ImGuiCol_SeparatorHovered) : table->BorderColorStrong;
  1052. }
  1053. else
  1054. {
  1055. draw_y2 = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? draw_y2_head : draw_y2_body;
  1056. col = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? table->BorderColorStrong : table->BorderColorLight;
  1057. }
  1058. if (draw_y2 > draw_y1)
  1059. inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, border_size);
  1060. }
  1061. }
  1062. // Draw outer border
  1063. if (table->Flags & ImGuiTableFlags_BordersOuter)
  1064. {
  1065. // Display outer border offset by 1 which is a simple way to display it without adding an extra draw call
  1066. // (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their
  1067. // parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part
  1068. // of it in inner window, and the part that's over scrollbars in the outer window..)
  1069. // Either solution currently won't allow us to use a larger border size: the border would clipped.
  1070. ImRect outer_border = table->OuterRect;
  1071. const ImU32 outer_col = table->BorderColorStrong;
  1072. if (inner_window != outer_window)
  1073. outer_border.Expand(1.0f);
  1074. if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter)
  1075. {
  1076. outer_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, ~0, border_size);
  1077. }
  1078. else if (table->Flags & ImGuiTableFlags_BordersOuterV)
  1079. {
  1080. outer_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Min.x, outer_border.Max.y), outer_col, border_size);
  1081. outer_drawlist->AddLine(ImVec2(outer_border.Max.x, outer_border.Min.y), outer_border.Max, outer_col, border_size);
  1082. }
  1083. else if (table->Flags & ImGuiTableFlags_BordersOuterH)
  1084. {
  1085. outer_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Max.x, outer_border.Min.y), outer_col, border_size);
  1086. outer_drawlist->AddLine(ImVec2(outer_border.Min.x, outer_border.Max.y), outer_border.Max, outer_col, border_size);
  1087. }
  1088. }
  1089. if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y)
  1090. {
  1091. // Draw bottom-most row border
  1092. const float border_y = table->RowPosY2;
  1093. if (border_y >= table->BackgroundClipRect.Min.y && border_y < table->BackgroundClipRect.Max.y)
  1094. inner_drawlist->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderColorLight, border_size);
  1095. }
  1096. }
  1097. static void TableUpdateColumnsWeightFromWidth(ImGuiTable* table)
  1098. {
  1099. IM_ASSERT(table->LeftMostStretchedColumnDisplayOrder != -1);
  1100. // Measure existing quantity
  1101. float visible_weight = 0.0f;
  1102. float visible_width = 0.0f;
  1103. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1104. {
  1105. ImGuiTableColumn* column = &table->Columns[column_n];
  1106. if (!column->IsVisible || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
  1107. continue;
  1108. visible_weight += column->WidthStretchWeight;
  1109. visible_width += column->WidthRequest;
  1110. }
  1111. IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f);
  1112. // Apply new weights
  1113. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1114. {
  1115. ImGuiTableColumn* column = &table->Columns[column_n];
  1116. if (!column->IsVisible || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
  1117. continue;
  1118. column->WidthStretchWeight = ((column->WidthRequest + 0.0f) / visible_width) * visible_weight;
  1119. }
  1120. }
  1121. // Public wrapper
  1122. void ImGui::TableSetColumnWidth(int column_n, float width)
  1123. {
  1124. ImGuiContext& g = *GImGui;
  1125. ImGuiTable* table = g.CurrentTable;
  1126. IM_ASSERT(table != NULL);
  1127. IM_ASSERT(table->IsLayoutLocked == false);
  1128. IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
  1129. TableSetColumnWidth(table, &table->Columns[column_n], width);
  1130. }
  1131. // [Internal]
  1132. void ImGui::TableSetColumnWidth(ImGuiTable* table, ImGuiTableColumn* column_0, float column_0_width)
  1133. {
  1134. // Constraints
  1135. float min_width = TableGetMinColumnWidth();
  1136. float max_width_0 = FLT_MAX;
  1137. if (!(table->Flags & ImGuiTableFlags_ScrollX))
  1138. max_width_0 = (table->WorkRect.Max.x - column_0->MinX) - (table->ColumnsVisibleCount - (column_0->IndexWithinVisibleSet + 1)) * min_width;
  1139. column_0_width = ImClamp(column_0_width, min_width, max_width_0);
  1140. // Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded)
  1141. if (column_0->WidthGiven == column_0_width || column_0->WidthRequest == column_0_width)
  1142. return;
  1143. ImGuiTableColumn* column_1 = (column_0->NextVisibleColumn != -1) ? &table->Columns[column_0->NextVisibleColumn] : NULL;
  1144. // In this surprisingly not simple because of how we support mixing Fixed and Stretch columns.
  1145. // When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1.
  1146. // FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user.
  1147. // Scenarios:
  1148. // - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset.
  1149. // - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered.
  1150. // - F1 F2 W3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size.
  1151. // - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
  1152. // - W1 W2 W3 resize from W1| or W2| --> FIXME
  1153. // - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
  1154. // - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1)
  1155. // - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1)
  1156. // - W1 W2 F3 resize from W1| or W2| --> ok
  1157. // - W1 F2 W3 resize from W1| or F2| --> FIXME
  1158. // - F1 W2 F3 resize from W2| --> ok
  1159. // - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move. (forwarded by Resize Rule 2)
  1160. // - W1 F2 F3 resize from F2| --> FIXME should resize F2, F3 and not have effect on W1 (Stretch columns are _before_ the Fixed column).
  1161. // Rules:
  1162. // - [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout().
  1163. // - [Resize Rule 2] Resizing from right-side of a Stretch column before a fixed column forward sizing to left-side of fixed column.
  1164. // - [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.
  1165. table->IsSettingsDirty = true;
  1166. if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed)
  1167. {
  1168. // [Resize Rule 3] If we are are followed by a fixed column and we have a Stretch column before, we need to ensure
  1169. // that our left border won't move, which we can do by making sure column_a/column_b resizes cancels each others.
  1170. if (column_1 && (column_1->Flags & ImGuiTableColumnFlags_WidthFixed))
  1171. if (table->LeftMostStretchedColumnDisplayOrder != -1 && table->LeftMostStretchedColumnDisplayOrder < column_0->DisplayOrder)
  1172. {
  1173. // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b)
  1174. float column_1_width = ImMax(column_1->WidthRequest - (column_0_width - column_0->WidthRequest), min_width);
  1175. column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width;
  1176. column_1->WidthRequest = column_1_width;
  1177. }
  1178. // Apply
  1179. //IMGUI_DEBUG_LOG("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthRequested, column_0_width);
  1180. column_0->WidthRequest = column_0_width;
  1181. }
  1182. else if (column_0->Flags & ImGuiTableColumnFlags_WidthStretch)
  1183. {
  1184. // [Resize Rule 2]
  1185. if (column_1 && (column_1->Flags & ImGuiTableColumnFlags_WidthFixed))
  1186. {
  1187. float off = (column_0->WidthGiven - column_0_width);
  1188. float column_1_width = column_1->WidthGiven + off;
  1189. column_1->WidthRequest = ImMax(min_width, column_1_width);
  1190. return;
  1191. }
  1192. // (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b)
  1193. float column_1_width = ImMax(column_1->WidthRequest - (column_0_width - column_0->WidthRequest), min_width);
  1194. column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width;
  1195. column_1->WidthRequest = column_1_width;
  1196. column_0->WidthRequest = column_0_width;
  1197. TableUpdateColumnsWeightFromWidth(table);
  1198. }
  1199. }
  1200. // This function reorder draw channels based on matching clip rectangle, to facilitate merging them.
  1201. //
  1202. // Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve
  1203. // this we merge their clip rect and make them contiguous in the channel list, so they can be merged
  1204. // by the call to DrawSplitter.Merge() following to the call to this function.
  1205. //
  1206. // We reorder draw commands by arranging them into a maximum of 4 distinct groups:
  1207. //
  1208. // 1 group: 2 groups: 2 groups: 4 groups:
  1209. // [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 02 ] row+col freeze
  1210. // [ .. ] or no scroll [ 1. ] and v-scroll [ .. ] and h-scroll [ 13 ] and v+h-scroll
  1211. //
  1212. // Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled).
  1213. // When the contents of a column didn't stray off its limit, we move its channels into the corresponding group
  1214. // based on its position (within frozen rows/columns groups or not).
  1215. // At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect.
  1216. //
  1217. // This function assume that each column are pointing to a distinct draw channel,
  1218. // otherwise merge_group->ChannelsCount will not match set bit count of merge_group->ChannelsMask.
  1219. //
  1220. // Column channels will not be merged into one of the 1-4 groups in the following cases:
  1221. // - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value).
  1222. // Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds
  1223. // matches, by e.g. calling SetCursorScreenPos().
  1224. // - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here..
  1225. // we could do better but it's going to be rare and probably not worth the hassle.
  1226. // Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd.
  1227. //
  1228. // This function is particularly tricky to understand.. take a breath.
  1229. void ImGui::TableReorderDrawChannelsForMerge(ImGuiTable* table)
  1230. {
  1231. ImGuiContext& g = *GImGui;
  1232. ImDrawListSplitter* splitter = &table->DrawSplitter;
  1233. const bool is_frozen_v = (table->FreezeRowsCount > 0);
  1234. const bool is_frozen_h = (table->FreezeColumnsCount > 0);
  1235. // Track which groups we are going to attempt to merge, and which channels goes into each group.
  1236. struct MergeGroup
  1237. {
  1238. ImRect ClipRect;
  1239. int ChannelsCount;
  1240. ImBitArray<IMGUI_TABLE_MAX_DRAW_CHANNELS> ChannelsMask;
  1241. };
  1242. int merge_group_mask = 0x00;
  1243. MergeGroup merge_groups[4];
  1244. memset(merge_groups, 0, sizeof(merge_groups));
  1245. // 1. Scan channels and take note of those which can be merged
  1246. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1247. {
  1248. if (!(table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)))
  1249. continue;
  1250. ImGuiTableColumn* column = &table->Columns[column_n];
  1251. const int merge_group_sub_count = is_frozen_v ? 2 : 1;
  1252. for (int merge_group_sub_n = 0; merge_group_sub_n < merge_group_sub_count; merge_group_sub_n++)
  1253. {
  1254. const int channel_no = (merge_group_sub_n == 0) ? column->DrawChannelFrozen : column->DrawChannelUnfrozen;
  1255. // Don't attempt to merge if there are multiple draw calls within the column
  1256. ImDrawChannel* src_channel = &splitter->_Channels[channel_no];
  1257. if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0)
  1258. src_channel->_CmdBuffer.pop_back();
  1259. if (src_channel->_CmdBuffer.Size != 1)
  1260. continue;
  1261. // Find out the width of this merge group and check if it will fit in our column
  1262. // (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it)
  1263. if (!(column->Flags & ImGuiTableColumnFlags_NoClipX))
  1264. {
  1265. float width_contents;
  1266. if (merge_group_sub_count == 1) // No row freeze (same as testing !is_frozen_v)
  1267. width_contents = ImMax(column->ContentWidthUnfrozen, column->ContentWidthHeadersUsed);
  1268. else if (merge_group_sub_n == 0) // Row freeze: use width before freeze
  1269. width_contents = ImMax(column->ContentWidthFrozen, column->ContentWidthHeadersUsed);
  1270. else // Row freeze: use width after freeze
  1271. width_contents = column->ContentWidthUnfrozen;
  1272. if (width_contents > column->WidthGiven)
  1273. continue;
  1274. }
  1275. const int merge_group_n = (is_frozen_h && column_n < table->FreezeColumnsCount ? 0 : 2) + (is_frozen_v ? merge_group_sub_n : 1);
  1276. IM_ASSERT(channel_no < IMGUI_TABLE_MAX_DRAW_CHANNELS);
  1277. MergeGroup* merge_group = &merge_groups[merge_group_n];
  1278. if (merge_group->ChannelsCount == 0)
  1279. merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
  1280. merge_group->ChannelsMask.SetBit(channel_no);
  1281. merge_group->ChannelsCount++;
  1282. merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect);
  1283. merge_group_mask |= (1 << merge_group_n);
  1284. }
  1285. // Invalidate current draw channel
  1286. // (we don't clear DrawChannelBeforeRowFreeze/DrawChannelAfterRowFreeze solely to facilitate debugging/later inspection of data)
  1287. column->DrawChannelCurrent = -1;
  1288. }
  1289. // [DEBUG] Display merge groups
  1290. #if 0
  1291. if (g.IO.KeyShift)
  1292. for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++)
  1293. {
  1294. MergeGroup* merge_group = &merge_groups[merge_group_n];
  1295. if (merge_group->ChannelsCount == 0)
  1296. continue;
  1297. char buf[32];
  1298. ImFormatString(buf, 32, "MG%d:%d", merge_group_n, merge_group->ChannelsCount);
  1299. ImVec2 text_pos = merge_group->ClipRect.Min + ImVec2(4, 4);
  1300. ImVec2 text_size = CalcTextSize(buf, NULL);
  1301. GetForegroundDrawList()->AddRectFilled(text_pos, text_pos + text_size, IM_COL32(0, 0, 0, 255));
  1302. GetForegroundDrawList()->AddText(text_pos, IM_COL32(255, 255, 0, 255), buf, NULL);
  1303. GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 255, 0, 255));
  1304. }
  1305. #endif
  1306. // 2. Rewrite channel list in our preferred order
  1307. if (merge_group_mask != 0)
  1308. {
  1309. // Use shared temporary storage so the allocation gets amortized
  1310. g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - 1);
  1311. ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data;
  1312. ImBitArray<IMGUI_TABLE_MAX_DRAW_CHANNELS> remaining_mask; // We need 130-bit of storage
  1313. remaining_mask.ClearBits();
  1314. remaining_mask.SetBitRange(1, splitter->_Count - 1); // Background channel 0 not part of the merge (see channel allocation in TableUpdateDrawChannels)
  1315. int remaining_count = splitter->_Count - 1;
  1316. for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++)
  1317. if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount)
  1318. {
  1319. MergeGroup* merge_group = &merge_groups[merge_group_n];
  1320. ImRect merge_clip_rect = merge_group->ClipRect;
  1321. // Extend outer-most clip limits to match those of host, so draw calls can be merged even if
  1322. // outer-most columns have some outer padding offsetting them from their parent ClipRect.
  1323. // The principal cases this is dealing with are:
  1324. // - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge
  1325. // - Columns can use padding and have left-most ClipRect.Min.x and right-most ClipRect.Max.x != from host ClipRect -> will extend and match host ClipRect -> will merge
  1326. // FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit
  1327. // within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect.
  1328. if ((merge_group_n & 2) == 0 || !is_frozen_h)
  1329. merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, table->HostClipRect.Min.x);
  1330. if ((merge_group_n & 1) == 0 || !is_frozen_v)
  1331. merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, table->HostClipRect.Min.y);
  1332. if ((merge_group_n & 2) != 0)
  1333. merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, table->HostClipRect.Max.x);
  1334. if ((merge_group_n & 1) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0)
  1335. merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, table->HostClipRect.Max.y);
  1336. #if 0
  1337. GetOverlayDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, ~0, 1.0f);
  1338. GetOverlayDrawList()->AddLine(merge_group->ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200));
  1339. GetOverlayDrawList()->AddLine(merge_group->ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200));
  1340. #endif
  1341. remaining_count -= merge_group->ChannelsCount;
  1342. for (int n = 0; n < IM_ARRAYSIZE(remaining_mask.Storage); n++)
  1343. remaining_mask.Storage[n] &= ~merge_group->ChannelsMask.Storage[n];
  1344. for (int n = 0; n < splitter->_Count && merge_channels_count != 0; n++)
  1345. {
  1346. // Copy + overwrite new clip rect
  1347. if (!merge_group->ChannelsMask.TestBit(n))
  1348. continue;
  1349. merge_group->ChannelsMask.ClearBit(n);
  1350. merge_channels_count--;
  1351. ImDrawChannel* channel = &splitter->_Channels[n];
  1352. IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect)));
  1353. channel->_CmdBuffer[0].ClipRect = merge_clip_rect.ToVec4();
  1354. memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));
  1355. }
  1356. }
  1357. // Append unmergeable channels that we didn't reorder at the end of the list
  1358. for (int n = 0; n < splitter->_Count && remaining_count != 0; n++)
  1359. {
  1360. if (!remaining_mask.TestBit(n))
  1361. continue;
  1362. ImDrawChannel* channel = &splitter->_Channels[n];
  1363. memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));
  1364. remaining_count--;
  1365. }
  1366. IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size);
  1367. memcpy(splitter->_Channels.Data + 1, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - 1) * sizeof(ImDrawChannel));
  1368. }
  1369. }
  1370. // We use a default parameter of 'init_width_or_weight == -1'
  1371. // ImGuiTableColumnFlags_WidthFixed, width <= 0 --> init width == auto
  1372. // ImGuiTableColumnFlags_WidthFixed, width > 0 --> init width == manual
  1373. // ImGuiTableColumnFlags_WidthStretch, weight < 0 --> init weight == 1.0f
  1374. // ImGuiTableColumnFlags_WidthStretch, weight >= 0 --> init weight == custom
  1375. // Use a different API?
  1376. void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id)
  1377. {
  1378. ImGuiContext& g = *GImGui;
  1379. ImGuiTable* table = g.CurrentTable;
  1380. IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!");
  1381. IM_ASSERT(table->IsLayoutLocked == false && "Need to call call TableSetupColumn() before first row!");
  1382. IM_ASSERT(table->DeclColumnsCount >= 0 && table->DeclColumnsCount < table->ColumnsCount && "Called TableSetupColumn() too many times!");
  1383. ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount];
  1384. table->DeclColumnsCount++;
  1385. // When passing a width automatically enforce WidthFixed policy
  1386. // (vs TableFixColumnFlags would default to WidthAlwaysAutoResize)
  1387. // (we write to FlagsIn which is a little misleading, another solution would be to pass init_width_or_weight to TableFixColumnFlags)
  1388. if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0)
  1389. if ((table->Flags & ImGuiTableFlags_SizingPolicyFixedX) && (init_width_or_weight > 0.0f))
  1390. flags |= ImGuiTableColumnFlags_WidthFixed;
  1391. column->UserID = user_id;
  1392. column->FlagsIn = flags;
  1393. column->Flags = TableFixColumnFlags(table, column->FlagsIn);
  1394. flags = column->Flags;
  1395. // Initialize defaults
  1396. if (flags & ImGuiTableColumnFlags_WidthStretch)
  1397. {
  1398. IM_ASSERT(init_width_or_weight != 0.0f && "Need to provide a valid weight!");
  1399. if (init_width_or_weight < 0.0f)
  1400. init_width_or_weight = 1.0f;
  1401. }
  1402. column->WidthOrWeightInitValue = init_width_or_weight;
  1403. if (table->IsInitializing && column->WidthRequest < 0.0f && column->WidthStretchWeight < 0.0f)
  1404. {
  1405. // Init width or weight
  1406. if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f)
  1407. {
  1408. // Disable auto-fit if a default fixed width has been specified
  1409. column->WidthRequest = init_width_or_weight;
  1410. column->AutoFitQueue = 0x00;
  1411. }
  1412. if (flags & ImGuiTableColumnFlags_WidthStretch)
  1413. column->WidthStretchWeight = init_width_or_weight;
  1414. else
  1415. column->WidthStretchWeight = 1.0f;
  1416. }
  1417. if (table->IsInitializing)
  1418. {
  1419. // Init default visibility/sort state
  1420. if ((flags & ImGuiTableColumnFlags_DefaultHide) && (table->SettingsLoadedFlags & ImGuiTableFlags_Hideable) == 0)
  1421. column->IsVisible = column->IsVisibleNextFrame = false;
  1422. if (flags & ImGuiTableColumnFlags_DefaultSort && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0)
  1423. {
  1424. column->SortOrder = 0; // Multiple columns using _DefaultSort will be reordered when building the sort specs.
  1425. column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending);
  1426. }
  1427. }
  1428. // Store name (append with zero-terminator in contiguous buffer)
  1429. IM_ASSERT(column->NameOffset == -1);
  1430. if (label != NULL)
  1431. {
  1432. column->NameOffset = (ImS16)table->ColumnsNames.size();
  1433. table->ColumnsNames.append(label, label + strlen(label) + 1);
  1434. }
  1435. }
  1436. // Starts into the first cell of a new row
  1437. void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float row_min_height)
  1438. {
  1439. ImGuiContext& g = *GImGui;
  1440. ImGuiTable* table = g.CurrentTable;
  1441. if (table->CurrentRow == -1)
  1442. TableUpdateLayout(table);
  1443. else if (table->IsInsideRow)
  1444. TableEndRow(table);
  1445. table->LastRowFlags = table->RowFlags;
  1446. table->RowFlags = row_flags;
  1447. table->RowMinHeight = row_min_height;
  1448. TableBeginRow(table);
  1449. // We honor min_row_height requested by user, but cannot guarantee per-row maximum height,
  1450. // because that would essentially require a unique clipping rectangle per-cell.
  1451. table->RowPosY2 += table->CellPaddingY * 2.0f;
  1452. table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + row_min_height);
  1453. // Disable output until user calls TableNextColumn()
  1454. table->InnerWindow->SkipItems = true;
  1455. }
  1456. // [Internal]
  1457. void ImGui::TableBeginRow(ImGuiTable* table)
  1458. {
  1459. ImGuiWindow* window = table->InnerWindow;
  1460. IM_ASSERT(!table->IsInsideRow);
  1461. // New row
  1462. table->CurrentRow++;
  1463. table->CurrentColumn = -1;
  1464. table->RowBgColor[0] = table->RowBgColor[1] = IM_COL32_DISABLE;
  1465. table->RowCellDataCurrent = -1;
  1466. table->IsInsideRow = true;
  1467. // Begin frozen rows
  1468. float next_y1 = table->RowPosY2;
  1469. if (table->CurrentRow == 0 && table->FreezeRowsCount > 0)
  1470. next_y1 = window->DC.CursorPos.y = table->OuterRect.Min.y;
  1471. table->RowPosY1 = table->RowPosY2 = next_y1;
  1472. table->RowTextBaseline = 0.0f;
  1473. table->RowIndentOffsetX = window->DC.Indent.x - table->HostIndentX; // Lock indent
  1474. window->DC.PrevLineTextBaseOffset = 0.0f;
  1475. window->DC.CursorMaxPos.y = next_y1;
  1476. // Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging.
  1477. if (table->RowFlags & ImGuiTableRowFlags_Headers)
  1478. {
  1479. TableSetBgColor(ImGuiTableBgTarget_RowBg0, GetColorU32(ImGuiCol_TableHeaderBg));
  1480. if (table->CurrentRow == 0)
  1481. table->IsUsingHeaders = true;
  1482. }
  1483. }
  1484. // [Internal]
  1485. void ImGui::TableEndRow(ImGuiTable* table)
  1486. {
  1487. ImGuiContext& g = *GImGui;
  1488. ImGuiWindow* window = g.CurrentWindow;
  1489. IM_ASSERT(window == table->InnerWindow);
  1490. IM_ASSERT(table->IsInsideRow);
  1491. if (table->CurrentColumn != -1)
  1492. TableEndCell(table);
  1493. // Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is
  1494. // likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding.
  1495. window->DC.CursorPos.y = table->RowPosY2;
  1496. // Row background fill
  1497. const float bg_y1 = table->RowPosY1;
  1498. const float bg_y2 = table->RowPosY2;
  1499. const bool unfreeze_rows_actual = (table->CurrentRow + 1 == table->FreezeRowsCount);
  1500. const bool unfreeze_rows_request = (table->CurrentRow + 1 == table->FreezeRowsRequest);
  1501. if (table->CurrentRow == 0)
  1502. table->LastFirstRowHeight = bg_y2 - bg_y1;
  1503. const bool is_visible = (bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y);
  1504. if (is_visible)
  1505. {
  1506. // Decide of background color for the row
  1507. ImU32 bg_col0 = 0;
  1508. ImU32 bg_col1 = 0;
  1509. if (table->RowBgColor[0] != IM_COL32_DISABLE)
  1510. bg_col0 = table->RowBgColor[0];
  1511. else if (table->Flags & ImGuiTableFlags_RowBg)
  1512. bg_col0 = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg);
  1513. if (table->RowBgColor[1] != IM_COL32_DISABLE)
  1514. bg_col1 = table->RowBgColor[1];
  1515. // Decide of top border color
  1516. ImU32 border_col = 0;
  1517. const float border_size = TABLE_BORDER_SIZE;
  1518. if (table->CurrentRow != 0 || table->InnerWindow == table->OuterWindow)
  1519. if (table->Flags & ImGuiTableFlags_BordersInnerH)
  1520. if (table->CurrentRow > 0)
  1521. border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight;
  1522. const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0;
  1523. const bool draw_strong_bottom_border = unfreeze_rows_actual;
  1524. if ((bg_col0 | bg_col1 | border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color)
  1525. {
  1526. // In theory we could call SetWindowClipRectBeforeChannelChange() but since we know TableEndRow() is
  1527. // always followed by a change of clipping rectangle we perform the smallest overwrite possible here.
  1528. window->DrawList->_CmdHeader.ClipRect = table->HostClipRect.ToVec4();
  1529. table->DrawSplitter.SetCurrentChannel(window->DrawList, 0);
  1530. }
  1531. // Draw row background
  1532. // We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle
  1533. if (bg_col0 || bg_col1)
  1534. {
  1535. ImRect row_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2);
  1536. row_rect.ClipWith(table->BackgroundClipRect);
  1537. if (bg_col0 != 0 && row_rect.Min.y < row_rect.Max.y)
  1538. window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col0);
  1539. if (bg_col1 != 0 && row_rect.Min.y < row_rect.Max.y)
  1540. window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col1);
  1541. }
  1542. // Draw cell background color
  1543. if (draw_cell_bg_color)
  1544. {
  1545. ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCurrent];
  1546. for (ImGuiTableCellData* cell_data = &table->RowCellData[0]; cell_data <= cell_data_end; cell_data++)
  1547. {
  1548. ImGuiTableColumn* column = &table->Columns[cell_data->Column];
  1549. ImRect cell_rect(column->MinX - table->CellSpacingX, bg_y1, column->MaxX, bg_y2); // FIXME-TABLE: Padding currently wrong until we finish the padding refactor
  1550. cell_rect.ClipWith(table->BackgroundClipRect);
  1551. window->DrawList->AddRectFilled(cell_rect.Min, cell_rect.Max, cell_data->BgColor);
  1552. }
  1553. }
  1554. // Draw top border
  1555. if (border_col && bg_y1 >= table->BackgroundClipRect.Min.y && bg_y1 < table->BackgroundClipRect.Max.y)
  1556. window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y1), ImVec2(table->BorderX2, bg_y1), border_col, border_size);
  1557. // Draw bottom border at the row unfreezing mark (always strong)
  1558. if (draw_strong_bottom_border)
  1559. if (bg_y2 >= table->BackgroundClipRect.Min.y && bg_y2 < table->BackgroundClipRect.Max.y)
  1560. window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong, border_size);
  1561. }
  1562. // End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle)
  1563. // We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and
  1564. // get the new cursor position.
  1565. if (unfreeze_rows_request)
  1566. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1567. {
  1568. ImGuiTableColumn* column = &table->Columns[column_n];
  1569. column->NavLayerCurrent = (column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main;
  1570. }
  1571. if (unfreeze_rows_actual)
  1572. {
  1573. IM_ASSERT(table->IsFreezeRowsPassed == false);
  1574. table->IsFreezeRowsPassed = true;
  1575. table->DrawSplitter.SetCurrentChannel(window->DrawList, 0);
  1576. // BackgroundClipRect starts as table->InnerClipRect, reduce it now
  1577. float y0 = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y);
  1578. table->BackgroundClipRect.Min.y = y0;
  1579. table->BackgroundClipRect.Max.y = window->InnerClipRect.Max.y;
  1580. float row_height = table->RowPosY2 - table->RowPosY1;
  1581. table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y;
  1582. table->RowPosY1 = table->RowPosY2 - row_height;
  1583. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  1584. {
  1585. ImGuiTableColumn* column = &table->Columns[column_n];
  1586. column->DrawChannelCurrent = column->DrawChannelUnfrozen;
  1587. column->ClipRect.Min.y = table->BackgroundClipRect.Min.y;
  1588. }
  1589. // Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y
  1590. SetWindowClipRectBeforeSetChannel(window, table->Columns[0].ClipRect);
  1591. table->DrawSplitter.SetCurrentChannel(window->DrawList, table->Columns[0].DrawChannelCurrent);
  1592. }
  1593. if (!(table->RowFlags & ImGuiTableRowFlags_Headers))
  1594. table->RowBgColorCounter++;
  1595. table->IsInsideRow = false;
  1596. }
  1597. // [Internal] Called by TableNextColumn()!
  1598. // This is called very frequently, so we need to be mindful of unnecessary overhead.
  1599. // FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns.
  1600. void ImGui::TableBeginCell(ImGuiTable* table, int column_n)
  1601. {
  1602. table->CurrentColumn = column_n;
  1603. ImGuiTableColumn* column = &table->Columns[column_n];
  1604. ImGuiWindow* window = table->InnerWindow;
  1605. // Start position is roughly ~~ CellRect.Min + CellPadding + Indent
  1606. float start_x = column->StartX;
  1607. if (column->Flags & ImGuiTableColumnFlags_IndentEnable)
  1608. start_x += table->RowIndentOffsetX; // ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row.
  1609. window->DC.CursorPos.x = start_x;
  1610. window->DC.CursorPos.y = table->RowPosY1 + table->CellPaddingY;
  1611. window->DC.CursorMaxPos.x = window->DC.CursorPos.x;
  1612. window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT
  1613. window->DC.CurrLineTextBaseOffset = table->RowTextBaseline;
  1614. window->DC.LastItemId = 0;
  1615. window->DC.NavLayerCurrent = column->NavLayerCurrent;
  1616. window->WorkRect.Min.y = window->DC.CursorPos.y;
  1617. window->WorkRect.Min.x = column->MinX + table->CellPaddingX1;
  1618. window->WorkRect.Max.x = column->MaxX - table->CellPaddingX2;
  1619. // To allow ImGuiListClipper to function we propagate our row height
  1620. if (!column->IsVisible)
  1621. window->DC.CursorPos.y = ImMax(window->DC.CursorPos.y, table->RowPosY2);
  1622. window->SkipItems = column->SkipItems;
  1623. if (table->Flags & ImGuiTableFlags_NoClip)
  1624. {
  1625. table->DrawSplitter.SetCurrentChannel(window->DrawList, 1);
  1626. }
  1627. else
  1628. {
  1629. SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
  1630. table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
  1631. }
  1632. }
  1633. // [Internal] Called by TableNextRow()/TableNextColumn()!
  1634. void ImGui::TableEndCell(ImGuiTable* table)
  1635. {
  1636. ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
  1637. ImGuiWindow* window = table->InnerWindow;
  1638. // Report maximum position so we can infer content size per column.
  1639. float* p_max_pos_x;
  1640. if (table->RowFlags & ImGuiTableRowFlags_Headers)
  1641. p_max_pos_x = &column->ContentMaxPosHeadersUsed; // Useful in case user submit contents in header row that is not a TableHeader() call
  1642. else
  1643. p_max_pos_x = table->IsFreezeRowsPassed ? &column->ContentMaxPosUnfrozen : &column->ContentMaxPosFrozen;
  1644. *p_max_pos_x = ImMax(*p_max_pos_x, window->DC.CursorMaxPos.x);
  1645. table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y + table->CellPaddingY);
  1646. // Propagate text baseline for the entire row
  1647. // FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one.
  1648. table->RowTextBaseline = ImMax(table->RowTextBaseline, window->DC.PrevLineTextBaseOffset);
  1649. }
  1650. // Append into the next cell
  1651. // FIXME-TABLE: Wrapping to next row should be optional?
  1652. bool ImGui::TableNextColumn()
  1653. {
  1654. ImGuiContext& g = *GImGui;
  1655. ImGuiTable* table = g.CurrentTable;
  1656. if (!table)
  1657. return false;
  1658. if (table->IsInsideRow && table->CurrentColumn + 1 < table->ColumnsCount)
  1659. {
  1660. if (table->CurrentColumn != -1)
  1661. TableEndCell(table);
  1662. TableBeginCell(table, table->CurrentColumn + 1);
  1663. }
  1664. else
  1665. {
  1666. TableNextRow();
  1667. TableBeginCell(table, 0);
  1668. }
  1669. // FIXME-TABLE: Need to clarify if we want to allow IsItemHovered() here
  1670. //g.CurrentWindow->DC.LastItemStatusFlags = (column_n == table->HoveredColumn) ? ImGuiItemStatusFlags_HoveredRect : ImGuiItemStatusFlags_None;
  1671. // FIXME-TABLE: it is likely to alter layout if user skips a columns contents based on clipping.
  1672. int column_n = table->CurrentColumn;
  1673. return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0;
  1674. }
  1675. bool ImGui::TableSetColumnIndex(int column_n)
  1676. {
  1677. ImGuiContext& g = *GImGui;
  1678. ImGuiTable* table = g.CurrentTable;
  1679. if (!table)
  1680. return false;
  1681. if (table->CurrentColumn != column_n)
  1682. {
  1683. if (table->CurrentColumn != -1)
  1684. TableEndCell(table);
  1685. IM_ASSERT(column_n >= 0 && table->ColumnsCount);
  1686. TableBeginCell(table, column_n);
  1687. }
  1688. // FIXME-TABLE: Need to clarify if we want to allow IsItemHovered() here
  1689. //g.CurrentWindow->DC.LastItemStatusFlags = (column_n == table->HoveredColumn) ? ImGuiItemStatusFlags_HoveredRect : ImGuiItemStatusFlags_None;
  1690. // FIXME-TABLE: it is likely to alter layout if user skips a columns contents based on clipping.
  1691. return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0;
  1692. }
  1693. int ImGui::TableGetColumnCount()
  1694. {
  1695. ImGuiContext& g = *GImGui;
  1696. ImGuiTable* table = g.CurrentTable;
  1697. return table ? table->ColumnsCount : 0;
  1698. }
  1699. const char* ImGui::TableGetColumnName(int column_n)
  1700. {
  1701. ImGuiContext& g = *GImGui;
  1702. ImGuiTable* table = g.CurrentTable;
  1703. if (!table)
  1704. return NULL;
  1705. if (column_n < 0)
  1706. column_n = table->CurrentColumn;
  1707. return TableGetColumnName(table, column_n);
  1708. }
  1709. // We expose "Visible and Unclipped" to the user, vs our internal "Visible" state which is !Hidden
  1710. bool ImGui::TableGetColumnIsVisible(int column_n)
  1711. {
  1712. ImGuiContext& g = *GImGui;
  1713. ImGuiTable* table = g.CurrentTable;
  1714. if (!table)
  1715. return false;
  1716. if (column_n < 0)
  1717. column_n = table->CurrentColumn;
  1718. return (table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) != 0;
  1719. }
  1720. int ImGui::TableGetColumnIndex()
  1721. {
  1722. ImGuiContext& g = *GImGui;
  1723. ImGuiTable* table = g.CurrentTable;
  1724. if (!table)
  1725. return 0;
  1726. return table->CurrentColumn;
  1727. }
  1728. // Return the cell rectangle based on currently known height.
  1729. // Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations.
  1730. // The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it.
  1731. ImRect ImGui::TableGetCellBgRect()
  1732. {
  1733. ImGuiContext& g = *GImGui;
  1734. ImGuiTable* table = g.CurrentTable;
  1735. ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
  1736. return ImRect(column->MinX, table->RowPosY1, column->MaxX, table->RowPosY2);
  1737. }
  1738. const char* ImGui::TableGetColumnName(const ImGuiTable* table, int column_n)
  1739. {
  1740. const ImGuiTableColumn* column = &table->Columns[column_n];
  1741. if (column->NameOffset == -1)
  1742. return NULL;
  1743. return &table->ColumnsNames.Buf[column->NameOffset];
  1744. }
  1745. // Return the resizing ID for the right-side of the given column.
  1746. ImGuiID ImGui::TableGetColumnResizeID(const ImGuiTable* table, int column_n, int instance_no)
  1747. {
  1748. IM_ASSERT(column_n < table->ColumnsCount);
  1749. ImGuiID id = table->ID + 1 + (instance_no * table->ColumnsCount) + column_n;
  1750. return id;
  1751. }
  1752. void ImGui::TableSetColumnAutofit(ImGuiTable* table, int column_n)
  1753. {
  1754. // Disable clipping then auto-fit, will take 2 frames
  1755. // (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns)
  1756. ImGuiTableColumn* column = &table->Columns[column_n];
  1757. column->CannotSkipItemsQueue = (1 << 0);
  1758. column->AutoFitQueue = (1 << 1);
  1759. }
  1760. void ImGui::PushTableBackground()
  1761. {
  1762. ImGuiContext& g = *GImGui;
  1763. ImGuiWindow* window = g.CurrentWindow;
  1764. ImGuiTable* table = g.CurrentTable;
  1765. // Optimization: avoid SetCurrentChannel() + PushClipRect()
  1766. table->HostBackupClipRect = window->ClipRect;
  1767. SetWindowClipRectBeforeSetChannel(window, table->HostClipRect);
  1768. table->DrawSplitter.SetCurrentChannel(window->DrawList, 0);
  1769. }
  1770. void ImGui::PopTableBackground()
  1771. {
  1772. ImGuiContext& g = *GImGui;
  1773. ImGuiWindow* window = g.CurrentWindow;
  1774. ImGuiTable* table = g.CurrentTable;
  1775. ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
  1776. // Optimization: avoid PopClipRect() + SetCurrentChannel()
  1777. SetWindowClipRectBeforeSetChannel(window, table->HostBackupClipRect);
  1778. table->DrawSplitter.SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
  1779. }
  1780. // Output context menu into current window (generally a popup)
  1781. // FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data?
  1782. void ImGui::TableDrawContextMenu(ImGuiTable* table)
  1783. {
  1784. ImGuiContext& g = *GImGui;
  1785. ImGuiWindow* window = g.CurrentWindow;
  1786. if (window->SkipItems)
  1787. return;
  1788. bool want_separator = false;
  1789. const int column_n = (table->ContextPopupColumn >= 0 && table->ContextPopupColumn < table->ColumnsCount) ? table->ContextPopupColumn : -1;
  1790. ImGuiTableColumn* column = (column_n != -1) ? &table->Columns[column_n] : NULL;
  1791. // Sizing
  1792. if (table->Flags & ImGuiTableFlags_Resizable)
  1793. {
  1794. if (column != NULL)
  1795. {
  1796. const bool can_resize = !(column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_WidthStretch)) && column->IsVisible;
  1797. if (MenuItem("Size column to fit", NULL, false, can_resize))
  1798. TableSetColumnAutofit(table, column_n);
  1799. }
  1800. if (MenuItem("Size all columns to fit", NULL))
  1801. {
  1802. for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
  1803. {
  1804. ImGuiTableColumn* other_column = &table->Columns[other_column_n];
  1805. if (other_column->IsVisible)
  1806. TableSetColumnAutofit(table, other_column_n);
  1807. }
  1808. }
  1809. want_separator = true;
  1810. }
  1811. // Ordering
  1812. if (table->Flags & ImGuiTableFlags_Reorderable)
  1813. {
  1814. if (MenuItem("Reset order", NULL, false, !table->IsDefaultDisplayOrder))
  1815. table->IsResetDisplayOrderRequest = true;
  1816. want_separator = true;
  1817. }
  1818. // Sorting
  1819. // (modify TableOpenContextMenu() to add _Sortable flag if enabling this)
  1820. #if 0
  1821. if ((table->Flags & ImGuiTableFlags_Sortable) && column != NULL && (column->Flags & ImGuiTableColumnFlags_NoSort) == 0)
  1822. {
  1823. if (want_separator)
  1824. Separator();
  1825. want_separator = true;
  1826. bool append_to_sort_specs = g.IO.KeyShift;
  1827. if (MenuItem("Sort in Ascending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Ascending, (column->Flags & ImGuiTableColumnFlags_NoSortAscending) == 0))
  1828. TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Ascending, append_to_sort_specs);
  1829. if (MenuItem("Sort in Descending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Descending, (column->Flags & ImGuiTableColumnFlags_NoSortDescending) == 0))
  1830. TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Descending, append_to_sort_specs);
  1831. }
  1832. #endif
  1833. // Hiding / Visibility
  1834. if (table->Flags & ImGuiTableFlags_Hideable)
  1835. {
  1836. if (want_separator)
  1837. Separator();
  1838. want_separator = true;
  1839. PushItemFlag(ImGuiItemFlags_SelectableDontClosePopup, true);
  1840. for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
  1841. {
  1842. ImGuiTableColumn* other_column = &table->Columns[other_column_n];
  1843. const char* name = TableGetColumnName(table, other_column_n);
  1844. if (name == NULL)
  1845. name = "<Unknown>";
  1846. // Make sure we can't hide the last active column
  1847. bool menu_item_active = (other_column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true;
  1848. if (other_column->IsVisible && table->ColumnsVisibleCount <= 1)
  1849. menu_item_active = false;
  1850. if (MenuItem(name, NULL, other_column->IsVisible, menu_item_active))
  1851. other_column->IsVisibleNextFrame = !other_column->IsVisible;
  1852. }
  1853. PopItemFlag();
  1854. }
  1855. }
  1856. // Use -1 to open menu not specific to a given column.
  1857. void ImGui::TableOpenContextMenu(int column_n)
  1858. {
  1859. ImGuiContext& g = *GImGui;
  1860. ImGuiTable* table = g.CurrentTable;
  1861. if (column_n == -1 && table->CurrentColumn != -1) // When called within a column automatically use this one (for consistency)
  1862. column_n = table->CurrentColumn;
  1863. if (column_n == table->ColumnsCount) // To facilitate using with TableGetHoveredColumn()
  1864. column_n = -1;
  1865. IM_ASSERT(column_n >= -1 && column_n < table->ColumnsCount);
  1866. if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
  1867. {
  1868. table->IsContextPopupOpen = true;
  1869. table->ContextPopupColumn = (ImS8)column_n;
  1870. table->InstanceInteracted = table->InstanceCurrent;
  1871. const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID);
  1872. OpenPopupEx(context_menu_id, ImGuiPopupFlags_None);
  1873. }
  1874. }
  1875. // This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn().
  1876. // The intent is that advanced users willing to create customized headers would not need to use this helper
  1877. // and can create their own! For example: TableHeader() may be preceeded by Checkbox() or other custom widgets.
  1878. // See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this.
  1879. void ImGui::TableHeadersRow()
  1880. {
  1881. ImGuiStyle& style = ImGui::GetStyle();
  1882. ImGuiContext& g = *GImGui;
  1883. ImGuiTable* table = g.CurrentTable;
  1884. IM_ASSERT(table != NULL && "Need to call TableHeadersRow() after BeginTable()!");
  1885. // Calculate row height (for the unlikely case that labels may be are multi-line)
  1886. // If we didn't do that, uneven header height would work but their highlight won't cover the full row height.
  1887. float row_height = GetTextLineHeight();
  1888. const float row_y1 = GetCursorScreenPos().y;
  1889. const int columns_count = TableGetColumnCount();
  1890. for (int column_n = 0; column_n < columns_count; column_n++)
  1891. if (TableGetColumnIsVisible(column_n))
  1892. row_height = ImMax(row_height, CalcTextSize(TableGetColumnName(column_n)).y);
  1893. row_height += style.CellPadding.y * 2.0f;
  1894. // Open row
  1895. TableNextRow(ImGuiTableRowFlags_Headers, row_height);
  1896. if (table->HostSkipItems) // Merely an optimization, you may skip in your own code.
  1897. return;
  1898. // This for loop is constructed to not make use of internal functions,
  1899. // as this is intended to be a base template to copy and build from.
  1900. for (int column_n = 0; column_n < columns_count; column_n++)
  1901. {
  1902. if (!TableSetColumnIndex(column_n))
  1903. continue;
  1904. // [DEBUG] Test custom user elements
  1905. #if 0
  1906. if (column_n < 2)
  1907. {
  1908. static bool b[2] = {};
  1909. PushID(column_n);
  1910. PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
  1911. Checkbox("##", &b[column_n]);
  1912. PopStyleVar();
  1913. PopID();
  1914. SameLine(0.0f, style.ItemInnerSpacing.x);
  1915. }
  1916. #endif
  1917. // Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them)
  1918. // - in your own code you may omit the PushID/PopID all-together, provided you know they won't collide
  1919. // - table->InstanceCurrent is only >0 when we use multiple BeginTable/EndTable calls with same identifier.
  1920. const char* name = TableGetColumnName(column_n);
  1921. PushID(table->InstanceCurrent * table->ColumnsCount + column_n);
  1922. TableHeader(name);
  1923. PopID();
  1924. }
  1925. // Allow opening popup from the right-most section after the last column.
  1926. // FIXME-TABLE: TableOpenContextMenu() is not public yet.
  1927. ImVec2 mouse_pos = ImGui::GetMousePos();
  1928. if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count)
  1929. if (mouse_pos.y >= row_y1 && mouse_pos.y < row_y1 + row_height)
  1930. TableOpenContextMenu(-1); // Will open a non-column-specific popup.
  1931. }
  1932. // Emit a column header (text + optional sort order)
  1933. // We cpu-clip text here so that all columns headers can be merged into a same draw call.
  1934. // Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader()
  1935. // FIXME-TABLE: Could hold a selection state.
  1936. // FIXME-TABLE: Style confusion between CellPadding.y and FramePadding.y
  1937. void ImGui::TableHeader(const char* label)
  1938. {
  1939. ImGuiContext& g = *GImGui;
  1940. ImGuiWindow* window = g.CurrentWindow;
  1941. if (window->SkipItems)
  1942. return;
  1943. ImGuiTable* table = g.CurrentTable;
  1944. IM_ASSERT(table != NULL && "Need to call TableHeader() after BeginTable()!");
  1945. IM_ASSERT(table->CurrentColumn != -1);
  1946. const int column_n = table->CurrentColumn;
  1947. ImGuiTableColumn* column = &table->Columns[column_n];
  1948. // Label
  1949. if (label == NULL)
  1950. label = "";
  1951. const char* label_end = FindRenderedTextEnd(label);
  1952. ImVec2 label_size = CalcTextSize(label, label_end, true);
  1953. ImVec2 label_pos = window->DC.CursorPos;
  1954. // If we already got a row height, there's use that.
  1955. ImRect cell_r = TableGetCellBgRect();
  1956. cell_r.Min.x -= table->CellSpacingX; // FIXME-TABLE: TableGetCellRect() is misleading.
  1957. float label_height = ImMax(label_size.y, table->RowMinHeight - g.Style.CellPadding.y * 2.0f);
  1958. //GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]
  1959. // Keep header highlighted when context menu is open.
  1960. // (FIXME-TABLE: however we cannot assume the ID of said popup if it has been created by the user...)
  1961. const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceCurrent);
  1962. ImGuiID id = window->GetID(label);
  1963. ImRect bb(cell_r.Min.x, cell_r.Min.y, cell_r.Max.x, ImMax(cell_r.Max.y, cell_r.Min.y + label_height + g.Style.CellPadding.y * 2.0f));
  1964. ItemSize(ImVec2(0.0f, label_height)); // Don't declare unclipped width, it'll be fed ContentMaxPosHeadersIdeal
  1965. if (!ItemAdd(bb, id))
  1966. return;
  1967. bool hovered, held;
  1968. bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None);
  1969. if (hovered || selected)
  1970. {
  1971. const ImU32 col = GetColorU32(held ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
  1972. RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
  1973. RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
  1974. }
  1975. if (held)
  1976. table->HeldHeaderColumn = (ImS8)column_n;
  1977. window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f;
  1978. // Drag and drop to re-order columns.
  1979. // FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone.
  1980. if (held && (table->Flags & ImGuiTableFlags_Reorderable) && IsMouseDragging(0) && !g.DragDropActive)
  1981. {
  1982. // While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x
  1983. table->ReorderColumn = (ImS8)column_n;
  1984. table->InstanceInteracted = table->InstanceCurrent;
  1985. // We don't reorder: through the frozen<>unfrozen line, or through a column that is marked with ImGuiTableColumnFlags_NoReorder.
  1986. if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x)
  1987. if (ImGuiTableColumn* prev_column = (column->PrevVisibleColumn != -1) ? &table->Columns[column->PrevVisibleColumn] : NULL)
  1988. if (!((column->Flags | prev_column->Flags) & ImGuiTableColumnFlags_NoReorder))
  1989. if ((column->IndexWithinVisibleSet < table->FreezeColumnsRequest) == (prev_column->IndexWithinVisibleSet < table->FreezeColumnsRequest))
  1990. table->ReorderColumnDir = -1;
  1991. if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x)
  1992. if (ImGuiTableColumn* next_column = (column->NextVisibleColumn != -1) ? &table->Columns[column->NextVisibleColumn] : NULL)
  1993. if (!((column->Flags | next_column->Flags) & ImGuiTableColumnFlags_NoReorder))
  1994. if ((column->IndexWithinVisibleSet < table->FreezeColumnsRequest) == (next_column->IndexWithinVisibleSet < table->FreezeColumnsRequest))
  1995. table->ReorderColumnDir = +1;
  1996. }
  1997. // Sort order arrow
  1998. float w_arrow = 0.0f;
  1999. float w_sort_text = 0.0f;
  2000. float ellipsis_max = cell_r.Max.x;
  2001. if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort))
  2002. {
  2003. const float ARROW_SCALE = 0.65f;
  2004. w_arrow = ImFloor(g.FontSize * ARROW_SCALE + g.Style.FramePadding.x);// table->CellPadding.x);
  2005. if (column->SortOrder != -1)
  2006. {
  2007. w_sort_text = 0.0f;
  2008. char sort_order_suf[8];
  2009. if (column->SortOrder > 0)
  2010. {
  2011. ImFormatString(sort_order_suf, IM_ARRAYSIZE(sort_order_suf), "%d", column->SortOrder + 1);
  2012. w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x;
  2013. }
  2014. float x = ImMax(cell_r.Min.x, cell_r.Max.x - w_arrow - w_sort_text);
  2015. ellipsis_max -= w_arrow + w_sort_text;
  2016. float y = label_pos.y;
  2017. ImU32 col = GetColorU32(ImGuiCol_Text);
  2018. if (column->SortOrder > 0)
  2019. {
  2020. PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text, 0.70f));
  2021. RenderText(ImVec2(x + g.Style.ItemInnerSpacing.x, y), sort_order_suf);
  2022. PopStyleColor();
  2023. x += w_sort_text;
  2024. }
  2025. RenderArrow(window->DrawList, ImVec2(x, y), col, column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE);
  2026. }
  2027. // Handle clicking on column header to adjust Sort Order
  2028. if (pressed && table->ReorderColumn != column_n)
  2029. {
  2030. // Set new sort direction
  2031. // - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click.
  2032. // - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op.
  2033. ImGuiSortDirection sort_direction;
  2034. if (column->SortOrder == -1)
  2035. sort_direction = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending;
  2036. else
  2037. sort_direction = (column->SortDirection == ImGuiSortDirection_Ascending) ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending;
  2038. TableSetColumnSortDirection(table, column_n, sort_direction, g.IO.KeyShift);
  2039. }
  2040. }
  2041. // Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will
  2042. // be merged into a single draw call.
  2043. //window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE);
  2044. RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, label_pos.y + label_height + g.Style.FramePadding.y), ellipsis_max, ellipsis_max, label, label_end, &label_size);
  2045. // We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering
  2046. // for merging.
  2047. // FIXME-TABLE: Clarify policies of how label width and potential decorations (arrows) fit into auto-resize of the column
  2048. float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow;
  2049. column->ContentMaxPosHeadersUsed = ImMax(column->ContentMaxPosHeadersUsed, cell_r.Max.x);// ImMin(max_pos_x, cell_r.Max.x));
  2050. column->ContentMaxPosHeadersIdeal = ImMax(column->ContentMaxPosHeadersIdeal, max_pos_x);
  2051. // We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden
  2052. if (IsMouseReleased(1) && IsItemHovered())
  2053. TableOpenContextMenu(column_n);
  2054. }
  2055. // Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert
  2056. // the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code.
  2057. void ImGui::TableSetColumnSortDirection(ImGuiTable* table, int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs)
  2058. {
  2059. if (!(table->Flags & ImGuiTableFlags_MultiSortable))
  2060. append_to_sort_specs = false;
  2061. ImS8 sort_order_max = 0;
  2062. if (append_to_sort_specs)
  2063. for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
  2064. sort_order_max = ImMax(sort_order_max, table->Columns[other_column_n].SortOrder);
  2065. ImGuiTableColumn* column = &table->Columns[column_n];
  2066. column->SortDirection = (ImS8)sort_direction;
  2067. if (column->SortOrder == -1 || !append_to_sort_specs)
  2068. column->SortOrder = append_to_sort_specs ? sort_order_max + 1 : 0;
  2069. for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
  2070. {
  2071. ImGuiTableColumn* other_column = &table->Columns[other_column_n];
  2072. if (other_column != column && !append_to_sort_specs)
  2073. other_column->SortOrder = -1;
  2074. TableFixColumnSortDirection(other_column);
  2075. }
  2076. table->IsSettingsDirty = true;
  2077. table->IsSortSpecsDirty = true;
  2078. }
  2079. // Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set)
  2080. // You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since
  2081. // last call, or the first time.
  2082. // Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()!
  2083. ImGuiTableSortSpecs* ImGui::TableGetSortSpecs()
  2084. {
  2085. ImGuiContext& g = *GImGui;
  2086. ImGuiTable* table = g.CurrentTable;
  2087. IM_ASSERT(table != NULL);
  2088. if (!(table->Flags & ImGuiTableFlags_Sortable))
  2089. return NULL;
  2090. if (table->IsSortSpecsDirty)
  2091. TableSortSpecsBuild(table);
  2092. return table->SortSpecs.SpecsCount ? &table->SortSpecs : NULL;
  2093. }
  2094. bool ImGui::TableGetColumnIsSorted(int column_n)
  2095. {
  2096. ImGuiContext& g = *GImGui;
  2097. ImGuiTable* table = g.CurrentTable;
  2098. if (!table)
  2099. return false;
  2100. if (column_n < 0)
  2101. column_n = table->CurrentColumn;
  2102. ImGuiTableColumn* column = &table->Columns[column_n];
  2103. return (column->SortOrder != -1);
  2104. }
  2105. // Return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered.
  2106. int ImGui::TableGetHoveredColumn()
  2107. {
  2108. ImGuiContext& g = *GImGui;
  2109. ImGuiTable* table = g.CurrentTable;
  2110. if (!table)
  2111. return -1;
  2112. return (int)table->HoveredColumnBody;
  2113. }
  2114. void ImGui::TableSetBgColor(ImGuiTableBgTarget bg_target, ImU32 color, int column_n)
  2115. {
  2116. ImGuiContext& g = *GImGui;
  2117. ImGuiTable* table = g.CurrentTable;
  2118. IM_ASSERT(bg_target != ImGuiTableBgTarget_None);
  2119. if (color == IM_COL32_DISABLE)
  2120. color = 0;
  2121. // We cannot draw neither the cell or row background immediately as we don't know the row height at this point in time.
  2122. switch (bg_target)
  2123. {
  2124. case ImGuiTableBgTarget_CellBg:
  2125. {
  2126. if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard
  2127. return;
  2128. if (column_n == -1)
  2129. column_n = table->CurrentColumn;
  2130. if ((table->VisibleUnclippedMaskByIndex & ((ImU64)1 << column_n)) == 0)
  2131. return;
  2132. if (table->RowCellDataCurrent < 0 || table->RowCellData[table->RowCellDataCurrent].Column != column_n)
  2133. table->RowCellDataCurrent++;
  2134. ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCurrent];
  2135. cell_data->BgColor = color;
  2136. cell_data->Column = (ImS8)column_n;
  2137. break;
  2138. }
  2139. case ImGuiTableBgTarget_RowBg0:
  2140. case ImGuiTableBgTarget_RowBg1:
  2141. {
  2142. if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard
  2143. return;
  2144. IM_ASSERT(column_n == -1);
  2145. int bg_idx = (bg_target == ImGuiTableBgTarget_RowBg1) ? 1 : 0;
  2146. table->RowBgColor[bg_idx] = color;
  2147. break;
  2148. }
  2149. default:
  2150. IM_ASSERT(0);
  2151. }
  2152. }
  2153. void ImGui::TableSortSpecsSanitize(ImGuiTable* table)
  2154. {
  2155. IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable);
  2156. // Clear SortOrder from hidden column and verify that there's no gap or duplicate.
  2157. int sort_order_count = 0;
  2158. ImU64 sort_order_mask = 0x00;
  2159. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  2160. {
  2161. ImGuiTableColumn* column = &table->Columns[column_n];
  2162. if (column->SortOrder != -1 && !column->IsVisible)
  2163. column->SortOrder = -1;
  2164. if (column->SortOrder == -1)
  2165. continue;
  2166. sort_order_count++;
  2167. sort_order_mask |= ((ImU64)1 << column->SortOrder);
  2168. IM_ASSERT(sort_order_count < (int)sizeof(sort_order_mask) * 8);
  2169. }
  2170. const bool need_fix_linearize = ((ImU64)1 << sort_order_count) != (sort_order_mask + 1);
  2171. const bool need_fix_single_sort_order = (sort_order_count > 1) && !(table->Flags & ImGuiTableFlags_MultiSortable);
  2172. if (need_fix_linearize || need_fix_single_sort_order)
  2173. {
  2174. ImU64 fixed_mask = 0x00;
  2175. for (int sort_n = 0; sort_n < sort_order_count; sort_n++)
  2176. {
  2177. // Fix: Rewrite sort order fields if needed so they have no gap or duplicate.
  2178. // (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1)
  2179. int column_with_smallest_sort_order = -1;
  2180. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  2181. if ((fixed_mask & ((ImU64)1 << (ImU64)column_n)) == 0 && table->Columns[column_n].SortOrder != -1)
  2182. if (column_with_smallest_sort_order == -1 || table->Columns[column_n].SortOrder < table->Columns[column_with_smallest_sort_order].SortOrder)
  2183. column_with_smallest_sort_order = column_n;
  2184. IM_ASSERT(column_with_smallest_sort_order != -1);
  2185. fixed_mask |= ((ImU64)1 << column_with_smallest_sort_order);
  2186. table->Columns[column_with_smallest_sort_order].SortOrder = (ImS8)sort_n;
  2187. // Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set.
  2188. if (need_fix_single_sort_order)
  2189. {
  2190. sort_order_count = 1;
  2191. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  2192. if (column_n != column_with_smallest_sort_order)
  2193. table->Columns[column_n].SortOrder = -1;
  2194. break;
  2195. }
  2196. }
  2197. }
  2198. // Fallback default sort order (if no column had the ImGuiTableColumnFlags_DefaultSort flag)
  2199. if (sort_order_count == 0)
  2200. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  2201. {
  2202. ImGuiTableColumn* column = &table->Columns[column_n];
  2203. if (column->IsVisible && !(column->Flags & ImGuiTableColumnFlags_NoSort))
  2204. {
  2205. sort_order_count = 1;
  2206. column->SortOrder = 0;
  2207. TableFixColumnSortDirection(column);
  2208. break;
  2209. }
  2210. }
  2211. table->SortSpecsCount = (ImS8)sort_order_count;
  2212. }
  2213. void ImGui::TableSortSpecsBuild(ImGuiTable* table)
  2214. {
  2215. IM_ASSERT(table->IsSortSpecsDirty);
  2216. TableSortSpecsSanitize(table);
  2217. // Write output
  2218. table->SortSpecsData.resize(table->SortSpecsCount);
  2219. table->SortSpecs.ColumnsMask = 0x00;
  2220. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  2221. {
  2222. ImGuiTableColumn* column = &table->Columns[column_n];
  2223. if (column->SortOrder == -1)
  2224. continue;
  2225. ImGuiTableSortSpecsColumn* sort_spec = &table->SortSpecsData[column->SortOrder];
  2226. sort_spec->ColumnUserID = column->UserID;
  2227. sort_spec->ColumnIndex = (ImU8)column_n;
  2228. sort_spec->SortOrder = (ImU8)column->SortOrder;
  2229. sort_spec->SortDirection = column->SortDirection;
  2230. table->SortSpecs.ColumnsMask |= (ImU64)1 << column_n;
  2231. }
  2232. table->SortSpecs.Specs = table->SortSpecsData.Data;
  2233. table->SortSpecs.SpecsCount = table->SortSpecsData.Size;
  2234. table->SortSpecs.SpecsDirty = true; // Mark as dirty for user
  2235. table->IsSortSpecsDirty = false; // Mark as not dirty for us
  2236. }
  2237. //-------------------------------------------------------------------------
  2238. // TABLE - .ini settings
  2239. //-------------------------------------------------------------------------
  2240. // [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings.
  2241. // [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table.
  2242. // [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty.
  2243. // [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file.
  2244. //-------------------------------------------------------------------------
  2245. // Clear and initialize empty settings instance
  2246. static void InitTableSettings(ImGuiTableSettings* settings, ImGuiID id, int columns_count, int columns_count_max)
  2247. {
  2248. IM_PLACEMENT_NEW(settings) ImGuiTableSettings();
  2249. ImGuiTableColumnSettings* settings_column = settings->GetColumnSettings();
  2250. for (int n = 0; n < columns_count_max; n++, settings_column++)
  2251. IM_PLACEMENT_NEW(settings_column) ImGuiTableColumnSettings();
  2252. settings->ID = id;
  2253. settings->ColumnsCount = (ImS8)columns_count;
  2254. settings->ColumnsCountMax = (ImS8)columns_count_max;
  2255. settings->WantApply = true;
  2256. }
  2257. ImGuiTableSettings* ImGui::TableSettingsCreate(ImGuiID id, int columns_count)
  2258. {
  2259. ImGuiContext& g = *GImGui;
  2260. ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings));
  2261. InitTableSettings(settings, id, columns_count, columns_count);
  2262. return settings;
  2263. }
  2264. // Find existing settings
  2265. ImGuiTableSettings* ImGui::TableSettingsFindByID(ImGuiID id)
  2266. {
  2267. // FIXME-OPT: Might want to store a lookup map for this?
  2268. ImGuiContext& g = *GImGui;
  2269. for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
  2270. if (settings->ID == id)
  2271. return settings;
  2272. return NULL;
  2273. }
  2274. void ImGui::TableSettingsClearByID(ImGuiID id)
  2275. {
  2276. if (ImGuiTableSettings* settings = TableSettingsFindByID(id))
  2277. settings->ID = 0;
  2278. }
  2279. // Get settings for a given table, NULL if none
  2280. ImGuiTableSettings* ImGui::TableGetBoundSettings(ImGuiTable* table)
  2281. {
  2282. if (table->SettingsOffset != -1)
  2283. {
  2284. ImGuiContext& g = *GImGui;
  2285. ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset);
  2286. IM_ASSERT(settings->ID == table->ID);
  2287. if (settings->ColumnsCountMax >= table->ColumnsCount)
  2288. return settings; // OK
  2289. settings->ID = 0; // Invalidate storage, we won't fit because of a count change
  2290. }
  2291. return NULL;
  2292. }
  2293. void ImGui::TableSaveSettings(ImGuiTable* table)
  2294. {
  2295. table->IsSettingsDirty = false;
  2296. if (table->Flags & ImGuiTableFlags_NoSavedSettings)
  2297. return;
  2298. // Bind or create settings data
  2299. ImGuiContext& g = *GImGui;
  2300. ImGuiTableSettings* settings = TableGetBoundSettings(table);
  2301. if (settings == NULL)
  2302. {
  2303. settings = TableSettingsCreate(table->ID, table->ColumnsCount);
  2304. table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);
  2305. }
  2306. settings->ColumnsCount = (ImS8)table->ColumnsCount;
  2307. // Serialize ImGuiTable/ImGuiTableColumn into ImGuiTableSettings/ImGuiTableColumnSettings
  2308. IM_ASSERT(settings->ID == table->ID);
  2309. IM_ASSERT(settings->ColumnsCount == table->ColumnsCount && settings->ColumnsCountMax >= settings->ColumnsCount);
  2310. ImGuiTableColumn* column = table->Columns.Data;
  2311. ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
  2312. bool save_ref_scale = false;
  2313. settings->SaveFlags = ImGuiTableFlags_None;
  2314. for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++)
  2315. {
  2316. const float width_or_weight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? column->WidthStretchWeight : column->WidthRequest;
  2317. column_settings->WidthOrWeight = width_or_weight;
  2318. column_settings->Index = (ImS8)n;
  2319. column_settings->DisplayOrder = column->DisplayOrder;
  2320. column_settings->SortOrder = column->SortOrder;
  2321. column_settings->SortDirection = column->SortDirection;
  2322. column_settings->IsVisible = column->IsVisible;
  2323. column_settings->IsStretch = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0;
  2324. if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) == 0)
  2325. save_ref_scale = true;
  2326. // We skip saving some data in the .ini file when they are unnecessary to restore our state.
  2327. // Note that fixed width where initial width was derived from auto-fit will always be saved as WidthOrWeightInitValue will be 0.0f.
  2328. // FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present.
  2329. if (width_or_weight != column->WidthOrWeightInitValue)
  2330. settings->SaveFlags |= ImGuiTableFlags_Resizable;
  2331. if (column->DisplayOrder != n)
  2332. settings->SaveFlags |= ImGuiTableFlags_Reorderable;
  2333. if (column->SortOrder != -1)
  2334. settings->SaveFlags |= ImGuiTableFlags_Sortable;
  2335. if (column->IsVisible != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0))
  2336. settings->SaveFlags |= ImGuiTableFlags_Hideable;
  2337. }
  2338. settings->SaveFlags &= table->Flags;
  2339. settings->RefScale = save_ref_scale ? table->RefScale : 0.0f;
  2340. MarkIniSettingsDirty();
  2341. }
  2342. void ImGui::TableLoadSettings(ImGuiTable* table)
  2343. {
  2344. ImGuiContext& g = *GImGui;
  2345. table->IsSettingsRequestLoad = false;
  2346. if (table->Flags & ImGuiTableFlags_NoSavedSettings)
  2347. return;
  2348. // Bind settings
  2349. ImGuiTableSettings* settings;
  2350. if (table->SettingsOffset == -1)
  2351. {
  2352. settings = TableSettingsFindByID(table->ID);
  2353. if (settings == NULL)
  2354. return;
  2355. if (settings->ColumnsCount != table->ColumnsCount) // Allow settings if columns count changed. We could otherwise decide to return...
  2356. table->IsSettingsDirty = true;
  2357. table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);
  2358. }
  2359. else
  2360. {
  2361. settings = TableGetBoundSettings(table);
  2362. }
  2363. table->SettingsLoadedFlags = settings->SaveFlags;
  2364. table->RefScale = settings->RefScale;
  2365. // Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn
  2366. ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
  2367. for (int data_n = 0; data_n < settings->ColumnsCount; data_n++, column_settings++)
  2368. {
  2369. int column_n = column_settings->Index;
  2370. if (column_n < 0 || column_n >= table->ColumnsCount)
  2371. continue;
  2372. ImGuiTableColumn* column = &table->Columns[column_n];
  2373. if (settings->SaveFlags & ImGuiTableFlags_Resizable)
  2374. {
  2375. if (column_settings->IsStretch)
  2376. column->WidthStretchWeight = column_settings->WidthOrWeight;
  2377. else
  2378. column->WidthRequest = column_settings->WidthOrWeight;
  2379. column->AutoFitQueue = 0x00;
  2380. }
  2381. if (settings->SaveFlags & ImGuiTableFlags_Reorderable)
  2382. column->DisplayOrder = column_settings->DisplayOrder;
  2383. else
  2384. column->DisplayOrder = (ImS8)column_n;
  2385. column->IsVisible = column->IsVisibleNextFrame = column_settings->IsVisible;
  2386. column->SortOrder = column_settings->SortOrder;
  2387. column->SortDirection = column_settings->SortDirection;
  2388. }
  2389. // FIXME-TABLE: Need to validate .ini data
  2390. for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
  2391. table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImS8)column_n;
  2392. }
  2393. static void TableSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
  2394. {
  2395. ImGuiContext& g = *ctx;
  2396. for (int i = 0; i != g.Tables.GetSize(); i++)
  2397. g.Tables.GetByIndex(i)->SettingsOffset = -1;
  2398. g.SettingsTables.clear();
  2399. }
  2400. // Apply to existing windows (if any)
  2401. static void TableSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
  2402. {
  2403. ImGuiContext& g = *ctx;
  2404. for (int i = 0; i != g.Tables.GetSize(); i++)
  2405. {
  2406. ImGuiTable* table = g.Tables.GetByIndex(i);
  2407. table->IsSettingsRequestLoad = true;
  2408. table->SettingsOffset = -1;
  2409. }
  2410. }
  2411. static void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
  2412. {
  2413. ImGuiID id = 0;
  2414. int columns_count = 0;
  2415. if (sscanf(name, "0x%08X,%d", &id, &columns_count) < 2)
  2416. return NULL;
  2417. if (ImGuiTableSettings* settings = ImGui::TableSettingsFindByID(id))
  2418. {
  2419. if (settings->ColumnsCountMax >= columns_count)
  2420. {
  2421. InitTableSettings(settings, id, columns_count, settings->ColumnsCountMax); // Recycle
  2422. return settings;
  2423. }
  2424. settings->ID = 0; // Invalidate storage if we won't fit because of a count change
  2425. }
  2426. return ImGui::TableSettingsCreate(id, columns_count);
  2427. }
  2428. static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
  2429. {
  2430. // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v"
  2431. ImGuiTableSettings* settings = (ImGuiTableSettings*)entry;
  2432. float f = 0.0f;
  2433. int column_n = 0, r = 0, n = 0;
  2434. if (sscanf(line, "RefScale=%f", &f) == 1) { settings->RefScale = f; return; }
  2435. if (sscanf(line, "Column %d%n", &column_n, &r) == 1)
  2436. {
  2437. if (column_n < 0 || column_n >= settings->ColumnsCount)
  2438. return;
  2439. line = ImStrSkipBlank(line + r);
  2440. char c = 0;
  2441. ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n;
  2442. column->Index = (ImS8)column_n;
  2443. if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r)==1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; }
  2444. if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = (float)n; column->IsStretch = 0; settings->SaveFlags |= ImGuiTableFlags_Resizable; }
  2445. if (sscanf(line, "Weight=%f%n", &f, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = f; column->IsStretch = 1; settings->SaveFlags |= ImGuiTableFlags_Resizable; }
  2446. if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->IsVisible = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; }
  2447. if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImS8)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; }
  2448. 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; }
  2449. }
  2450. }
  2451. static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
  2452. {
  2453. ImGuiContext& g = *ctx;
  2454. for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
  2455. {
  2456. if (settings->ID == 0) // Skip ditched settings
  2457. continue;
  2458. // TableSaveSettings() may clear some of those flags when we establish that the data can be stripped
  2459. // (e.g. Order was unchanged)
  2460. const bool save_size = (settings->SaveFlags & ImGuiTableFlags_Resizable) != 0;
  2461. const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0;
  2462. const bool save_order = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0;
  2463. const bool save_sort = (settings->SaveFlags & ImGuiTableFlags_Sortable) != 0;
  2464. if (!save_size && !save_visible && !save_order && !save_sort)
  2465. continue;
  2466. buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve
  2467. buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount);
  2468. if (settings->RefScale != 0.0f)
  2469. buf->appendf("RefScale=%g\n", settings->RefScale);
  2470. ImGuiTableColumnSettings* column = settings->GetColumnSettings();
  2471. for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++)
  2472. {
  2473. // "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v"
  2474. buf->appendf("Column %-2d", column_n);
  2475. if (column->UserID != 0) buf->appendf(" UserID=%08X", column->UserID);
  2476. if (save_size && column->IsStretch) buf->appendf(" Weight=%.4f", column->WidthOrWeight);
  2477. if (save_size && !column->IsStretch) buf->appendf(" Width=%d", (int)column->WidthOrWeight);
  2478. if (save_visible) buf->appendf(" Visible=%d", column->IsVisible);
  2479. if (save_order) buf->appendf(" Order=%d", column->DisplayOrder);
  2480. if (save_sort && column->SortOrder != -1) buf->appendf(" Sort=%d%c", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^');
  2481. buf->append("\n");
  2482. }
  2483. buf->append("\n");
  2484. }
  2485. }
  2486. void ImGui::TableSettingsInstallHandler(ImGuiContext* context)
  2487. {
  2488. ImGuiContext& g = *context;
  2489. ImGuiSettingsHandler ini_handler;
  2490. ini_handler.TypeName = "Table";
  2491. ini_handler.TypeHash = ImHashStr("Table");
  2492. ini_handler.ClearAllFn = TableSettingsHandler_ClearAll;
  2493. ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen;
  2494. ini_handler.ReadLineFn = TableSettingsHandler_ReadLine;
  2495. ini_handler.ApplyAllFn = TableSettingsHandler_ApplyAll;
  2496. ini_handler.WriteAllFn = TableSettingsHandler_WriteAll;
  2497. g.SettingsHandlers.push_back(ini_handler);
  2498. }
  2499. //-------------------------------------------------------------------------
  2500. // TABLE - Debugging
  2501. //-------------------------------------------------------------------------
  2502. // - DebugNodeTable() [Internal]
  2503. //-------------------------------------------------------------------------
  2504. #ifndef IMGUI_DISABLE_METRICS_WINDOW
  2505. void ImGui::DebugNodeTable(ImGuiTable* table)
  2506. {
  2507. char buf[256];
  2508. char* p = buf;
  2509. const char* buf_end = buf + IM_ARRAYSIZE(buf);
  2510. const bool is_active = (table->LastFrameActive >= ImGui::GetFrameCount() - 2);
  2511. ImFormatString(p, buf_end - p, "Table 0x%08X (%d columns, in '%s')%s", table->ID, table->ColumnsCount, table->OuterWindow->Name, is_active ? "" : " *Inactive*");
  2512. if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
  2513. bool open = TreeNode(table, "%s", buf);
  2514. if (!is_active) { PopStyleColor(); }
  2515. if (IsItemHovered())
  2516. GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255));
  2517. if (!open)
  2518. return;
  2519. BulletText("OuterRect: Pos: (%.1f,%.1f) Size: (%.1f,%.1f)", table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.GetWidth(), table->OuterRect.GetHeight());
  2520. BulletText("InnerWidth: %.1f%s", table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : "");
  2521. BulletText("ColumnsWidth: %.1f, AutoFitWidth: %.1f", table->ColumnsTotalWidth, table->ColumnsAutoFitWidth);
  2522. BulletText("HoveredColumnBody: %d, HoveredColumnBorder: %d", table->HoveredColumnBody, table->HoveredColumnBorder);
  2523. BulletText("ResizedColumn: %d, ReorderColumn: %d, HeldHeaderColumn: %d", table->ResizedColumn, table->ReorderColumn, table->HeldHeaderColumn);
  2524. for (int n = 0; n < table->ColumnsCount; n++)
  2525. {
  2526. ImGuiTableColumn* column = &table->Columns[n];
  2527. const char* name = TableGetColumnName(table, n);
  2528. BulletText("Column %d order %d name '%s': +%.1f to +%.1f\n"
  2529. "Visible: %d, Clipped: %d, DrawChannels: %d,%d\n"
  2530. "WidthGiven/Request: %.2f/%.2f, WidthWeight: %.3f\n"
  2531. "ContentWidth: Frozen %d, Unfrozen %d, HeadersUsed/Ideal %d/%d\n"
  2532. "SortOrder: %d, SortDir: %s\n"
  2533. "UserID: 0x%08X, Flags: 0x%04X: %s%s%s%s..",
  2534. n, column->DisplayOrder, name ? name : "NULL", column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x,
  2535. column->IsVisible, column->IsClipped, column->DrawChannelFrozen, column->DrawChannelUnfrozen,
  2536. column->WidthGiven, column->WidthRequest, column->WidthStretchWeight,
  2537. column->ContentWidthFrozen, column->ContentWidthUnfrozen, column->ContentWidthHeadersUsed, column->ContentWidthHeadersIdeal,
  2538. column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? "Ascending" : (column->SortDirection == ImGuiSortDirection_Descending) ? "Descending" : "None",
  2539. column->UserID, column->Flags,
  2540. (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "",
  2541. (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "",
  2542. (column->Flags & ImGuiTableColumnFlags_WidthAlwaysAutoResize) ? "WidthAlwaysAutoResize " : "",
  2543. (column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : "");
  2544. }
  2545. if (ImGuiTableSettings* settings = TableGetBoundSettings(table))
  2546. DebugNodeTableSettings(settings);
  2547. TreePop();
  2548. }
  2549. void ImGui::DebugNodeTableSettings(ImGuiTableSettings* settings)
  2550. {
  2551. if (!TreeNode((void*)(intptr_t)settings->ID, "Settings 0x%08X (%d columns)", settings->ID, settings->ColumnsCount))
  2552. return;
  2553. BulletText("SaveFlags: 0x%08X", settings->SaveFlags);
  2554. BulletText("ColumnsCount: %d (max %d)", settings->ColumnsCount, settings->ColumnsCountMax);
  2555. for (int n = 0; n < settings->ColumnsCount; n++)
  2556. {
  2557. ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n];
  2558. ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? (ImGuiSortDirection)column_settings->SortDirection : ImGuiSortDirection_None;
  2559. BulletText("Column %d Order %d SortOrder %d %s Visible %d UserID 0x%08X WidthOrWeight %.3f",
  2560. n, column_settings->DisplayOrder, column_settings->SortOrder,
  2561. (sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---",
  2562. column_settings->IsVisible, column_settings->UserID, column_settings->WidthOrWeight);
  2563. }
  2564. TreePop();
  2565. }
  2566. #endif // #ifndef IMGUI_DISABLE_METRICS_WINDOW
  2567. //-------------------------------------------------------------------------
  2568. //-------------------------------------------------------------------------
  2569. // [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc.
  2570. // (This is a legacy API, prefer using BeginTable/EndTable!)
  2571. //-------------------------------------------------------------------------
  2572. // - SetWindowClipRectBeforeSetChannel() [Internal]
  2573. // - GetColumnIndex()
  2574. // - GetColumnsCount()
  2575. // - GetColumnOffset()
  2576. // - GetColumnWidth()
  2577. // - SetColumnOffset()
  2578. // - SetColumnWidth()
  2579. // - PushColumnClipRect() [Internal]
  2580. // - PushColumnsBackground() [Internal]
  2581. // - PopColumnsBackground() [Internal]
  2582. // - FindOrCreateColumns() [Internal]
  2583. // - GetColumnsID() [Internal]
  2584. // - BeginColumns()
  2585. // - NextColumn()
  2586. // - EndColumns()
  2587. // - Columns()
  2588. //-------------------------------------------------------------------------
  2589. // [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences,
  2590. // they would meddle many times with the underlying ImDrawCmd.
  2591. // Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let
  2592. // the subsequent single call to SetCurrentChannel() does it things once.
  2593. void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect)
  2594. {
  2595. ImVec4 clip_rect_vec4 = clip_rect.ToVec4();
  2596. window->ClipRect = clip_rect;
  2597. window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4;
  2598. window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4;
  2599. }
  2600. int ImGui::GetColumnIndex()
  2601. {
  2602. ImGuiWindow* window = GetCurrentWindowRead();
  2603. return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0;
  2604. }
  2605. int ImGui::GetColumnsCount()
  2606. {
  2607. ImGuiWindow* window = GetCurrentWindowRead();
  2608. return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1;
  2609. }
  2610. float ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm)
  2611. {
  2612. return offset_norm * (columns->OffMaxX - columns->OffMinX);
  2613. }
  2614. float ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset)
  2615. {
  2616. return offset / (columns->OffMaxX - columns->OffMinX);
  2617. }
  2618. static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f;
  2619. static float GetDraggedColumnOffset(ImGuiOldColumns* columns, int column_index)
  2620. {
  2621. // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
  2622. // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
  2623. ImGuiContext& g = *GImGui;
  2624. ImGuiWindow* window = g.CurrentWindow;
  2625. IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
  2626. IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
  2627. float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x;
  2628. x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
  2629. if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths))
  2630. x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
  2631. return x;
  2632. }
  2633. float ImGui::GetColumnOffset(int column_index)
  2634. {
  2635. ImGuiWindow* window = GetCurrentWindowRead();
  2636. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2637. if (columns == NULL)
  2638. return 0.0f;
  2639. if (column_index < 0)
  2640. column_index = columns->Current;
  2641. IM_ASSERT(column_index < columns->Columns.Size);
  2642. const float t = columns->Columns[column_index].OffsetNorm;
  2643. const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t);
  2644. return x_offset;
  2645. }
  2646. static float GetColumnWidthEx(ImGuiOldColumns* columns, int column_index, bool before_resize = false)
  2647. {
  2648. if (column_index < 0)
  2649. column_index = columns->Current;
  2650. float offset_norm;
  2651. if (before_resize)
  2652. offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
  2653. else
  2654. offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
  2655. return ImGui::GetColumnOffsetFromNorm(columns, offset_norm);
  2656. }
  2657. float ImGui::GetColumnWidth(int column_index)
  2658. {
  2659. ImGuiContext& g = *GImGui;
  2660. ImGuiWindow* window = g.CurrentWindow;
  2661. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2662. if (columns == NULL)
  2663. return GetContentRegionAvail().x;
  2664. if (column_index < 0)
  2665. column_index = columns->Current;
  2666. return GetColumnOffsetFromNorm(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
  2667. }
  2668. void ImGui::SetColumnOffset(int column_index, float offset)
  2669. {
  2670. ImGuiContext& g = *GImGui;
  2671. ImGuiWindow* window = g.CurrentWindow;
  2672. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2673. IM_ASSERT(columns != NULL);
  2674. if (column_index < 0)
  2675. column_index = columns->Current;
  2676. IM_ASSERT(column_index < columns->Columns.Size);
  2677. const bool preserve_width = !(columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1);
  2678. const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
  2679. if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow))
  2680. offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
  2681. columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX);
  2682. if (preserve_width)
  2683. SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
  2684. }
  2685. void ImGui::SetColumnWidth(int column_index, float width)
  2686. {
  2687. ImGuiWindow* window = GetCurrentWindowRead();
  2688. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2689. IM_ASSERT(columns != NULL);
  2690. if (column_index < 0)
  2691. column_index = columns->Current;
  2692. SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
  2693. }
  2694. void ImGui::PushColumnClipRect(int column_index)
  2695. {
  2696. ImGuiWindow* window = GetCurrentWindowRead();
  2697. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2698. if (column_index < 0)
  2699. column_index = columns->Current;
  2700. ImGuiOldColumnData* column = &columns->Columns[column_index];
  2701. PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false);
  2702. }
  2703. // Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns)
  2704. void ImGui::PushColumnsBackground()
  2705. {
  2706. ImGuiWindow* window = GetCurrentWindowRead();
  2707. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2708. if (columns->Count == 1)
  2709. return;
  2710. // Optimization: avoid SetCurrentChannel() + PushClipRect()
  2711. columns->HostBackupClipRect = window->ClipRect;
  2712. SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect);
  2713. columns->Splitter.SetCurrentChannel(window->DrawList, 0);
  2714. }
  2715. void ImGui::PopColumnsBackground()
  2716. {
  2717. ImGuiWindow* window = GetCurrentWindowRead();
  2718. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2719. if (columns->Count == 1)
  2720. return;
  2721. // Optimization: avoid PopClipRect() + SetCurrentChannel()
  2722. SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect);
  2723. columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
  2724. }
  2725. ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id)
  2726. {
  2727. // We have few columns per window so for now we don't need bother much with turning this into a faster lookup.
  2728. for (int n = 0; n < window->ColumnsStorage.Size; n++)
  2729. if (window->ColumnsStorage[n].ID == id)
  2730. return &window->ColumnsStorage[n];
  2731. window->ColumnsStorage.push_back(ImGuiOldColumns());
  2732. ImGuiOldColumns* columns = &window->ColumnsStorage.back();
  2733. columns->ID = id;
  2734. return columns;
  2735. }
  2736. ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count)
  2737. {
  2738. ImGuiWindow* window = GetCurrentWindow();
  2739. // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
  2740. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
  2741. PushID(0x11223347 + (str_id ? 0 : columns_count));
  2742. ImGuiID id = window->GetID(str_id ? str_id : "columns");
  2743. PopID();
  2744. return id;
  2745. }
  2746. void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags)
  2747. {
  2748. ImGuiContext& g = *GImGui;
  2749. ImGuiWindow* window = GetCurrentWindow();
  2750. IM_ASSERT(columns_count >= 1);
  2751. IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported
  2752. // Acquire storage for the columns set
  2753. ImGuiID id = GetColumnsID(str_id, columns_count);
  2754. ImGuiOldColumns* columns = FindOrCreateColumns(window, id);
  2755. IM_ASSERT(columns->ID == id);
  2756. columns->Current = 0;
  2757. columns->Count = columns_count;
  2758. columns->Flags = flags;
  2759. window->DC.CurrentColumns = columns;
  2760. columns->HostCursorPosY = window->DC.CursorPos.y;
  2761. columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x;
  2762. columns->HostInitialClipRect = window->ClipRect;
  2763. columns->HostBackupParentWorkRect = window->ParentWorkRect;
  2764. window->ParentWorkRect = window->WorkRect;
  2765. // Set state for first column
  2766. // We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect
  2767. const float column_padding = g.Style.ItemSpacing.x;
  2768. const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize));
  2769. const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f);
  2770. const float max_2 = window->WorkRect.Max.x + half_clip_extend_x;
  2771. columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f);
  2772. columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f);
  2773. columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
  2774. // Clear data if columns count changed
  2775. if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
  2776. columns->Columns.resize(0);
  2777. // Initialize default widths
  2778. columns->IsFirstFrame = (columns->Columns.Size == 0);
  2779. if (columns->Columns.Size == 0)
  2780. {
  2781. columns->Columns.reserve(columns_count + 1);
  2782. for (int n = 0; n < columns_count + 1; n++)
  2783. {
  2784. ImGuiOldColumnData column;
  2785. column.OffsetNorm = n / (float)columns_count;
  2786. columns->Columns.push_back(column);
  2787. }
  2788. }
  2789. for (int n = 0; n < columns_count; n++)
  2790. {
  2791. // Compute clipping rectangle
  2792. ImGuiOldColumnData* column = &columns->Columns[n];
  2793. float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n));
  2794. float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
  2795. column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
  2796. column->ClipRect.ClipWithFull(window->ClipRect);
  2797. }
  2798. if (columns->Count > 1)
  2799. {
  2800. columns->Splitter.Split(window->DrawList, 1 + columns->Count);
  2801. columns->Splitter.SetCurrentChannel(window->DrawList, 1);
  2802. PushColumnClipRect(0);
  2803. }
  2804. // We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user.
  2805. float offset_0 = GetColumnOffset(columns->Current);
  2806. float offset_1 = GetColumnOffset(columns->Current + 1);
  2807. float width = offset_1 - offset_0;
  2808. PushItemWidth(width * 0.65f);
  2809. window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
  2810. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  2811. window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
  2812. }
  2813. void ImGui::NextColumn()
  2814. {
  2815. ImGuiWindow* window = GetCurrentWindow();
  2816. if (window->SkipItems || window->DC.CurrentColumns == NULL)
  2817. return;
  2818. ImGuiContext& g = *GImGui;
  2819. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2820. if (columns->Count == 1)
  2821. {
  2822. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  2823. IM_ASSERT(columns->Current == 0);
  2824. return;
  2825. }
  2826. // Next column
  2827. if (++columns->Current == columns->Count)
  2828. columns->Current = 0;
  2829. PopItemWidth();
  2830. // Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect()
  2831. // (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them),
  2832. ImGuiOldColumnData* column = &columns->Columns[columns->Current];
  2833. SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
  2834. columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
  2835. const float column_padding = g.Style.ItemSpacing.x;
  2836. columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
  2837. if (columns->Current > 0)
  2838. {
  2839. // Columns 1+ ignore IndentX (by canceling it out)
  2840. // FIXME-COLUMNS: Unnecessary, could be locked?
  2841. window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding;
  2842. }
  2843. else
  2844. {
  2845. // New row/line: column 0 honor IndentX.
  2846. window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
  2847. columns->LineMinY = columns->LineMaxY;
  2848. }
  2849. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  2850. window->DC.CursorPos.y = columns->LineMinY;
  2851. window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
  2852. window->DC.CurrLineTextBaseOffset = 0.0f;
  2853. // FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup.
  2854. float offset_0 = GetColumnOffset(columns->Current);
  2855. float offset_1 = GetColumnOffset(columns->Current + 1);
  2856. float width = offset_1 - offset_0;
  2857. PushItemWidth(width * 0.65f);
  2858. window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
  2859. }
  2860. void ImGui::EndColumns()
  2861. {
  2862. ImGuiContext& g = *GImGui;
  2863. ImGuiWindow* window = GetCurrentWindow();
  2864. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2865. IM_ASSERT(columns != NULL);
  2866. PopItemWidth();
  2867. if (columns->Count > 1)
  2868. {
  2869. PopClipRect();
  2870. columns->Splitter.Merge(window->DrawList);
  2871. }
  2872. const ImGuiOldColumnFlags flags = columns->Flags;
  2873. columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
  2874. window->DC.CursorPos.y = columns->LineMaxY;
  2875. if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize))
  2876. window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent
  2877. // Draw columns borders and handle resize
  2878. // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy
  2879. bool is_being_resized = false;
  2880. if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems)
  2881. {
  2882. // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.
  2883. const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y);
  2884. const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y);
  2885. int dragging_column = -1;
  2886. for (int n = 1; n < columns->Count; n++)
  2887. {
  2888. ImGuiOldColumnData* column = &columns->Columns[n];
  2889. float x = window->Pos.x + GetColumnOffset(n);
  2890. const ImGuiID column_id = columns->ID + ImGuiID(n);
  2891. const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH;
  2892. const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2));
  2893. KeepAliveID(column_id);
  2894. if (IsClippedEx(column_hit_rect, column_id, false))
  2895. continue;
  2896. bool hovered = false, held = false;
  2897. if (!(flags & ImGuiOldColumnFlags_NoResize))
  2898. {
  2899. ButtonBehavior(column_hit_rect, column_id, &hovered, &held);
  2900. if (hovered || held)
  2901. g.MouseCursor = ImGuiMouseCursor_ResizeEW;
  2902. if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize))
  2903. dragging_column = n;
  2904. }
  2905. // Draw column
  2906. const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
  2907. const float xi = IM_FLOOR(x);
  2908. window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col);
  2909. }
  2910. // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
  2911. if (dragging_column != -1)
  2912. {
  2913. if (!columns->IsBeingResized)
  2914. for (int n = 0; n < columns->Count + 1; n++)
  2915. columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
  2916. columns->IsBeingResized = is_being_resized = true;
  2917. float x = GetDraggedColumnOffset(columns, dragging_column);
  2918. SetColumnOffset(dragging_column, x);
  2919. }
  2920. }
  2921. columns->IsBeingResized = is_being_resized;
  2922. window->WorkRect = window->ParentWorkRect;
  2923. window->ParentWorkRect = columns->HostBackupParentWorkRect;
  2924. window->DC.CurrentColumns = NULL;
  2925. window->DC.ColumnsOffset.x = 0.0f;
  2926. window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
  2927. }
  2928. void ImGui::Columns(int columns_count, const char* id, bool border)
  2929. {
  2930. ImGuiWindow* window = GetCurrentWindow();
  2931. IM_ASSERT(columns_count >= 1);
  2932. ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder);
  2933. //flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior
  2934. ImGuiOldColumns* columns = window->DC.CurrentColumns;
  2935. if (columns != NULL && columns->Count == columns_count && columns->Flags == flags)
  2936. return;
  2937. if (columns != NULL)
  2938. EndColumns();
  2939. if (columns_count != 1)
  2940. BeginColumns(id, columns_count, flags);
  2941. }
  2942. //-------------------------------------------------------------------------
  2943. #endif // #ifndef IMGUI_DISABLE