imgui_tables.cpp 174 KB

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