imgui_tables.cpp 189 KB

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