imgui_tables.cpp 242 KB

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