imgui_tables.cpp 156 KB

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