imgui_tables.cpp 187 KB

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