imgui_tables.cpp 155 KB

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