imgui_tables.cpp 194 KB

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