imgui_tables.cpp 193 KB

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