imgui_tables.cpp 245 KB

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