imgui_tables.cpp 172 KB

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