imgui_tables.cpp 245 KB

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