imgui_tables.cpp 143 KB

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