imgui_tables.cpp 154 KB

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