imgui_tables.cpp 180 KB

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