imgui_tables.cpp 162 KB

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