imgui_tables.cpp 195 KB

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