imgui_tables.cpp 163 KB

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