imgui_tables.cpp 167 KB

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