Debian Codegraph @

subprojects/imgui-1.91.6/imgui_widgets.cpp

raw
1 // dear imgui, v1.91.6
2 // (widgets code)
3
4 /*
5
6 Index of this file:
7
8 // [SECTION] Forward Declarations
9 // [SECTION] Widgets: Text, etc.
10 // [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.)
11 // [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.)
12 // [SECTION] Widgets: ComboBox
13 // [SECTION] Data Type and Data Formatting Helpers
14 // [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.
15 // [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
16 // [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
17 // [SECTION] Widgets: InputText, InputTextMultiline
18 // [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.
19 // [SECTION] Widgets: TreeNode, CollapsingHeader, etc.
20 // [SECTION] Widgets: Selectable
21 // [SECTION] Widgets: Typing-Select support
22 // [SECTION] Widgets: Box-Select support
23 // [SECTION] Widgets: Multi-Select support
24 // [SECTION] Widgets: Multi-Select helpers
25 // [SECTION] Widgets: ListBox
26 // [SECTION] Widgets: PlotLines, PlotHistogram
27 // [SECTION] Widgets: Value helpers
28 // [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc.
29 // [SECTION] Widgets: BeginTabBar, EndTabBar, etc.
30 // [SECTION] Widgets: BeginTabItem, EndTabItem, etc.
31 // [SECTION] Widgets: Columns, BeginColumns, EndColumns, etc.
32
33 */
34
35 #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
36 #define _CRT_SECURE_NO_WARNINGS
37 #endif
38
39 #ifndef IMGUI_DEFINE_MATH_OPERATORS
40 #define IMGUI_DEFINE_MATH_OPERATORS
41 #endif
42
43 #include "imgui.h"
44 #ifndef IMGUI_DISABLE
45 #include "imgui_internal.h"
46
47 // System includes
48 #include <stdint.h> // intptr_t
49
50 //-------------------------------------------------------------------------
51 // Warnings
52 //-------------------------------------------------------------------------
53
54 // Visual Studio warnings
55 #ifdef _MSC_VER
56 #pragma warning (disable: 4127) // condition expression is constant
57 #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
58 #if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
59 #pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
60 #endif
61 #pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
62 #pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
63 #endif
64
65 // Clang/GCC warnings with -Weverything
66 #if defined(__clang__)
67 #if __has_warning("-Wunknown-warning-option")
68 #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!
69 #endif
70 #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
71 #pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
72 #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.
73 #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning: format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
74 #pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
75 #pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used.
76 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
77 #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.
78 #pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_')
79 #pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
80 #pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
81 #pragma clang diagnostic ignored "-Wunsafe-buffer-usage" // warning: 'xxx' is an unsafe pointer used for buffer access
82 #pragma clang diagnostic ignored "-Wnontrivial-memaccess" // warning: first argument in call to 'memset' is a pointer to non-trivially copyable type
83 #elif defined(__GNUC__)
84 #pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
85 #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
86 #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
87 #pragma GCC diagnostic ignored "-Wdeprecated-enum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
88 #endif
89
90 //-------------------------------------------------------------------------
91 // Data
92 //-------------------------------------------------------------------------
93
94 // Widgets
95 static const float DRAGDROP_HOLD_TO_OPEN_TIMER = 0.70f; // Time for drag-hold to activate items accepting the ImGuiButtonFlags_PressedOnDragDropHold button behavior.
96 static const float DRAG_MOUSE_THRESHOLD_FACTOR = 0.50f; // Multiplier for the default value of io.MouseDragThreshold to make DragFloat/DragInt react faster to mouse drags.
97
98 // Those MIN/MAX values are not define because we need to point to them
99 static const signed char IM_S8_MIN = -128;
100 static const signed char IM_S8_MAX = 127;
101 static const unsigned char IM_U8_MIN = 0;
102 static const unsigned char IM_U8_MAX = 0xFF;
103 static const signed short IM_S16_MIN = -32768;
104 static const signed short IM_S16_MAX = 32767;
105 static const unsigned short IM_U16_MIN = 0;
106 static const unsigned short IM_U16_MAX = 0xFFFF;
107 static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000);
108 static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF)
109 static const ImU32 IM_U32_MIN = 0;
110 static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF)
111 #ifdef LLONG_MIN
112 static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll);
113 static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll);
114 #else
115 static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1;
116 static const ImS64 IM_S64_MAX = 9223372036854775807LL;
117 #endif
118 static const ImU64 IM_U64_MIN = 0;
119 #ifdef ULLONG_MAX
120 static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull);
121 #else
122 static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1);
123 #endif
124
125 //-------------------------------------------------------------------------
126 // [SECTION] Forward Declarations
127 //-------------------------------------------------------------------------
128
129 // For InputTextEx()
130 static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard = false);
131 static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
132 static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
133
134 //-------------------------------------------------------------------------
135 // [SECTION] Widgets: Text, etc.
136 //-------------------------------------------------------------------------
137 // - TextEx() [Internal]
138 // - TextUnformatted()
139 // - Text()
140 // - TextV()
141 // - TextColored()
142 // - TextColoredV()
143 // - TextDisabled()
144 // - TextDisabledV()
145 // - TextWrapped()
146 // - TextWrappedV()
147 // - LabelText()
148 // - LabelTextV()
149 // - BulletText()
150 // - BulletTextV()
151 //-------------------------------------------------------------------------
152
153 void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags)
154 {
155 ImGuiWindow* window = GetCurrentWindow();
156 if (window->SkipItems)
157 return;
158 ImGuiContext& g = *GImGui;
159
160 // Accept null ranges
161 if (text == text_end)
162 text = text_end = "";
163
164 // Calculate length
165 const char* text_begin = text;
166 if (text_end == NULL)
167 text_end = text + strlen(text); // FIXME-OPT
168
169 const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
170 const float wrap_pos_x = window->DC.TextWrapPos;
171 const bool wrap_enabled = (wrap_pos_x >= 0.0f);
172 if (text_end - text <= 2000 || wrap_enabled)
173 {
174 // Common case
175 const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
176 const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
177
178 ImRect bb(text_pos, text_pos + text_size);
179 ItemSize(text_size, 0.0f);
180 if (!ItemAdd(bb, 0))
181 return;
182
183 // Render (we don't hide text after ## in this end-user function)
184 RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
185 }
186 else
187 {
188 // Long text!
189 // Perform manual coarse clipping to optimize for long multi-line text
190 // - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
191 // - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.
192 // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop.
193 const char* line = text;
194 const float line_height = GetTextLineHeight();
195 ImVec2 text_size(0, 0);
196
197 // Lines to skip (can't skip when logging text)
198 ImVec2 pos = text_pos;
199 if (!g.LogEnabled)
200 {
201 int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height);
202 if (lines_skippable > 0)
203 {
204 int lines_skipped = 0;
205 while (line < text_end && lines_skipped < lines_skippable)
206 {
207 const char* line_end = (const char*)memchr(line, '\n', text_end - line);
208 if (!line_end)
209 line_end = text_end;
210 if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
211 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
212 line = line_end + 1;
213 lines_skipped++;
214 }
215 pos.y += lines_skipped * line_height;
216 }
217 }
218
219 // Lines to render
220 if (line < text_end)
221 {
222 ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
223 while (line < text_end)
224 {
225 if (IsClippedEx(line_rect, 0))
226 break;
227
228 const char* line_end = (const char*)memchr(line, '\n', text_end - line);
229 if (!line_end)
230 line_end = text_end;
231 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
232 RenderText(pos, line, line_end, false);
233 line = line_end + 1;
234 line_rect.Min.y += line_height;
235 line_rect.Max.y += line_height;
236 pos.y += line_height;
237 }
238
239 // Count remaining lines
240 int lines_skipped = 0;
241 while (line < text_end)
242 {
243 const char* line_end = (const char*)memchr(line, '\n', text_end - line);
244 if (!line_end)
245 line_end = text_end;
246 if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0)
247 text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x);
248 line = line_end + 1;
249 lines_skipped++;
250 }
251 pos.y += lines_skipped * line_height;
252 }
253 text_size.y = (pos - text_pos).y;
254
255 ImRect bb(text_pos, text_pos + text_size);
256 ItemSize(text_size, 0.0f);
257 ItemAdd(bb, 0);
258 }
259 }
260
261 void ImGui::TextUnformatted(const char* text, const char* text_end)
262 {
263 TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
264 }
265
266 void ImGui::Text(const char* fmt, ...)
267 {
268 va_list args;
269 va_start(args, fmt);
270 TextV(fmt, args);
271 va_end(args);
272 }
273
274 void ImGui::TextV(const char* fmt, va_list args)
275 {
276 ImGuiWindow* window = GetCurrentWindow();
277 if (window->SkipItems)
278 return;
279
280 const char* text, *text_end;
281 ImFormatStringToTempBufferV(&text, &text_end, fmt, args);
282 TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText);
283 }
284
285 void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
286 {
287 va_list args;
288 va_start(args, fmt);
289 TextColoredV(col, fmt, args);
290 va_end(args);
291 }
292
293 void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
294 {
295 PushStyleColor(ImGuiCol_Text, col);
296 TextV(fmt, args);
297 PopStyleColor();
298 }
299
300 void ImGui::TextDisabled(const char* fmt, ...)
301 {
302 va_list args;
303 va_start(args, fmt);
304 TextDisabledV(fmt, args);
305 va_end(args);
306 }
307
308 void ImGui::TextDisabledV(const char* fmt, va_list args)
309 {
310 ImGuiContext& g = *GImGui;
311 PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
312 TextV(fmt, args);
313 PopStyleColor();
314 }
315
316 void ImGui::TextWrapped(const char* fmt, ...)
317 {
318 va_list args;
319 va_start(args, fmt);
320 TextWrappedV(fmt, args);
321 va_end(args);
322 }
323
324 void ImGui::TextWrappedV(const char* fmt, va_list args)
325 {
326 ImGuiContext& g = *GImGui;
327 const bool need_backup = (g.CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set
328 if (need_backup)
329 PushTextWrapPos(0.0f);
330 TextV(fmt, args);
331 if (need_backup)
332 PopTextWrapPos();
333 }
334
335 void ImGui::LabelText(const char* label, const char* fmt, ...)
336 {
337 va_list args;
338 va_start(args, fmt);
339 LabelTextV(label, fmt, args);
340 va_end(args);
341 }
342
343 // Add a label+text combo aligned to other label+value widgets
344 void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
345 {
346 ImGuiWindow* window = GetCurrentWindow();
347 if (window->SkipItems)
348 return;
349
350 ImGuiContext& g = *GImGui;
351 const ImGuiStyle& style = g.Style;
352 const float w = CalcItemWidth();
353
354 const char* value_text_begin, *value_text_end;
355 ImFormatStringToTempBufferV(&value_text_begin, &value_text_end, fmt, args);
356 const ImVec2 value_size = CalcTextSize(value_text_begin, value_text_end, false);
357 const ImVec2 label_size = CalcTextSize(label, NULL, true);
358
359 const ImVec2 pos = window->DC.CursorPos;
360 const ImRect value_bb(pos, pos + ImVec2(w, value_size.y + style.FramePadding.y * 2));
361 const ImRect total_bb(pos, pos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), ImMax(value_size.y, label_size.y) + style.FramePadding.y * 2));
362 ItemSize(total_bb, style.FramePadding.y);
363 if (!ItemAdd(total_bb, 0))
364 return;
365
366 // Render
367 RenderTextClipped(value_bb.Min + style.FramePadding, value_bb.Max, value_text_begin, value_text_end, &value_size, ImVec2(0.0f, 0.0f));
368 if (label_size.x > 0.0f)
369 RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
370 }
371
372 void ImGui::BulletText(const char* fmt, ...)
373 {
374 va_list args;
375 va_start(args, fmt);
376 BulletTextV(fmt, args);
377 va_end(args);
378 }
379
380 // Text with a little bullet aligned to the typical tree node.
381 void ImGui::BulletTextV(const char* fmt, va_list args)
382 {
383 ImGuiWindow* window = GetCurrentWindow();
384 if (window->SkipItems)
385 return;
386
387 ImGuiContext& g = *GImGui;
388 const ImGuiStyle& style = g.Style;
389
390 const char* text_begin, *text_end;
391 ImFormatStringToTempBufferV(&text_begin, &text_end, fmt, args);
392 const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
393 const ImVec2 total_size = ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x * 2) : 0.0f), label_size.y); // Empty text doesn't add padding
394 ImVec2 pos = window->DC.CursorPos;
395 pos.y += window->DC.CurrLineTextBaseOffset;
396 ItemSize(total_size, 0.0f);
397 const ImRect bb(pos, pos + total_size);
398 if (!ItemAdd(bb, 0))
399 return;
400
401 // Render
402 ImU32 text_col = GetColorU32(ImGuiCol_Text);
403 RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, g.FontSize * 0.5f), text_col);
404 RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x * 2, 0.0f), text_begin, text_end, false);
405 }
406
407 //-------------------------------------------------------------------------
408 // [SECTION] Widgets: Main
409 //-------------------------------------------------------------------------
410 // - ButtonBehavior() [Internal]
411 // - Button()
412 // - SmallButton()
413 // - InvisibleButton()
414 // - ArrowButton()
415 // - CloseButton() [Internal]
416 // - CollapseButton() [Internal]
417 // - GetWindowScrollbarID() [Internal]
418 // - GetWindowScrollbarRect() [Internal]
419 // - Scrollbar() [Internal]
420 // - ScrollbarEx() [Internal]
421 // - Image()
422 // - ImageButton()
423 // - Checkbox()
424 // - CheckboxFlagsT() [Internal]
425 // - CheckboxFlags()
426 // - RadioButton()
427 // - ProgressBar()
428 // - Bullet()
429 // - Hyperlink()
430 //-------------------------------------------------------------------------
431
432 // The ButtonBehavior() function is key to many interactions and used by many/most widgets.
433 // Because we handle so many cases (keyboard/gamepad navigation, drag and drop) and many specific behavior (via ImGuiButtonFlags_),
434 // this code is a little complex.
435 // By far the most common path is interacting with the Mouse using the default ImGuiButtonFlags_PressedOnClickRelease button behavior.
436 // See the series of events below and the corresponding state reported by dear imgui:
437 //------------------------------------------------------------------------------------------------------------------------------------------------
438 // with PressedOnClickRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
439 // Frame N+0 (mouse is outside bb) - - - - - -
440 // Frame N+1 (mouse moves inside bb) - true - - - -
441 // Frame N+2 (mouse button is down) - true true true - true
442 // Frame N+3 (mouse button is down) - true true - - -
443 // Frame N+4 (mouse moves outside bb) - - true - - -
444 // Frame N+5 (mouse moves inside bb) - true true - - -
445 // Frame N+6 (mouse button is released) true true - - true -
446 // Frame N+7 (mouse button is released) - true - - - -
447 // Frame N+8 (mouse moves outside bb) - - - - - -
448 //------------------------------------------------------------------------------------------------------------------------------------------------
449 // with PressedOnClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
450 // Frame N+2 (mouse button is down) true true true true - true
451 // Frame N+3 (mouse button is down) - true true - - -
452 // Frame N+6 (mouse button is released) - true - - true -
453 // Frame N+7 (mouse button is released) - true - - - -
454 //------------------------------------------------------------------------------------------------------------------------------------------------
455 // with PressedOnRelease: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
456 // Frame N+2 (mouse button is down) - true - - - true
457 // Frame N+3 (mouse button is down) - true - - - -
458 // Frame N+6 (mouse button is released) true true - - - -
459 // Frame N+7 (mouse button is released) - true - - - -
460 //------------------------------------------------------------------------------------------------------------------------------------------------
461 // with PressedOnDoubleClick: return-value IsItemHovered() IsItemActive() IsItemActivated() IsItemDeactivated() IsItemClicked()
462 // Frame N+0 (mouse button is down) - true - - - true
463 // Frame N+1 (mouse button is down) - true - - - -
464 // Frame N+2 (mouse button is released) - true - - - -
465 // Frame N+3 (mouse button is released) - true - - - -
466 // Frame N+4 (mouse button is down) true true true true - true
467 // Frame N+5 (mouse button is down) - true true - - -
468 // Frame N+6 (mouse button is released) - true - - true -
469 // Frame N+7 (mouse button is released) - true - - - -
470 //------------------------------------------------------------------------------------------------------------------------------------------------
471 // Note that some combinations are supported,
472 // - PressedOnDragDropHold can generally be associated with any flag.
473 // - PressedOnDoubleClick can be associated by PressedOnClickRelease/PressedOnRelease, in which case the second release event won't be reported.
474 //------------------------------------------------------------------------------------------------------------------------------------------------
475 // The behavior of the return-value changes when ImGuiButtonFlags_Repeat is set:
476 // Repeat+ Repeat+ Repeat+ Repeat+
477 // PressedOnClickRelease PressedOnClick PressedOnRelease PressedOnDoubleClick
478 //-------------------------------------------------------------------------------------------------------------------------------------------------
479 // Frame N+0 (mouse button is down) - true - true
480 // ... - - - -
481 // Frame N + RepeatDelay true true - true
482 // ... - - - -
483 // Frame N + RepeatDelay + RepeatRate*N true true - true
484 //-------------------------------------------------------------------------------------------------------------------------------------------------
485
486 // - FIXME: For refactor we could output flags, incl mouse hovered vs nav keyboard vs nav triggered etc.
487 // And better standardize how widgets use 'GetColor32((held && hovered) ? ... : hovered ? ...)' vs 'GetColor32(held ? ... : hovered ? ...);'
488 // For mouse feedback we typically prefer the 'held && hovered' test, but for nav feedback not always. Outputting hovered=true on Activation may be misleading.
489 // - Since v1.91.2 (Sept 2024) we included io.ConfigDebugHighlightIdConflicts feature.
490 // One idiom which was previously valid which will now emit a warning is when using multiple overlayed ButtonBehavior()
491 // with same ID and different MouseButton (see #8030). You can fix it by:
492 // (1) switching to use a single ButtonBehavior() with multiple _MouseButton flags.
493 // or (2) surrounding those calls with PushItemFlag(ImGuiItemFlags_AllowDuplicateId, true); ... PopItemFlag()
494 bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
495 {
496 ImGuiContext& g = *GImGui;
497 ImGuiWindow* window = GetCurrentWindow();
498
499 // Default behavior inherited from item flags
500 // Note that _both_ ButtonFlags and ItemFlags are valid sources, so copy one into the item_flags and only check that.
501 ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.ItemFlags : g.CurrentItemFlags);
502 if (flags & ImGuiButtonFlags_AllowOverlap)
503 item_flags |= ImGuiItemFlags_AllowOverlap;
504
505 // Default only reacts to left mouse button
506 if ((flags & ImGuiButtonFlags_MouseButtonMask_) == 0)
507 flags |= ImGuiButtonFlags_MouseButtonLeft;
508
509 // Default behavior requires click + release inside bounding box
510 if ((flags & ImGuiButtonFlags_PressedOnMask_) == 0)
511 flags |= (item_flags & ImGuiItemFlags_ButtonRepeat) ? ImGuiButtonFlags_PressedOnClick : ImGuiButtonFlags_PressedOnDefault_;
512
513 ImGuiWindow* backup_hovered_window = g.HoveredWindow;
514 const bool flatten_hovered_children = (flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredWindow && g.HoveredWindow->RootWindow == window;
515 if (flatten_hovered_children)
516 g.HoveredWindow = window;
517
518 #ifdef IMGUI_ENABLE_TEST_ENGINE
519 // Alternate registration spot, for when caller didn't use ItemAdd()
520 if (g.LastItemData.ID != id)
521 IMGUI_TEST_ENGINE_ITEM_ADD(id, bb, NULL);
522 #endif
523
524 bool pressed = false;
525 bool hovered = ItemHoverable(bb, id, item_flags);
526
527 // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button
528 if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
529 if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
530 {
531 hovered = true;
532 SetHoveredID(id);
533 if (g.HoveredIdTimer - g.IO.DeltaTime <= DRAGDROP_HOLD_TO_OPEN_TIMER && g.HoveredIdTimer >= DRAGDROP_HOLD_TO_OPEN_TIMER)
534 {
535 pressed = true;
536 g.DragDropHoldJustPressedId = id;
537 FocusWindow(window);
538 }
539 }
540
541 if (flatten_hovered_children)
542 g.HoveredWindow = backup_hovered_window;
543
544 // Mouse handling
545 const ImGuiID test_owner_id = (flags & ImGuiButtonFlags_NoTestKeyOwner) ? ImGuiKeyOwner_Any : id;
546 if (hovered)
547 {
548 IM_ASSERT(id != 0); // Lazily check inside rare path.
549
550 // Poll mouse buttons
551 // - 'mouse_button_clicked' is generally carried into ActiveIdMouseButton when setting ActiveId.
552 // - Technically we only need some values in one code path, but since this is gated by hovered test this is fine.
553 int mouse_button_clicked = -1;
554 int mouse_button_released = -1;
555 for (int button = 0; button < 3; button++)
556 if (flags & (ImGuiButtonFlags_MouseButtonLeft << button)) // Handle ImGuiButtonFlags_MouseButtonRight and ImGuiButtonFlags_MouseButtonMiddle here.
557 {
558 if (IsMouseClicked(button, ImGuiInputFlags_None, test_owner_id) && mouse_button_clicked == -1) { mouse_button_clicked = button; }
559 if (IsMouseReleased(button, test_owner_id) && mouse_button_released == -1) { mouse_button_released = button; }
560 }
561
562 // Process initial action
563 const bool mods_ok = !(flags & ImGuiButtonFlags_NoKeyModsAllowed) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt);
564 if (mods_ok)
565 {
566 if (mouse_button_clicked != -1 && g.ActiveId != id)
567 {
568 if (!(flags & ImGuiButtonFlags_NoSetKeyOwner))
569 SetKeyOwner(MouseButtonToKey(mouse_button_clicked), id);
570 if (flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClickReleaseAnywhere))
571 {
572 SetActiveID(id, window);
573 g.ActiveIdMouseButton = mouse_button_clicked;
574 if (!(flags & ImGuiButtonFlags_NoNavFocus))
575 {
576 SetFocusID(id, window);
577 FocusWindow(window);
578 }
579 else
580 {
581 FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child
582 }
583 }
584 if ((flags & ImGuiButtonFlags_PressedOnClick) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseClickedCount[mouse_button_clicked] == 2))
585 {
586 pressed = true;
587 if (flags & ImGuiButtonFlags_NoHoldingActiveId)
588 ClearActiveID();
589 else
590 SetActiveID(id, window); // Hold on ID
591 g.ActiveIdMouseButton = mouse_button_clicked;
592 if (!(flags & ImGuiButtonFlags_NoNavFocus))
593 {
594 SetFocusID(id, window);
595 FocusWindow(window);
596 }
597 else
598 {
599 FocusWindow(window, ImGuiFocusRequestFlags_RestoreFocusedChild); // Still need to focus and bring to front, but try to avoid losing NavId when navigating a child
600 }
601 }
602 }
603 if (flags & ImGuiButtonFlags_PressedOnRelease)
604 {
605 if (mouse_button_released != -1)
606 {
607 const bool has_repeated_at_least_once = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button_released] >= g.IO.KeyRepeatDelay; // Repeat mode trumps on release behavior
608 if (!has_repeated_at_least_once)
609 pressed = true;
610 if (!(flags & ImGuiButtonFlags_NoNavFocus))
611 SetFocusID(id, window); // FIXME: Lack of FocusWindow() call here is inconsistent with other paths. Research why.
612 ClearActiveID();
613 }
614 }
615
616 // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
617 // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
618 if (g.ActiveId == id && (item_flags & ImGuiItemFlags_ButtonRepeat))
619 if (g.IO.MouseDownDuration[g.ActiveIdMouseButton] > 0.0f && IsMouseClicked(g.ActiveIdMouseButton, ImGuiInputFlags_Repeat, test_owner_id))
620 pressed = true;
621 }
622
623 if (pressed && g.IO.ConfigNavCursorVisibleAuto)
624 g.NavCursorVisible = false;
625 }
626
627 // Keyboard/Gamepad navigation handling
628 // We report navigated and navigation-activated items as hovered but we don't set g.HoveredId to not interfere with mouse.
629 if (g.NavId == id && g.NavCursorVisible && g.NavHighlightItemUnderNav)
630 if (!(flags & ImGuiButtonFlags_NoHoveredOnFocus))
631 hovered = true;
632 if (g.NavActivateDownId == id)
633 {
634 bool nav_activated_by_code = (g.NavActivateId == id);
635 bool nav_activated_by_inputs = (g.NavActivatePressedId == id);
636 if (!nav_activated_by_inputs && (item_flags & ImGuiItemFlags_ButtonRepeat))
637 {
638 // Avoid pressing multiple keys from triggering excessive amount of repeat events
639 const ImGuiKeyData* key1 = GetKeyData(ImGuiKey_Space);
640 const ImGuiKeyData* key2 = GetKeyData(ImGuiKey_Enter);
641 const ImGuiKeyData* key3 = GetKeyData(ImGuiKey_NavGamepadActivate);
642 const float t1 = ImMax(ImMax(key1->DownDuration, key2->DownDuration), key3->DownDuration);
643 nav_activated_by_inputs = CalcTypematicRepeatAmount(t1 - g.IO.DeltaTime, t1, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
644 }
645 if (nav_activated_by_code || nav_activated_by_inputs)
646 {
647 // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.
648 pressed = true;
649 SetActiveID(id, window);
650 g.ActiveIdSource = g.NavInputSource;
651 if (!(flags & ImGuiButtonFlags_NoNavFocus) && !(g.NavActivateFlags & ImGuiActivateFlags_FromShortcut))
652 SetFocusID(id, window);
653 if (g.NavActivateFlags & ImGuiActivateFlags_FromShortcut)
654 g.ActiveIdFromShortcut = true;
655 }
656 }
657
658 // Process while held
659 bool held = false;
660 if (g.ActiveId == id)
661 {
662 if (g.ActiveIdSource == ImGuiInputSource_Mouse)
663 {
664 if (g.ActiveIdIsJustActivated)
665 g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
666
667 const int mouse_button = g.ActiveIdMouseButton;
668 if (mouse_button == -1)
669 {
670 // Fallback for the rare situation were g.ActiveId was set programmatically or from another widget (e.g. #6304).
671 ClearActiveID();
672 }
673 else if (IsMouseDown(mouse_button, test_owner_id))
674 {
675 held = true;
676 }
677 else
678 {
679 bool release_in = hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease) != 0;
680 bool release_anywhere = (flags & ImGuiButtonFlags_PressedOnClickReleaseAnywhere) != 0;
681 if ((release_in || release_anywhere) && !g.DragDropActive)
682 {
683 // Report as pressed when releasing the mouse (this is the most common path)
684 bool is_double_click_release = (flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseReleased[mouse_button] && g.IO.MouseClickedLastCount[mouse_button] == 2;
685 bool is_repeating_already = (item_flags & ImGuiItemFlags_ButtonRepeat) && g.IO.MouseDownDurationPrev[mouse_button] >= g.IO.KeyRepeatDelay; // Repeat mode trumps <on release>
686 bool is_button_avail_or_owned = TestKeyOwner(MouseButtonToKey(mouse_button), test_owner_id);
687 if (!is_double_click_release && !is_repeating_already && is_button_avail_or_owned)
688 pressed = true;
689 }
690 ClearActiveID();
691 }
692 if (!(flags & ImGuiButtonFlags_NoNavFocus) && g.IO.ConfigNavCursorVisibleAuto)
693 g.NavCursorVisible = false;
694 }
695 else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
696 {
697 // When activated using Nav, we hold on the ActiveID until activation button is released
698 if (g.NavActivateDownId == id)
699 held = true; // hovered == true not true as we are already likely hovered on direct activation.
700 else
701 ClearActiveID();
702 }
703 if (pressed)
704 g.ActiveIdHasBeenPressedBefore = true;
705 }
706
707 // Activation highlight (this may be a remote activation)
708 if (g.NavHighlightActivatedId == id)
709 hovered = true;
710
711 if (out_hovered) *out_hovered = hovered;
712 if (out_held) *out_held = held;
713
714 return pressed;
715 }
716
717 bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
718 {
719 ImGuiWindow* window = GetCurrentWindow();
720 if (window->SkipItems)
721 return false;
722
723 ImGuiContext& g = *GImGui;
724 const ImGuiStyle& style = g.Style;
725 const ImGuiID id = window->GetID(label);
726 const ImVec2 label_size = CalcTextSize(label, NULL, true);
727
728 ImVec2 pos = window->DC.CursorPos;
729 if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
730 pos.y += window->DC.CurrLineTextBaseOffset - style.FramePadding.y;
731 ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
732
733 const ImRect bb(pos, pos + size);
734 ItemSize(size, style.FramePadding.y);
735 if (!ItemAdd(bb, id))
736 return false;
737
738 bool hovered, held;
739 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
740
741 // Render
742 const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
743 RenderNavCursor(bb, id);
744 RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
745
746 if (g.LogEnabled)
747 LogSetNextTextDecoration("[", "]");
748 RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
749
750 // Automatically close popups
751 //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
752 // CloseCurrentPopup();
753
754 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
755 return pressed;
756 }
757
758 bool ImGui::Button(const char* label, const ImVec2& size_arg)
759 {
760 return ButtonEx(label, size_arg, ImGuiButtonFlags_None);
761 }
762
763 // Small buttons fits within text without additional vertical spacing.
764 bool ImGui::SmallButton(const char* label)
765 {
766 ImGuiContext& g = *GImGui;
767 float backup_padding_y = g.Style.FramePadding.y;
768 g.Style.FramePadding.y = 0.0f;
769 bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine);
770 g.Style.FramePadding.y = backup_padding_y;
771 return pressed;
772 }
773
774 // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
775 // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)
776 bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg, ImGuiButtonFlags flags)
777 {
778 ImGuiContext& g = *GImGui;
779 ImGuiWindow* window = GetCurrentWindow();
780 if (window->SkipItems)
781 return false;
782
783 // Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size.
784 IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f);
785
786 const ImGuiID id = window->GetID(str_id);
787 ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
788 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
789 ItemSize(size);
790 if (!ItemAdd(bb, id, NULL, (flags & ImGuiButtonFlags_EnableNav) ? ImGuiItemFlags_None : ImGuiItemFlags_NoNav))
791 return false;
792
793 bool hovered, held;
794 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
795 RenderNavCursor(bb, id);
796
797 IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags);
798 return pressed;
799 }
800
801 bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags)
802 {
803 ImGuiContext& g = *GImGui;
804 ImGuiWindow* window = GetCurrentWindow();
805 if (window->SkipItems)
806 return false;
807
808 const ImGuiID id = window->GetID(str_id);
809 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
810 const float default_size = GetFrameHeight();
811 ItemSize(size, (size.y >= default_size) ? g.Style.FramePadding.y : -1.0f);
812 if (!ItemAdd(bb, id))
813 return false;
814
815 bool hovered, held;
816 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
817
818 // Render
819 const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
820 const ImU32 text_col = GetColorU32(ImGuiCol_Text);
821 RenderNavCursor(bb, id);
822 RenderFrame(bb.Min, bb.Max, bg_col, true, g.Style.FrameRounding);
823 RenderArrow(window->DrawList, bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), text_col, dir);
824
825 IMGUI_TEST_ENGINE_ITEM_INFO(id, str_id, g.LastItemData.StatusFlags);
826 return pressed;
827 }
828
829 bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)
830 {
831 float sz = GetFrameHeight();
832 return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), ImGuiButtonFlags_None);
833 }
834
835 // Button to close a window
836 bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos)
837 {
838 ImGuiContext& g = *GImGui;
839 ImGuiWindow* window = g.CurrentWindow;
840
841 // Tweak 1: Shrink hit-testing area if button covers an abnormally large proportion of the visible region. That's in order to facilitate moving the window away. (#3825)
842 // This may better be applied as a general hit-rect reduction mechanism for all widgets to ensure the area to move window is always accessible?
843 const ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize));
844 ImRect bb_interact = bb;
845 const float area_to_visible_ratio = window->OuterRectClipped.GetArea() / bb.GetArea();
846 if (area_to_visible_ratio < 1.5f)
847 bb_interact.Expand(ImTrunc(bb_interact.GetSize() * -0.25f));
848
849 // Tweak 2: We intentionally allow interaction when clipped so that a mechanical Alt,Right,Activate sequence can always close a window.
850 // (this isn't the common behavior of buttons, but it doesn't affect the user because navigation tends to keep items visible in scrolling layer).
851 bool is_clipped = !ItemAdd(bb_interact, id);
852
853 bool hovered, held;
854 bool pressed = ButtonBehavior(bb_interact, id, &hovered, &held);
855 if (is_clipped)
856 return pressed;
857
858 // Render
859 ImU32 bg_col = GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered);
860 if (hovered)
861 window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col);
862 RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact);
863 ImU32 cross_col = GetColorU32(ImGuiCol_Text);
864 ImVec2 cross_center = bb.GetCenter() - ImVec2(0.5f, 0.5f);
865 float cross_extent = g.FontSize * 0.5f * 0.7071f - 1.0f;
866 window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, +cross_extent), cross_center + ImVec2(-cross_extent, -cross_extent), cross_col, 1.0f);
867 window->DrawList->AddLine(cross_center + ImVec2(+cross_extent, -cross_extent), cross_center + ImVec2(-cross_extent, +cross_extent), cross_col, 1.0f);
868
869 return pressed;
870 }
871
872 bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos)
873 {
874 ImGuiContext& g = *GImGui;
875 ImGuiWindow* window = g.CurrentWindow;
876
877 ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize));
878 bool is_clipped = !ItemAdd(bb, id);
879 bool hovered, held;
880 bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None);
881 if (is_clipped)
882 return pressed;
883
884 // Render
885 ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
886 ImU32 text_col = GetColorU32(ImGuiCol_Text);
887 if (hovered || held)
888 window->DrawList->AddRectFilled(bb.Min, bb.Max, bg_col);
889 RenderNavCursor(bb, id, ImGuiNavRenderCursorFlags_Compact);
890 RenderArrow(window->DrawList, bb.Min, text_col, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
891
892 // Switch to moving the window after mouse is moved beyond the initial drag threshold
893 if (IsItemActive() && IsMouseDragging(0))
894 StartMouseMovingWindow(window);
895
896 return pressed;
897 }
898
899 ImGuiID ImGui::GetWindowScrollbarID(ImGuiWindow* window, ImGuiAxis axis)
900 {
901 return window->GetID(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY");
902 }
903
904 // Return scrollbar rectangle, must only be called for corresponding axis if window->ScrollbarX/Y is set.
905 ImRect ImGui::GetWindowScrollbarRect(ImGuiWindow* window, ImGuiAxis axis)
906 {
907 const ImRect outer_rect = window->Rect();
908 const ImRect inner_rect = window->InnerRect;
909 const float border_size = window->WindowBorderSize;
910 const float scrollbar_size = window->ScrollbarSizes[axis ^ 1]; // (ScrollbarSizes.x = width of Y scrollbar; ScrollbarSizes.y = height of X scrollbar)
911 IM_ASSERT(scrollbar_size > 0.0f);
912 if (axis == ImGuiAxis_X)
913 return ImRect(inner_rect.Min.x, ImMax(outer_rect.Min.y, outer_rect.Max.y - border_size - scrollbar_size), inner_rect.Max.x - border_size, outer_rect.Max.y - border_size);
914 else
915 return ImRect(ImMax(outer_rect.Min.x, outer_rect.Max.x - border_size - scrollbar_size), inner_rect.Min.y, outer_rect.Max.x - border_size, inner_rect.Max.y - border_size);
916 }
917
918 void ImGui::Scrollbar(ImGuiAxis axis)
919 {
920 ImGuiContext& g = *GImGui;
921 ImGuiWindow* window = g.CurrentWindow;
922 const ImGuiID id = GetWindowScrollbarID(window, axis);
923
924 // Calculate scrollbar bounding box
925 ImRect bb = GetWindowScrollbarRect(window, axis);
926 ImDrawFlags rounding_corners = ImDrawFlags_RoundCornersNone;
927 if (axis == ImGuiAxis_X)
928 {
929 rounding_corners |= ImDrawFlags_RoundCornersBottomLeft;
930 if (!window->ScrollbarY)
931 rounding_corners |= ImDrawFlags_RoundCornersBottomRight;
932 }
933 else
934 {
935 if ((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar))
936 rounding_corners |= ImDrawFlags_RoundCornersTopRight;
937 if (!window->ScrollbarX)
938 rounding_corners |= ImDrawFlags_RoundCornersBottomRight;
939 }
940 float size_visible = window->InnerRect.Max[axis] - window->InnerRect.Min[axis];
941 float size_contents = window->ContentSize[axis] + window->WindowPadding[axis] * 2.0f;
942 ImS64 scroll = (ImS64)window->Scroll[axis];
943 ScrollbarEx(bb, id, axis, &scroll, (ImS64)size_visible, (ImS64)size_contents, rounding_corners);
944 window->Scroll[axis] = (float)scroll;
945 }
946
947 // Vertical/Horizontal scrollbar
948 // The entire piece of code below is rather confusing because:
949 // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
950 // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
951 // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
952 // Still, the code should probably be made simpler..
953 bool ImGui::ScrollbarEx(const ImRect& bb_frame, ImGuiID id, ImGuiAxis axis, ImS64* p_scroll_v, ImS64 size_visible_v, ImS64 size_contents_v, ImDrawFlags draw_rounding_flags)
954 {
955 ImGuiContext& g = *GImGui;
956 ImGuiWindow* window = g.CurrentWindow;
957 if (window->SkipItems)
958 return false;
959
960 const float bb_frame_width = bb_frame.GetWidth();
961 const float bb_frame_height = bb_frame.GetHeight();
962 if (bb_frame_width <= 0.0f || bb_frame_height <= 0.0f)
963 return false;
964
965 // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the window resize grab)
966 float alpha = 1.0f;
967 if ((axis == ImGuiAxis_Y) && bb_frame_height < g.FontSize + g.Style.FramePadding.y * 2.0f)
968 alpha = ImSaturate((bb_frame_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f));
969 if (alpha <= 0.0f)
970 return false;
971
972 const ImGuiStyle& style = g.Style;
973 const bool allow_interaction = (alpha >= 1.0f);
974
975 ImRect bb = bb_frame;
976 bb.Expand(ImVec2(-ImClamp(IM_TRUNC((bb_frame_width - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp(IM_TRUNC((bb_frame_height - 2.0f) * 0.5f), 0.0f, 3.0f)));
977
978 // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
979 const float scrollbar_size_v = (axis == ImGuiAxis_X) ? bb.GetWidth() : bb.GetHeight();
980
981 // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
982 // But we maintain a minimum size in pixel to allow for the user to still aim inside.
983 IM_ASSERT(ImMax(size_contents_v, size_visible_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.
984 const ImS64 win_size_v = ImMax(ImMax(size_contents_v, size_visible_v), (ImS64)1);
985 const float grab_h_pixels = ImClamp(scrollbar_size_v * ((float)size_visible_v / (float)win_size_v), style.GrabMinSize, scrollbar_size_v);
986 const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
987
988 // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
989 bool held = false;
990 bool hovered = false;
991 ItemAdd(bb_frame, id, NULL, ImGuiItemFlags_NoNav);
992 ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus);
993
994 const ImS64 scroll_max = ImMax((ImS64)1, size_contents_v - size_visible_v);
995 float scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max);
996 float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Grab position in normalized space
997 if (held && allow_interaction && grab_h_norm < 1.0f)
998 {
999 const float scrollbar_pos_v = bb.Min[axis];
1000 const float mouse_pos_v = g.IO.MousePos[axis];
1001
1002 // Click position in scrollbar normalized space (0.0f->1.0f)
1003 const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
1004
1005 const int held_dir = (clicked_v_norm < grab_v_norm) ? -1 : (clicked_v_norm > grab_v_norm + grab_h_norm) ? +1 : 0;
1006 if (g.ActiveIdIsJustActivated)
1007 {
1008 // On initial click when held_dir == 0 (clicked over grab): calculate the distance between mouse and the center of the grab
1009 const bool scroll_to_clicked_location = (g.IO.ConfigScrollbarScrollByPage == false || g.IO.KeyShift || held_dir == 0);
1010 g.ScrollbarSeekMode = scroll_to_clicked_location ? 0 : (short)held_dir;
1011 g.ScrollbarClickDeltaToGrabCenter = (held_dir == 0 && !g.IO.KeyShift) ? clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f : 0.0f;
1012 }
1013
1014 // Apply scroll (p_scroll_v will generally point on one member of window->Scroll)
1015 // It is ok to modify Scroll here because we are being called in Begin() after the calculation of ContentSize and before setting up our starting position
1016 if (g.ScrollbarSeekMode == 0)
1017 {
1018 // Absolute seeking
1019 const float scroll_v_norm = ImSaturate((clicked_v_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm * 0.5f) / (1.0f - grab_h_norm));
1020 *p_scroll_v = (ImS64)(scroll_v_norm * scroll_max);
1021 }
1022 else
1023 {
1024 // Page by page
1025 if (IsMouseClicked(ImGuiMouseButton_Left, ImGuiInputFlags_Repeat) && held_dir == g.ScrollbarSeekMode)
1026 {
1027 float page_dir = (g.ScrollbarSeekMode > 0.0f) ? +1.0f : -1.0f;
1028 *p_scroll_v = ImClamp(*p_scroll_v + (ImS64)(page_dir * size_visible_v), (ImS64)0, scroll_max);
1029 }
1030 }
1031
1032 // Update values for rendering
1033 scroll_ratio = ImSaturate((float)*p_scroll_v / (float)scroll_max);
1034 grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
1035
1036 // Update distance to grab now that we have seek'ed and saturated
1037 //if (seek_absolute)
1038 // g.ScrollbarClickDeltaToGrabCenter = clicked_v_norm - grab_v_norm - grab_h_norm * 0.5f;
1039 }
1040
1041 // Render
1042 const ImU32 bg_col = GetColorU32(ImGuiCol_ScrollbarBg);
1043 const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha);
1044 window->DrawList->AddRectFilled(bb_frame.Min, bb_frame.Max, bg_col, window->WindowRounding, draw_rounding_flags);
1045 ImRect grab_rect;
1046 if (axis == ImGuiAxis_X)
1047 grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y);
1048 else
1049 grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels);
1050 window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);
1051
1052 return held;
1053 }
1054
1055 // - Read about ImTextureID here: https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
1056 // - 'uv0' and 'uv1' are texture coordinates. Read about them from the same link above.
1057 void ImGui::Image(ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
1058 {
1059 ImGuiWindow* window = GetCurrentWindow();
1060 if (window->SkipItems)
1061 return;
1062
1063 const float border_size = (border_col.w > 0.0f) ? 1.0f : 0.0f;
1064 const ImVec2 padding(border_size, border_size);
1065 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f);
1066 ItemSize(bb);
1067 if (!ItemAdd(bb, 0))
1068 return;
1069
1070 // Render
1071 if (border_size > 0.0f)
1072 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f, ImDrawFlags_None, border_size);
1073 window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
1074 }
1075
1076 bool ImGui::ImageButtonEx(ImGuiID id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col, ImGuiButtonFlags flags)
1077 {
1078 ImGuiContext& g = *GImGui;
1079 ImGuiWindow* window = GetCurrentWindow();
1080 if (window->SkipItems)
1081 return false;
1082
1083 const ImVec2 padding = g.Style.FramePadding;
1084 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + image_size + padding * 2.0f);
1085 ItemSize(bb);
1086 if (!ItemAdd(bb, id))
1087 return false;
1088
1089 bool hovered, held;
1090 bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
1091
1092 // Render
1093 const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
1094 RenderNavCursor(bb, id);
1095 RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, g.Style.FrameRounding));
1096 if (bg_col.w > 0.0f)
1097 window->DrawList->AddRectFilled(bb.Min + padding, bb.Max - padding, GetColorU32(bg_col));
1098 window->DrawList->AddImage(user_texture_id, bb.Min + padding, bb.Max - padding, uv0, uv1, GetColorU32(tint_col));
1099
1100 return pressed;
1101 }
1102
1103 // - ImageButton() adds style.FramePadding*2.0f to provided size. This is in order to facilitate fitting an image in a button.
1104 // - ImageButton() draws a background based on regular Button() color + optionally an inner background if specified. (#8165) // FIXME: Maybe that's not the best design?
1105 bool ImGui::ImageButton(const char* str_id, ImTextureID user_texture_id, const ImVec2& image_size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& bg_col, const ImVec4& tint_col)
1106 {
1107 ImGuiContext& g = *GImGui;
1108 ImGuiWindow* window = g.CurrentWindow;
1109 if (window->SkipItems)
1110 return false;
1111
1112 return ImageButtonEx(window->GetID(str_id), user_texture_id, image_size, uv0, uv1, bg_col, tint_col);
1113 }
1114
1115 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1116 // Legacy API obsoleted in 1.89. Two differences with new ImageButton()
1117 // - old ImageButton() used ImTextureID as item id (created issue with multiple buttons with same image, transient texture id values, opaque computation of ID)
1118 // - new ImageButton() requires an explicit 'const char* str_id'
1119 // - old ImageButton() had frame_padding' override argument.
1120 // - new ImageButton() always use style.FramePadding.
1121 /*
1122 bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
1123 {
1124 // Default to using texture ID as ID. User can still push string/integer prefixes.
1125 PushID((ImTextureID)(intptr_t)user_texture_id);
1126 if (frame_padding >= 0)
1127 PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2((float)frame_padding, (float)frame_padding));
1128 bool ret = ImageButton("", user_texture_id, size, uv0, uv1, bg_col, tint_col);
1129 if (frame_padding >= 0)
1130 PopStyleVar();
1131 PopID();
1132 return ret;
1133 }
1134 */
1135 #endif // #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1136
1137 bool ImGui::Checkbox(const char* label, bool* v)
1138 {
1139 ImGuiWindow* window = GetCurrentWindow();
1140 if (window->SkipItems)
1141 return false;
1142
1143 ImGuiContext& g = *GImGui;
1144 const ImGuiStyle& style = g.Style;
1145 const ImGuiID id = window->GetID(label);
1146 const ImVec2 label_size = CalcTextSize(label, NULL, true);
1147
1148 const float square_sz = GetFrameHeight();
1149 const ImVec2 pos = window->DC.CursorPos;
1150 const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));
1151 ItemSize(total_bb, style.FramePadding.y);
1152 const bool is_visible = ItemAdd(total_bb, id);
1153 const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
1154 if (!is_visible)
1155 if (!is_multi_select || !g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(total_bb)) // Extra layer of "no logic clip" for box-select support
1156 {
1157 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));
1158 return false;
1159 }
1160
1161 // Range-Selection/Multi-selection support (header)
1162 bool checked = *v;
1163 if (is_multi_select)
1164 MultiSelectItemHeader(id, &checked, NULL);
1165
1166 bool hovered, held;
1167 bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
1168
1169 // Range-Selection/Multi-selection support (footer)
1170 if (is_multi_select)
1171 MultiSelectItemFooter(id, &checked, &pressed);
1172 else if (pressed)
1173 checked = !checked;
1174
1175 if (*v != checked)
1176 {
1177 *v = checked;
1178 pressed = true; // return value
1179 MarkItemEdited(id);
1180 }
1181
1182 const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
1183 const bool mixed_value = (g.LastItemData.ItemFlags & ImGuiItemFlags_MixedValue) != 0;
1184 if (is_visible)
1185 {
1186 RenderNavCursor(total_bb, id);
1187 RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
1188 ImU32 check_col = GetColorU32(ImGuiCol_CheckMark);
1189 if (mixed_value)
1190 {
1191 // Undocumented tristate/mixed/indeterminate checkbox (#2644)
1192 // This may seem awkwardly designed because the aim is to make ImGuiItemFlags_MixedValue supported by all widgets (not just checkbox)
1193 ImVec2 pad(ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)), ImMax(1.0f, IM_TRUNC(square_sz / 3.6f)));
1194 window->DrawList->AddRectFilled(check_bb.Min + pad, check_bb.Max - pad, check_col, style.FrameRounding);
1195 }
1196 else if (*v)
1197 {
1198 const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f));
1199 RenderCheckMark(window->DrawList, check_bb.Min + ImVec2(pad, pad), check_col, square_sz - pad * 2.0f);
1200 }
1201 }
1202 const ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y);
1203 if (g.LogEnabled)
1204 LogRenderedText(&label_pos, mixed_value ? "[~]" : *v ? "[x]" : "[ ]");
1205 if (is_visible && label_size.x > 0.0f)
1206 RenderText(label_pos, label);
1207
1208 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0));
1209 return pressed;
1210 }
1211
1212 template<typename T>
1213 bool ImGui::CheckboxFlagsT(const char* label, T* flags, T flags_value)
1214 {
1215 bool all_on = (*flags & flags_value) == flags_value;
1216 bool any_on = (*flags & flags_value) != 0;
1217 bool pressed;
1218 if (!all_on && any_on)
1219 {
1220 ImGuiContext& g = *GImGui;
1221 g.NextItemData.ItemFlags |= ImGuiItemFlags_MixedValue;
1222 pressed = Checkbox(label, &all_on);
1223 }
1224 else
1225 {
1226 pressed = Checkbox(label, &all_on);
1227
1228 }
1229 if (pressed)
1230 {
1231 if (all_on)
1232 *flags |= flags_value;
1233 else
1234 *flags &= ~flags_value;
1235 }
1236 return pressed;
1237 }
1238
1239 bool ImGui::CheckboxFlags(const char* label, int* flags, int flags_value)
1240 {
1241 return CheckboxFlagsT(label, flags, flags_value);
1242 }
1243
1244 bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
1245 {
1246 return CheckboxFlagsT(label, flags, flags_value);
1247 }
1248
1249 bool ImGui::CheckboxFlags(const char* label, ImS64* flags, ImS64 flags_value)
1250 {
1251 return CheckboxFlagsT(label, flags, flags_value);
1252 }
1253
1254 bool ImGui::CheckboxFlags(const char* label, ImU64* flags, ImU64 flags_value)
1255 {
1256 return CheckboxFlagsT(label, flags, flags_value);
1257 }
1258
1259 bool ImGui::RadioButton(const char* label, bool active)
1260 {
1261 ImGuiWindow* window = GetCurrentWindow();
1262 if (window->SkipItems)
1263 return false;
1264
1265 ImGuiContext& g = *GImGui;
1266 const ImGuiStyle& style = g.Style;
1267 const ImGuiID id = window->GetID(label);
1268 const ImVec2 label_size = CalcTextSize(label, NULL, true);
1269
1270 const float square_sz = GetFrameHeight();
1271 const ImVec2 pos = window->DC.CursorPos;
1272 const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz));
1273 const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f));
1274 ItemSize(total_bb, style.FramePadding.y);
1275 if (!ItemAdd(total_bb, id))
1276 return false;
1277
1278 ImVec2 center = check_bb.GetCenter();
1279 center.x = IM_ROUND(center.x);
1280 center.y = IM_ROUND(center.y);
1281 const float radius = (square_sz - 1.0f) * 0.5f;
1282
1283 bool hovered, held;
1284 bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
1285 if (pressed)
1286 MarkItemEdited(id);
1287
1288 RenderNavCursor(total_bb, id);
1289 const int num_segment = window->DrawList->_CalcCircleAutoSegmentCount(radius);
1290 window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), num_segment);
1291 if (active)
1292 {
1293 const float pad = ImMax(1.0f, IM_TRUNC(square_sz / 6.0f));
1294 window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark));
1295 }
1296
1297 if (style.FrameBorderSize > 0.0f)
1298 {
1299 window->DrawList->AddCircle(center + ImVec2(1, 1), radius, GetColorU32(ImGuiCol_BorderShadow), num_segment, style.FrameBorderSize);
1300 window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), num_segment, style.FrameBorderSize);
1301 }
1302
1303 ImVec2 label_pos = ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y);
1304 if (g.LogEnabled)
1305 LogRenderedText(&label_pos, active ? "(x)" : "( )");
1306 if (label_size.x > 0.0f)
1307 RenderText(label_pos, label);
1308
1309 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
1310 return pressed;
1311 }
1312
1313 // FIXME: This would work nicely if it was a public template, e.g. 'template<T> RadioButton(const char* label, T* v, T v_button)', but I'm not sure how we would expose it..
1314 bool ImGui::RadioButton(const char* label, int* v, int v_button)
1315 {
1316 const bool pressed = RadioButton(label, *v == v_button);
1317 if (pressed)
1318 *v = v_button;
1319 return pressed;
1320 }
1321
1322 // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
1323 void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
1324 {
1325 ImGuiWindow* window = GetCurrentWindow();
1326 if (window->SkipItems)
1327 return;
1328
1329 ImGuiContext& g = *GImGui;
1330 const ImGuiStyle& style = g.Style;
1331
1332 ImVec2 pos = window->DC.CursorPos;
1333 ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y * 2.0f);
1334 ImRect bb(pos, pos + size);
1335 ItemSize(size, style.FramePadding.y);
1336 if (!ItemAdd(bb, 0))
1337 return;
1338
1339 // Fraction < 0.0f will display an indeterminate progress bar animation
1340 // The value must be animated along with time, so e.g. passing '-1.0f * ImGui::GetTime()' as fraction works.
1341 const bool is_indeterminate = (fraction < 0.0f);
1342 if (!is_indeterminate)
1343 fraction = ImSaturate(fraction);
1344
1345 // Out of courtesy we accept a NaN fraction without crashing
1346 float fill_n0 = 0.0f;
1347 float fill_n1 = (fraction == fraction) ? fraction : 0.0f;
1348
1349 if (is_indeterminate)
1350 {
1351 const float fill_width_n = 0.2f;
1352 fill_n0 = ImFmod(-fraction, 1.0f) * (1.0f + fill_width_n) - fill_width_n;
1353 fill_n1 = ImSaturate(fill_n0 + fill_width_n);
1354 fill_n0 = ImSaturate(fill_n0);
1355 }
1356
1357 // Render
1358 RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
1359 bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));
1360 RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), fill_n0, fill_n1, style.FrameRounding);
1361
1362 // Default displaying the fraction as percentage string, but user can override it
1363 // Don't display text for indeterminate bars by default
1364 char overlay_buf[32];
1365 if (!is_indeterminate || overlay != NULL)
1366 {
1367 if (!overlay)
1368 {
1369 ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction * 100 + 0.01f);
1370 overlay = overlay_buf;
1371 }
1372
1373 ImVec2 overlay_size = CalcTextSize(overlay, NULL);
1374 if (overlay_size.x > 0.0f)
1375 {
1376 float text_x = is_indeterminate ? (bb.Min.x + bb.Max.x - overlay_size.x) * 0.5f : ImLerp(bb.Min.x, bb.Max.x, fill_n1) + style.ItemSpacing.x;
1377 RenderTextClipped(ImVec2(ImClamp(text_x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f, 0.5f), &bb);
1378 }
1379 }
1380 }
1381
1382 void ImGui::Bullet()
1383 {
1384 ImGuiWindow* window = GetCurrentWindow();
1385 if (window->SkipItems)
1386 return;
1387
1388 ImGuiContext& g = *GImGui;
1389 const ImGuiStyle& style = g.Style;
1390 const float line_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), g.FontSize);
1391 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
1392 ItemSize(bb);
1393 if (!ItemAdd(bb, 0))
1394 {
1395 SameLine(0, style.FramePadding.x * 2);
1396 return;
1397 }
1398
1399 // Render and stay on same line
1400 ImU32 text_col = GetColorU32(ImGuiCol_Text);
1401 RenderBullet(window->DrawList, bb.Min + ImVec2(style.FramePadding.x + g.FontSize * 0.5f, line_height * 0.5f), text_col);
1402 SameLine(0, style.FramePadding.x * 2.0f);
1403 }
1404
1405 // This is provided as a convenience for being an often requested feature.
1406 // FIXME-STYLE: we delayed adding as there is a larger plan to revamp the styling system.
1407 // Because of this we currently don't provide many styling options for this widget
1408 // (e.g. hovered/active colors are automatically inferred from a single color).
1409 bool ImGui::TextLink(const char* label)
1410 {
1411 ImGuiWindow* window = GetCurrentWindow();
1412 if (window->SkipItems)
1413 return false;
1414
1415 ImGuiContext& g = *GImGui;
1416 const ImGuiID id = window->GetID(label);
1417 const char* label_end = FindRenderedTextEnd(label);
1418
1419 ImVec2 pos = window->DC.CursorPos;
1420 ImVec2 size = CalcTextSize(label, label_end, true);
1421 ImRect bb(pos, pos + size);
1422 ItemSize(size, 0.0f);
1423 if (!ItemAdd(bb, id))
1424 return false;
1425
1426 bool hovered, held;
1427 bool pressed = ButtonBehavior(bb, id, &hovered, &held);
1428 RenderNavCursor(bb, id);
1429
1430 if (hovered)
1431 SetMouseCursor(ImGuiMouseCursor_Hand);
1432
1433 ImVec4 text_colf = g.Style.Colors[ImGuiCol_TextLink];
1434 ImVec4 line_colf = text_colf;
1435 {
1436 // FIXME-STYLE: Read comments above. This widget is NOT written in the same style as some earlier widgets,
1437 // as we are currently experimenting/planning a different styling system.
1438 float h, s, v;
1439 ColorConvertRGBtoHSV(text_colf.x, text_colf.y, text_colf.z, h, s, v);
1440 if (held || hovered)
1441 {
1442 v = ImSaturate(v + (held ? 0.4f : 0.3f));
1443 h = ImFmod(h + 0.02f, 1.0f);
1444 }
1445 ColorConvertHSVtoRGB(h, s, v, text_colf.x, text_colf.y, text_colf.z);
1446 v = ImSaturate(v - 0.20f);
1447 ColorConvertHSVtoRGB(h, s, v, line_colf.x, line_colf.y, line_colf.z);
1448 }
1449
1450 float line_y = bb.Max.y + ImFloor(g.Font->Descent * g.FontScale * 0.20f);
1451 window->DrawList->AddLine(ImVec2(bb.Min.x, line_y), ImVec2(bb.Max.x, line_y), GetColorU32(line_colf)); // FIXME-TEXT: Underline mode.
1452
1453 PushStyleColor(ImGuiCol_Text, GetColorU32(text_colf));
1454 RenderText(bb.Min, label, label_end);
1455 PopStyleColor();
1456
1457 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
1458 return pressed;
1459 }
1460
1461 void ImGui::TextLinkOpenURL(const char* label, const char* url)
1462 {
1463 ImGuiContext& g = *GImGui;
1464 if (url == NULL)
1465 url = label;
1466 if (TextLink(label))
1467 if (g.PlatformIO.Platform_OpenInShellFn != NULL)
1468 g.PlatformIO.Platform_OpenInShellFn(&g, url);
1469 SetItemTooltip(LocalizeGetMsg(ImGuiLocKey_OpenLink_s), url); // It is more reassuring for user to _always_ display URL when we same as label
1470 if (BeginPopupContextItem())
1471 {
1472 if (MenuItem(LocalizeGetMsg(ImGuiLocKey_CopyLink)))
1473 SetClipboardText(url);
1474 EndPopup();
1475 }
1476 }
1477
1478 //-------------------------------------------------------------------------
1479 // [SECTION] Widgets: Low-level Layout helpers
1480 //-------------------------------------------------------------------------
1481 // - Spacing()
1482 // - Dummy()
1483 // - NewLine()
1484 // - AlignTextToFramePadding()
1485 // - SeparatorEx() [Internal]
1486 // - Separator()
1487 // - SplitterBehavior() [Internal]
1488 // - ShrinkWidths() [Internal]
1489 //-------------------------------------------------------------------------
1490
1491 void ImGui::Spacing()
1492 {
1493 ImGuiWindow* window = GetCurrentWindow();
1494 if (window->SkipItems)
1495 return;
1496 ItemSize(ImVec2(0, 0));
1497 }
1498
1499 void ImGui::Dummy(const ImVec2& size)
1500 {
1501 ImGuiWindow* window = GetCurrentWindow();
1502 if (window->SkipItems)
1503 return;
1504
1505 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
1506 ItemSize(size);
1507 ItemAdd(bb, 0);
1508 }
1509
1510 void ImGui::NewLine()
1511 {
1512 ImGuiWindow* window = GetCurrentWindow();
1513 if (window->SkipItems)
1514 return;
1515
1516 ImGuiContext& g = *GImGui;
1517 const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
1518 window->DC.LayoutType = ImGuiLayoutType_Vertical;
1519 window->DC.IsSameLine = false;
1520 if (window->DC.CurrLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
1521 ItemSize(ImVec2(0, 0));
1522 else
1523 ItemSize(ImVec2(0.0f, g.FontSize));
1524 window->DC.LayoutType = backup_layout_type;
1525 }
1526
1527 void ImGui::AlignTextToFramePadding()
1528 {
1529 ImGuiWindow* window = GetCurrentWindow();
1530 if (window->SkipItems)
1531 return;
1532
1533 ImGuiContext& g = *GImGui;
1534 window->DC.CurrLineSize.y = ImMax(window->DC.CurrLineSize.y, g.FontSize + g.Style.FramePadding.y * 2);
1535 window->DC.CurrLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, g.Style.FramePadding.y);
1536 }
1537
1538 // Horizontal/vertical separating line
1539 // FIXME: Surprisingly, this seemingly trivial widget is a victim of many different legacy/tricky layout issues.
1540 // Note how thickness == 1.0f is handled specifically as not moving CursorPos by 'thickness', but other values are.
1541 void ImGui::SeparatorEx(ImGuiSeparatorFlags flags, float thickness)
1542 {
1543 ImGuiWindow* window = GetCurrentWindow();
1544 if (window->SkipItems)
1545 return;
1546
1547 ImGuiContext& g = *GImGui;
1548 IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected
1549 IM_ASSERT(thickness > 0.0f);
1550
1551 if (flags & ImGuiSeparatorFlags_Vertical)
1552 {
1553 // Vertical separator, for menu bars (use current line height).
1554 float y1 = window->DC.CursorPos.y;
1555 float y2 = window->DC.CursorPos.y + window->DC.CurrLineSize.y;
1556 const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + thickness, y2));
1557 ItemSize(ImVec2(thickness, 0.0f));
1558 if (!ItemAdd(bb, 0))
1559 return;
1560
1561 // Draw
1562 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator));
1563 if (g.LogEnabled)
1564 LogText(" |");
1565 }
1566 else if (flags & ImGuiSeparatorFlags_Horizontal)
1567 {
1568 // Horizontal Separator
1569 float x1 = window->DC.CursorPos.x;
1570 float x2 = window->WorkRect.Max.x;
1571
1572 // Preserve legacy behavior inside Columns()
1573 // Before Tables API happened, we relied on Separator() to span all columns of a Columns() set.
1574 // We currently don't need to provide the same feature for tables because tables naturally have border features.
1575 ImGuiOldColumns* columns = (flags & ImGuiSeparatorFlags_SpanAllColumns) ? window->DC.CurrentColumns : NULL;
1576 if (columns)
1577 {
1578 x1 = window->Pos.x + window->DC.Indent.x; // Used to be Pos.x before 2023/10/03
1579 x2 = window->Pos.x + window->Size.x;
1580 PushColumnsBackground();
1581 }
1582
1583 // We don't provide our width to the layout so that it doesn't get feed back into AutoFit
1584 // FIXME: This prevents ->CursorMaxPos based bounding box evaluation from working (e.g. TableEndCell)
1585 const float thickness_for_layout = (thickness == 1.0f) ? 0.0f : thickness; // FIXME: See 1.70/1.71 Separator() change: makes legacy 1-px separator not affect layout yet. Should change.
1586 const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y + thickness));
1587 ItemSize(ImVec2(0.0f, thickness_for_layout));
1588
1589 if (ItemAdd(bb, 0))
1590 {
1591 // Draw
1592 window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator));
1593 if (g.LogEnabled)
1594 LogRenderedText(&bb.Min, "--------------------------------\n");
1595
1596 }
1597 if (columns)
1598 {
1599 PopColumnsBackground();
1600 columns->LineMinY = window->DC.CursorPos.y;
1601 }
1602 }
1603 }
1604
1605 void ImGui::Separator()
1606 {
1607 ImGuiContext& g = *GImGui;
1608 ImGuiWindow* window = g.CurrentWindow;
1609 if (window->SkipItems)
1610 return;
1611
1612 // Those flags should eventually be configurable by the user
1613 // FIXME: We cannot g.Style.SeparatorTextBorderSize for thickness as it relates to SeparatorText() which is a decorated separator, not defaulting to 1.0f.
1614 ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
1615
1616 // Only applies to legacy Columns() api as they relied on Separator() a lot.
1617 if (window->DC.CurrentColumns)
1618 flags |= ImGuiSeparatorFlags_SpanAllColumns;
1619
1620 SeparatorEx(flags, 1.0f);
1621 }
1622
1623 void ImGui::SeparatorTextEx(ImGuiID id, const char* label, const char* label_end, float extra_w)
1624 {
1625 ImGuiContext& g = *GImGui;
1626 ImGuiWindow* window = g.CurrentWindow;
1627 ImGuiStyle& style = g.Style;
1628
1629 const ImVec2 label_size = CalcTextSize(label, label_end, false);
1630 const ImVec2 pos = window->DC.CursorPos;
1631 const ImVec2 padding = style.SeparatorTextPadding;
1632
1633 const float separator_thickness = style.SeparatorTextBorderSize;
1634 const ImVec2 min_size(label_size.x + extra_w + padding.x * 2.0f, ImMax(label_size.y + padding.y * 2.0f, separator_thickness));
1635 const ImRect bb(pos, ImVec2(window->WorkRect.Max.x, pos.y + min_size.y));
1636 const float text_baseline_y = ImTrunc((bb.GetHeight() - label_size.y) * style.SeparatorTextAlign.y + 0.99999f); //ImMax(padding.y, ImFloor((style.SeparatorTextSize - label_size.y) * 0.5f));
1637 ItemSize(min_size, text_baseline_y);
1638 if (!ItemAdd(bb, id))
1639 return;
1640
1641 const float sep1_x1 = pos.x;
1642 const float sep2_x2 = bb.Max.x;
1643 const float seps_y = ImTrunc((bb.Min.y + bb.Max.y) * 0.5f + 0.99999f);
1644
1645 const float label_avail_w = ImMax(0.0f, sep2_x2 - sep1_x1 - padding.x * 2.0f);
1646 const ImVec2 label_pos(pos.x + padding.x + ImMax(0.0f, (label_avail_w - label_size.x - extra_w) * style.SeparatorTextAlign.x), pos.y + text_baseline_y); // FIXME-ALIGN
1647
1648 // This allows using SameLine() to position something in the 'extra_w'
1649 window->DC.CursorPosPrevLine.x = label_pos.x + label_size.x;
1650
1651 const ImU32 separator_col = GetColorU32(ImGuiCol_Separator);
1652 if (label_size.x > 0.0f)
1653 {
1654 const float sep1_x2 = label_pos.x - style.ItemSpacing.x;
1655 const float sep2_x1 = label_pos.x + label_size.x + extra_w + style.ItemSpacing.x;
1656 if (sep1_x2 > sep1_x1 && separator_thickness > 0.0f)
1657 window->DrawList->AddLine(ImVec2(sep1_x1, seps_y), ImVec2(sep1_x2, seps_y), separator_col, separator_thickness);
1658 if (sep2_x2 > sep2_x1 && separator_thickness > 0.0f)
1659 window->DrawList->AddLine(ImVec2(sep2_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness);
1660 if (g.LogEnabled)
1661 LogSetNextTextDecoration("---", NULL);
1662 RenderTextEllipsis(window->DrawList, label_pos, ImVec2(bb.Max.x, bb.Max.y + style.ItemSpacing.y), bb.Max.x, bb.Max.x, label, label_end, &label_size);
1663 }
1664 else
1665 {
1666 if (g.LogEnabled)
1667 LogText("---");
1668 if (separator_thickness > 0.0f)
1669 window->DrawList->AddLine(ImVec2(sep1_x1, seps_y), ImVec2(sep2_x2, seps_y), separator_col, separator_thickness);
1670 }
1671 }
1672
1673 void ImGui::SeparatorText(const char* label)
1674 {
1675 ImGuiWindow* window = GetCurrentWindow();
1676 if (window->SkipItems)
1677 return;
1678
1679 // The SeparatorText() vs SeparatorTextEx() distinction is designed to be considerate that we may want:
1680 // - allow separator-text to be draggable items (would require a stable ID + a noticeable highlight)
1681 // - this high-level entry point to allow formatting? (which in turns may require ID separate from formatted string)
1682 // - because of this we probably can't turn 'const char* label' into 'const char* fmt, ...'
1683 // Otherwise, we can decide that users wanting to drag this would layout a dedicated drag-item,
1684 // and then we can turn this into a format function.
1685 SeparatorTextEx(0, label, FindRenderedTextEnd(label), 0.0f);
1686 }
1687
1688 // Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise.
1689 bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend, float hover_visibility_delay, ImU32 bg_col)
1690 {
1691 ImGuiContext& g = *GImGui;
1692 ImGuiWindow* window = g.CurrentWindow;
1693
1694 if (!ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav))
1695 return false;
1696
1697 // FIXME: AFAIK the only leftover reason for passing ImGuiButtonFlags_AllowOverlap here is
1698 // to allow caller of SplitterBehavior() to call SetItemAllowOverlap() after the item.
1699 // Nowadays we would instead want to use SetNextItemAllowOverlap() before the item.
1700 ImGuiButtonFlags button_flags = ImGuiButtonFlags_FlattenChildren;
1701 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
1702 button_flags |= ImGuiButtonFlags_AllowOverlap;
1703 #endif
1704
1705 bool hovered, held;
1706 ImRect bb_interact = bb;
1707 bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));
1708 ButtonBehavior(bb_interact, id, &hovered, &held, button_flags);
1709 if (hovered)
1710 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect; // for IsItemHovered(), because bb_interact is larger than bb
1711
1712 if (held || (hovered && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay))
1713 SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);
1714
1715 ImRect bb_render = bb;
1716 if (held)
1717 {
1718 float mouse_delta = (g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min)[axis];
1719
1720 // Minimum pane size
1721 float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1);
1722 float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2);
1723 if (mouse_delta < -size_1_maximum_delta)
1724 mouse_delta = -size_1_maximum_delta;
1725 if (mouse_delta > size_2_maximum_delta)
1726 mouse_delta = size_2_maximum_delta;
1727
1728 // Apply resize
1729 if (mouse_delta != 0.0f)
1730 {
1731 *size1 = ImMax(*size1 + mouse_delta, min_size1);
1732 *size2 = ImMax(*size2 - mouse_delta, min_size2);
1733 bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));
1734 MarkItemEdited(id);
1735 }
1736 }
1737
1738 // Render at new position
1739 if (bg_col & IM_COL32_A_MASK)
1740 window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, bg_col, 0.0f);
1741 const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
1742 window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, 0.0f);
1743
1744 return held;
1745 }
1746
1747 static int IMGUI_CDECL ShrinkWidthItemComparer(const void* lhs, const void* rhs)
1748 {
1749 const ImGuiShrinkWidthItem* a = (const ImGuiShrinkWidthItem*)lhs;
1750 const ImGuiShrinkWidthItem* b = (const ImGuiShrinkWidthItem*)rhs;
1751 if (int d = (int)(b->Width - a->Width))
1752 return d;
1753 return (b->Index - a->Index);
1754 }
1755
1756 // Shrink excess width from a set of item, by removing width from the larger items first.
1757 // Set items Width to -1.0f to disable shrinking this item.
1758 void ImGui::ShrinkWidths(ImGuiShrinkWidthItem* items, int count, float width_excess)
1759 {
1760 if (count == 1)
1761 {
1762 if (items[0].Width >= 0.0f)
1763 items[0].Width = ImMax(items[0].Width - width_excess, 1.0f);
1764 return;
1765 }
1766 ImQsort(items, (size_t)count, sizeof(ImGuiShrinkWidthItem), ShrinkWidthItemComparer);
1767 int count_same_width = 1;
1768 while (width_excess > 0.0f && count_same_width < count)
1769 {
1770 while (count_same_width < count && items[0].Width <= items[count_same_width].Width)
1771 count_same_width++;
1772 float max_width_to_remove_per_item = (count_same_width < count && items[count_same_width].Width >= 0.0f) ? (items[0].Width - items[count_same_width].Width) : (items[0].Width - 1.0f);
1773 if (max_width_to_remove_per_item <= 0.0f)
1774 break;
1775 float width_to_remove_per_item = ImMin(width_excess / count_same_width, max_width_to_remove_per_item);
1776 for (int item_n = 0; item_n < count_same_width; item_n++)
1777 items[item_n].Width -= width_to_remove_per_item;
1778 width_excess -= width_to_remove_per_item * count_same_width;
1779 }
1780
1781 // Round width and redistribute remainder
1782 // Ensure that e.g. the right-most tab of a shrunk tab-bar always reaches exactly at the same distance from the right-most edge of the tab bar separator.
1783 width_excess = 0.0f;
1784 for (int n = 0; n < count; n++)
1785 {
1786 float width_rounded = ImTrunc(items[n].Width);
1787 width_excess += items[n].Width - width_rounded;
1788 items[n].Width = width_rounded;
1789 }
1790 while (width_excess > 0.0f)
1791 for (int n = 0; n < count && width_excess > 0.0f; n++)
1792 {
1793 float width_to_add = ImMin(items[n].InitialWidth - items[n].Width, 1.0f);
1794 items[n].Width += width_to_add;
1795 width_excess -= width_to_add;
1796 }
1797 }
1798
1799 //-------------------------------------------------------------------------
1800 // [SECTION] Widgets: ComboBox
1801 //-------------------------------------------------------------------------
1802 // - CalcMaxPopupHeightFromItemCount() [Internal]
1803 // - BeginCombo()
1804 // - BeginComboPopup() [Internal]
1805 // - EndCombo()
1806 // - BeginComboPreview() [Internal]
1807 // - EndComboPreview() [Internal]
1808 // - Combo()
1809 //-------------------------------------------------------------------------
1810
1811 static float CalcMaxPopupHeightFromItemCount(int items_count)
1812 {
1813 ImGuiContext& g = *GImGui;
1814 if (items_count <= 0)
1815 return FLT_MAX;
1816 return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);
1817 }
1818
1819 bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)
1820 {
1821 ImGuiContext& g = *GImGui;
1822 ImGuiWindow* window = GetCurrentWindow();
1823
1824 ImGuiNextWindowDataFlags backup_next_window_data_flags = g.NextWindowData.Flags;
1825 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
1826 if (window->SkipItems)
1827 return false;
1828
1829 const ImGuiStyle& style = g.Style;
1830 const ImGuiID id = window->GetID(label);
1831 IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together
1832 if (flags & ImGuiComboFlags_WidthFitPreview)
1833 IM_ASSERT((flags & (ImGuiComboFlags_NoPreview | (ImGuiComboFlags)ImGuiComboFlags_CustomPreview)) == 0);
1834
1835 const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight();
1836 const ImVec2 label_size = CalcTextSize(label, NULL, true);
1837 const float preview_width = ((flags & ImGuiComboFlags_WidthFitPreview) && (preview_value != NULL)) ? CalcTextSize(preview_value, NULL, true).x : 0.0f;
1838 const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : ((flags & ImGuiComboFlags_WidthFitPreview) ? (arrow_size + preview_width + style.FramePadding.x * 2.0f) : CalcItemWidth());
1839 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));
1840 const ImRect total_bb(bb.Min, bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
1841 ItemSize(total_bb, style.FramePadding.y);
1842 if (!ItemAdd(total_bb, id, &bb))
1843 return false;
1844
1845 // Open on click
1846 bool hovered, held;
1847 bool pressed = ButtonBehavior(bb, id, &hovered, &held);
1848 const ImGuiID popup_id = ImHashStr("##ComboPopup", 0, id);
1849 bool popup_open = IsPopupOpen(popup_id, ImGuiPopupFlags_None);
1850 if (pressed && !popup_open)
1851 {
1852 OpenPopupEx(popup_id, ImGuiPopupFlags_None);
1853 popup_open = true;
1854 }
1855
1856 // Render shape
1857 const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
1858 const float value_x2 = ImMax(bb.Min.x, bb.Max.x - arrow_size);
1859 RenderNavCursor(bb, id);
1860 if (!(flags & ImGuiComboFlags_NoPreview))
1861 window->DrawList->AddRectFilled(bb.Min, ImVec2(value_x2, bb.Max.y), frame_col, style.FrameRounding, (flags & ImGuiComboFlags_NoArrowButton) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersLeft);
1862 if (!(flags & ImGuiComboFlags_NoArrowButton))
1863 {
1864 ImU32 bg_col = GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
1865 ImU32 text_col = GetColorU32(ImGuiCol_Text);
1866 window->DrawList->AddRectFilled(ImVec2(value_x2, bb.Min.y), bb.Max, bg_col, style.FrameRounding, (w <= arrow_size) ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersRight);
1867 if (value_x2 + arrow_size - style.FramePadding.x <= bb.Max.x)
1868 RenderArrow(window->DrawList, ImVec2(value_x2 + style.FramePadding.y, bb.Min.y + style.FramePadding.y), text_col, ImGuiDir_Down, 1.0f);
1869 }
1870 RenderFrameBorder(bb.Min, bb.Max, style.FrameRounding);
1871
1872 // Custom preview
1873 if (flags & ImGuiComboFlags_CustomPreview)
1874 {
1875 g.ComboPreviewData.PreviewRect = ImRect(bb.Min.x, bb.Min.y, value_x2, bb.Max.y);
1876 IM_ASSERT(preview_value == NULL || preview_value[0] == 0);
1877 preview_value = NULL;
1878 }
1879
1880 // Render preview and label
1881 if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))
1882 {
1883 if (g.LogEnabled)
1884 LogSetNextTextDecoration("{", "}");
1885 RenderTextClipped(bb.Min + style.FramePadding, ImVec2(value_x2, bb.Max.y), preview_value, NULL, NULL);
1886 }
1887 if (label_size.x > 0)
1888 RenderText(ImVec2(bb.Max.x + style.ItemInnerSpacing.x, bb.Min.y + style.FramePadding.y), label);
1889
1890 if (!popup_open)
1891 return false;
1892
1893 g.NextWindowData.Flags = backup_next_window_data_flags;
1894 return BeginComboPopup(popup_id, bb, flags);
1895 }
1896
1897 bool ImGui::BeginComboPopup(ImGuiID popup_id, const ImRect& bb, ImGuiComboFlags flags)
1898 {
1899 ImGuiContext& g = *GImGui;
1900 if (!IsPopupOpen(popup_id, ImGuiPopupFlags_None))
1901 {
1902 g.NextWindowData.ClearFlags();
1903 return false;
1904 }
1905
1906 // Set popup size
1907 float w = bb.GetWidth();
1908 if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
1909 {
1910 g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
1911 }
1912 else
1913 {
1914 if ((flags & ImGuiComboFlags_HeightMask_) == 0)
1915 flags |= ImGuiComboFlags_HeightRegular;
1916 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one
1917 int popup_max_height_in_items = -1;
1918 if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8;
1919 else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
1920 else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
1921 ImVec2 constraint_min(0.0f, 0.0f), constraint_max(FLT_MAX, FLT_MAX);
1922 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.x <= 0.0f) // Don't apply constraints if user specified a size
1923 constraint_min.x = w;
1924 if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize) == 0 || g.NextWindowData.SizeVal.y <= 0.0f)
1925 constraint_max.y = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items);
1926 SetNextWindowSizeConstraints(constraint_min, constraint_max);
1927 }
1928
1929 // This is essentially a specialized version of BeginPopupEx()
1930 char name[16];
1931 ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginComboDepth); // Recycle windows based on depth
1932
1933 // Set position given a custom constraint (peak into expected window size so we can position it)
1934 // FIXME: This might be easier to express with an hypothetical SetNextWindowPosConstraints() function?
1935 // FIXME: This might be moved to Begin() or at least around the same spot where Tooltips and other Popups are calling FindBestWindowPosForPopupEx()?
1936 if (ImGuiWindow* popup_window = FindWindowByName(name))
1937 if (popup_window->WasActive)
1938 {
1939 // Always override 'AutoPosLastDirection' to not leave a chance for a past value to affect us.
1940 ImVec2 size_expected = CalcWindowNextAutoFitSize(popup_window);
1941 popup_window->AutoPosLastDirection = (flags & ImGuiComboFlags_PopupAlignLeft) ? ImGuiDir_Left : ImGuiDir_Down; // Left = "Below, Toward Left", Down = "Below, Toward Right (default)"
1942 ImRect r_outer = GetPopupAllowedExtentRect(popup_window);
1943 ImVec2 pos = FindBestWindowPosForPopupEx(bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, bb, ImGuiPopupPositionPolicy_ComboBox);
1944 SetNextWindowPos(pos);
1945 }
1946
1947 // We don't use BeginPopupEx() solely because we have a custom name string, which we could make an argument to BeginPopupEx()
1948 ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoMove;
1949 PushStyleVarX(ImGuiStyleVar_WindowPadding, g.Style.FramePadding.x); // Horizontally align ourselves with the framed text
1950 bool ret = Begin(name, NULL, window_flags);
1951 PopStyleVar();
1952 if (!ret)
1953 {
1954 EndPopup();
1955 IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
1956 return false;
1957 }
1958 g.BeginComboDepth++;
1959 return true;
1960 }
1961
1962 void ImGui::EndCombo()
1963 {
1964 ImGuiContext& g = *GImGui;
1965 EndPopup();
1966 g.BeginComboDepth--;
1967 }
1968
1969 // Call directly after the BeginCombo/EndCombo block. The preview is designed to only host non-interactive elements
1970 // (Experimental, see GitHub issues: #1658, #4168)
1971 bool ImGui::BeginComboPreview()
1972 {
1973 ImGuiContext& g = *GImGui;
1974 ImGuiWindow* window = g.CurrentWindow;
1975 ImGuiComboPreviewData* preview_data = &g.ComboPreviewData;
1976
1977 if (window->SkipItems || !(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible))
1978 return false;
1979 IM_ASSERT(g.LastItemData.Rect.Min.x == preview_data->PreviewRect.Min.x && g.LastItemData.Rect.Min.y == preview_data->PreviewRect.Min.y); // Didn't call after BeginCombo/EndCombo block or forgot to pass ImGuiComboFlags_CustomPreview flag?
1980 if (!window->ClipRect.Overlaps(preview_data->PreviewRect)) // Narrower test (optional)
1981 return false;
1982
1983 // FIXME: This could be contained in a PushWorkRect() api
1984 preview_data->BackupCursorPos = window->DC.CursorPos;
1985 preview_data->BackupCursorMaxPos = window->DC.CursorMaxPos;
1986 preview_data->BackupCursorPosPrevLine = window->DC.CursorPosPrevLine;
1987 preview_data->BackupPrevLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
1988 preview_data->BackupLayout = window->DC.LayoutType;
1989 window->DC.CursorPos = preview_data->PreviewRect.Min + g.Style.FramePadding;
1990 window->DC.CursorMaxPos = window->DC.CursorPos;
1991 window->DC.LayoutType = ImGuiLayoutType_Horizontal;
1992 window->DC.IsSameLine = false;
1993 PushClipRect(preview_data->PreviewRect.Min, preview_data->PreviewRect.Max, true);
1994
1995 return true;
1996 }
1997
1998 void ImGui::EndComboPreview()
1999 {
2000 ImGuiContext& g = *GImGui;
2001 ImGuiWindow* window = g.CurrentWindow;
2002 ImGuiComboPreviewData* preview_data = &g.ComboPreviewData;
2003
2004 // FIXME: Using CursorMaxPos approximation instead of correct AABB which we will store in ImDrawCmd in the future
2005 ImDrawList* draw_list = window->DrawList;
2006 if (window->DC.CursorMaxPos.x < preview_data->PreviewRect.Max.x && window->DC.CursorMaxPos.y < preview_data->PreviewRect.Max.y)
2007 if (draw_list->CmdBuffer.Size > 1) // Unlikely case that the PushClipRect() didn't create a command
2008 {
2009 draw_list->_CmdHeader.ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ClipRect = draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 2].ClipRect;
2010 draw_list->_TryMergeDrawCmds();
2011 }
2012 PopClipRect();
2013 window->DC.CursorPos = preview_data->BackupCursorPos;
2014 window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, preview_data->BackupCursorMaxPos);
2015 window->DC.CursorPosPrevLine = preview_data->BackupCursorPosPrevLine;
2016 window->DC.PrevLineTextBaseOffset = preview_data->BackupPrevLineTextBaseOffset;
2017 window->DC.LayoutType = preview_data->BackupLayout;
2018 window->DC.IsSameLine = false;
2019 preview_data->PreviewRect = ImRect();
2020 }
2021
2022 // Getter for the old Combo() API: const char*[]
2023 static const char* Items_ArrayGetter(void* data, int idx)
2024 {
2025 const char* const* items = (const char* const*)data;
2026 return items[idx];
2027 }
2028
2029 // Getter for the old Combo() API: "item1\0item2\0item3\0"
2030 static const char* Items_SingleStringGetter(void* data, int idx)
2031 {
2032 const char* items_separated_by_zeros = (const char*)data;
2033 int items_count = 0;
2034 const char* p = items_separated_by_zeros;
2035 while (*p)
2036 {
2037 if (idx == items_count)
2038 break;
2039 p += strlen(p) + 1;
2040 items_count++;
2041 }
2042 return *p ? p : NULL;
2043 }
2044
2045 // Old API, prefer using BeginCombo() nowadays if you can.
2046 bool ImGui::Combo(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int popup_max_height_in_items)
2047 {
2048 ImGuiContext& g = *GImGui;
2049
2050 // Call the getter to obtain the preview string which is a parameter to BeginCombo()
2051 const char* preview_value = NULL;
2052 if (*current_item >= 0 && *current_item < items_count)
2053 preview_value = getter(user_data, *current_item);
2054
2055 // The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here.
2056 if (popup_max_height_in_items != -1 && !(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint))
2057 SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
2058
2059 if (!BeginCombo(label, preview_value, ImGuiComboFlags_None))
2060 return false;
2061
2062 // Display items
2063 bool value_changed = false;
2064 ImGuiListClipper clipper;
2065 clipper.Begin(items_count);
2066 clipper.IncludeItemByIndex(*current_item);
2067 while (clipper.Step())
2068 for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
2069 {
2070 const char* item_text = getter(user_data, i);
2071 if (item_text == NULL)
2072 item_text = "*Unknown item*";
2073
2074 PushID(i);
2075 const bool item_selected = (i == *current_item);
2076 if (Selectable(item_text, item_selected) && *current_item != i)
2077 {
2078 value_changed = true;
2079 *current_item = i;
2080 }
2081 if (item_selected)
2082 SetItemDefaultFocus();
2083 PopID();
2084 }
2085
2086 EndCombo();
2087 if (value_changed)
2088 MarkItemEdited(g.LastItemData.ID);
2089
2090 return value_changed;
2091 }
2092
2093 // Combo box helper allowing to pass an array of strings.
2094 bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)
2095 {
2096 const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
2097 return value_changed;
2098 }
2099
2100 // Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0"
2101 bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
2102 {
2103 int items_count = 0;
2104 const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
2105 while (*p)
2106 {
2107 p += strlen(p) + 1;
2108 items_count++;
2109 }
2110 bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
2111 return value_changed;
2112 }
2113
2114 #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2115
2116 struct ImGuiGetNameFromIndexOldToNewCallbackData { void* UserData; bool (*OldCallback)(void*, int, const char**); };
2117 static const char* ImGuiGetNameFromIndexOldToNewCallback(void* user_data, int idx)
2118 {
2119 ImGuiGetNameFromIndexOldToNewCallbackData* data = (ImGuiGetNameFromIndexOldToNewCallbackData*)user_data;
2120 const char* s = NULL;
2121 data->OldCallback(data->UserData, idx, &s);
2122 return s;
2123 }
2124
2125 bool ImGui::ListBox(const char* label, int* current_item, bool (*old_getter)(void*, int, const char**), void* user_data, int items_count, int height_in_items)
2126 {
2127 ImGuiGetNameFromIndexOldToNewCallbackData old_to_new_data = { user_data, old_getter };
2128 return ListBox(label, current_item, ImGuiGetNameFromIndexOldToNewCallback, &old_to_new_data, items_count, height_in_items);
2129 }
2130 bool ImGui::Combo(const char* label, int* current_item, bool (*old_getter)(void*, int, const char**), void* user_data, int items_count, int popup_max_height_in_items)
2131 {
2132 ImGuiGetNameFromIndexOldToNewCallbackData old_to_new_data = { user_data, old_getter };
2133 return Combo(label, current_item, ImGuiGetNameFromIndexOldToNewCallback, &old_to_new_data, items_count, popup_max_height_in_items);
2134 }
2135
2136 #endif
2137
2138 //-------------------------------------------------------------------------
2139 // [SECTION] Data Type and Data Formatting Helpers [Internal]
2140 //-------------------------------------------------------------------------
2141 // - DataTypeGetInfo()
2142 // - DataTypeFormatString()
2143 // - DataTypeApplyOp()
2144 // - DataTypeApplyFromText()
2145 // - DataTypeCompare()
2146 // - DataTypeClamp()
2147 // - GetMinimumStepAtDecimalPrecision
2148 // - RoundScalarWithFormat<>()
2149 //-------------------------------------------------------------------------
2150
2151 static const ImGuiDataTypeInfo GDataTypeInfo[] =
2152 {
2153 { sizeof(char), "S8", "%d", "%d" }, // ImGuiDataType_S8
2154 { sizeof(unsigned char), "U8", "%u", "%u" },
2155 { sizeof(short), "S16", "%d", "%d" }, // ImGuiDataType_S16
2156 { sizeof(unsigned short), "U16", "%u", "%u" },
2157 { sizeof(int), "S32", "%d", "%d" }, // ImGuiDataType_S32
2158 { sizeof(unsigned int), "U32", "%u", "%u" },
2159 #ifdef _MSC_VER
2160 { sizeof(ImS64), "S64", "%I64d","%I64d" }, // ImGuiDataType_S64
2161 { sizeof(ImU64), "U64", "%I64u","%I64u" },
2162 #else
2163 { sizeof(ImS64), "S64", "%lld", "%lld" }, // ImGuiDataType_S64
2164 { sizeof(ImU64), "U64", "%llu", "%llu" },
2165 #endif
2166 { sizeof(float), "float", "%.3f","%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg)
2167 { sizeof(double), "double","%f", "%lf" }, // ImGuiDataType_Double
2168 { sizeof(bool), "bool", "%d", "%d" }, // ImGuiDataType_Bool
2169 };
2170 IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT);
2171
2172 const ImGuiDataTypeInfo* ImGui::DataTypeGetInfo(ImGuiDataType data_type)
2173 {
2174 IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT);
2175 return &GDataTypeInfo[data_type];
2176 }
2177
2178 int ImGui::DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* p_data, const char* format)
2179 {
2180 // Signedness doesn't matter when pushing integer arguments
2181 if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32)
2182 return ImFormatString(buf, buf_size, format, *(const ImU32*)p_data);
2183 if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64)
2184 return ImFormatString(buf, buf_size, format, *(const ImU64*)p_data);
2185 if (data_type == ImGuiDataType_Float)
2186 return ImFormatString(buf, buf_size, format, *(const float*)p_data);
2187 if (data_type == ImGuiDataType_Double)
2188 return ImFormatString(buf, buf_size, format, *(const double*)p_data);
2189 if (data_type == ImGuiDataType_S8)
2190 return ImFormatString(buf, buf_size, format, *(const ImS8*)p_data);
2191 if (data_type == ImGuiDataType_U8)
2192 return ImFormatString(buf, buf_size, format, *(const ImU8*)p_data);
2193 if (data_type == ImGuiDataType_S16)
2194 return ImFormatString(buf, buf_size, format, *(const ImS16*)p_data);
2195 if (data_type == ImGuiDataType_U16)
2196 return ImFormatString(buf, buf_size, format, *(const ImU16*)p_data);
2197 IM_ASSERT(0);
2198 return 0;
2199 }
2200
2201 void ImGui::DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, const void* arg1, const void* arg2)
2202 {
2203 IM_ASSERT(op == '+' || op == '-');
2204 switch (data_type)
2205 {
2206 case ImGuiDataType_S8:
2207 if (op == '+') { *(ImS8*)output = ImAddClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
2208 if (op == '-') { *(ImS8*)output = ImSubClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); }
2209 return;
2210 case ImGuiDataType_U8:
2211 if (op == '+') { *(ImU8*)output = ImAddClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
2212 if (op == '-') { *(ImU8*)output = ImSubClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); }
2213 return;
2214 case ImGuiDataType_S16:
2215 if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
2216 if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); }
2217 return;
2218 case ImGuiDataType_U16:
2219 if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
2220 if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); }
2221 return;
2222 case ImGuiDataType_S32:
2223 if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
2224 if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); }
2225 return;
2226 case ImGuiDataType_U32:
2227 if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
2228 if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); }
2229 return;
2230 case ImGuiDataType_S64:
2231 if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
2232 if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); }
2233 return;
2234 case ImGuiDataType_U64:
2235 if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
2236 if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); }
2237 return;
2238 case ImGuiDataType_Float:
2239 if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; }
2240 if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; }
2241 return;
2242 case ImGuiDataType_Double:
2243 if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; }
2244 if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; }
2245 return;
2246 case ImGuiDataType_COUNT: break;
2247 }
2248 IM_ASSERT(0);
2249 }
2250
2251 // User can input math operators (e.g. +100) to edit a numerical values.
2252 // NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess..
2253 bool ImGui::DataTypeApplyFromText(const char* buf, ImGuiDataType data_type, void* p_data, const char* format, void* p_data_when_empty)
2254 {
2255 // Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all.
2256 const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type);
2257 ImGuiDataTypeStorage data_backup;
2258 memcpy(&data_backup, p_data, type_info->Size);
2259
2260 while (ImCharIsBlankA(*buf))
2261 buf++;
2262 if (!buf[0])
2263 {
2264 if (p_data_when_empty != NULL)
2265 {
2266 memcpy(p_data, p_data_when_empty, type_info->Size);
2267 return memcmp(&data_backup, p_data, type_info->Size) != 0;
2268 }
2269 return false;
2270 }
2271
2272 // Sanitize format
2273 // - For float/double we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in, so force them into %f and %lf
2274 // - In theory could treat empty format as using default, but this would only cover rare/bizarre case of using InputScalar() + integer + format string without %.
2275 char format_sanitized[32];
2276 if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double)
2277 format = type_info->ScanFmt;
2278 else
2279 format = ImParseFormatSanitizeForScanning(format, format_sanitized, IM_ARRAYSIZE(format_sanitized));
2280
2281 // Small types need a 32-bit buffer to receive the result from scanf()
2282 int v32 = 0;
2283 if (sscanf(buf, format, type_info->Size >= 4 ? p_data : &v32) < 1)
2284 return false;
2285 if (type_info->Size < 4)
2286 {
2287 if (data_type == ImGuiDataType_S8)
2288 *(ImS8*)p_data = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX);
2289 else if (data_type == ImGuiDataType_U8)
2290 *(ImU8*)p_data = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX);
2291 else if (data_type == ImGuiDataType_S16)
2292 *(ImS16*)p_data = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX);
2293 else if (data_type == ImGuiDataType_U16)
2294 *(ImU16*)p_data = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX);
2295 else
2296 IM_ASSERT(0);
2297 }
2298
2299 return memcmp(&data_backup, p_data, type_info->Size) != 0;
2300 }
2301
2302 template<typename T>
2303 static int DataTypeCompareT(const T* lhs, const T* rhs)
2304 {
2305 if (*lhs < *rhs) return -1;
2306 if (*lhs > *rhs) return +1;
2307 return 0;
2308 }
2309
2310 int ImGui::DataTypeCompare(ImGuiDataType data_type, const void* arg_1, const void* arg_2)
2311 {
2312 switch (data_type)
2313 {
2314 case ImGuiDataType_S8: return DataTypeCompareT<ImS8 >((const ImS8* )arg_1, (const ImS8* )arg_2);
2315 case ImGuiDataType_U8: return DataTypeCompareT<ImU8 >((const ImU8* )arg_1, (const ImU8* )arg_2);
2316 case ImGuiDataType_S16: return DataTypeCompareT<ImS16 >((const ImS16* )arg_1, (const ImS16* )arg_2);
2317 case ImGuiDataType_U16: return DataTypeCompareT<ImU16 >((const ImU16* )arg_1, (const ImU16* )arg_2);
2318 case ImGuiDataType_S32: return DataTypeCompareT<ImS32 >((const ImS32* )arg_1, (const ImS32* )arg_2);
2319 case ImGuiDataType_U32: return DataTypeCompareT<ImU32 >((const ImU32* )arg_1, (const ImU32* )arg_2);
2320 case ImGuiDataType_S64: return DataTypeCompareT<ImS64 >((const ImS64* )arg_1, (const ImS64* )arg_2);
2321 case ImGuiDataType_U64: return DataTypeCompareT<ImU64 >((const ImU64* )arg_1, (const ImU64* )arg_2);
2322 case ImGuiDataType_Float: return DataTypeCompareT<float >((const float* )arg_1, (const float* )arg_2);
2323 case ImGuiDataType_Double: return DataTypeCompareT<double>((const double*)arg_1, (const double*)arg_2);
2324 case ImGuiDataType_COUNT: break;
2325 }
2326 IM_ASSERT(0);
2327 return 0;
2328 }
2329
2330 template<typename T>
2331 static bool DataTypeClampT(T* v, const T* v_min, const T* v_max)
2332 {
2333 // Clamp, both sides are optional, return true if modified
2334 if (v_min && *v < *v_min) { *v = *v_min; return true; }
2335 if (v_max && *v > *v_max) { *v = *v_max; return true; }
2336 return false;
2337 }
2338
2339 bool ImGui::DataTypeClamp(ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max)
2340 {
2341 switch (data_type)
2342 {
2343 case ImGuiDataType_S8: return DataTypeClampT<ImS8 >((ImS8* )p_data, (const ImS8* )p_min, (const ImS8* )p_max);
2344 case ImGuiDataType_U8: return DataTypeClampT<ImU8 >((ImU8* )p_data, (const ImU8* )p_min, (const ImU8* )p_max);
2345 case ImGuiDataType_S16: return DataTypeClampT<ImS16 >((ImS16* )p_data, (const ImS16* )p_min, (const ImS16* )p_max);
2346 case ImGuiDataType_U16: return DataTypeClampT<ImU16 >((ImU16* )p_data, (const ImU16* )p_min, (const ImU16* )p_max);
2347 case ImGuiDataType_S32: return DataTypeClampT<ImS32 >((ImS32* )p_data, (const ImS32* )p_min, (const ImS32* )p_max);
2348 case ImGuiDataType_U32: return DataTypeClampT<ImU32 >((ImU32* )p_data, (const ImU32* )p_min, (const ImU32* )p_max);
2349 case ImGuiDataType_S64: return DataTypeClampT<ImS64 >((ImS64* )p_data, (const ImS64* )p_min, (const ImS64* )p_max);
2350 case ImGuiDataType_U64: return DataTypeClampT<ImU64 >((ImU64* )p_data, (const ImU64* )p_min, (const ImU64* )p_max);
2351 case ImGuiDataType_Float: return DataTypeClampT<float >((float* )p_data, (const float* )p_min, (const float* )p_max);
2352 case ImGuiDataType_Double: return DataTypeClampT<double>((double*)p_data, (const double*)p_min, (const double*)p_max);
2353 case ImGuiDataType_COUNT: break;
2354 }
2355 IM_ASSERT(0);
2356 return false;
2357 }
2358
2359 bool ImGui::DataTypeIsZero(ImGuiDataType data_type, const void* p_data)
2360 {
2361 ImGuiContext& g = *GImGui;
2362 return DataTypeCompare(data_type, p_data, &g.DataTypeZeroValue) == 0;
2363 }
2364
2365 static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
2366 {
2367 static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
2368 if (decimal_precision < 0)
2369 return FLT_MIN;
2370 return (decimal_precision < IM_ARRAYSIZE(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision);
2371 }
2372
2373 template<typename TYPE>
2374 TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v)
2375 {
2376 IM_UNUSED(data_type);
2377 IM_ASSERT(data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double);
2378 const char* fmt_start = ImParseFormatFindStart(format);
2379 if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string
2380 return v;
2381
2382 // Sanitize format
2383 char fmt_sanitized[32];
2384 ImParseFormatSanitizeForPrinting(fmt_start, fmt_sanitized, IM_ARRAYSIZE(fmt_sanitized));
2385 fmt_start = fmt_sanitized;
2386
2387 // Format value with our rounding, and read back
2388 char v_str[64];
2389 ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v);
2390 const char* p = v_str;
2391 while (*p == ' ')
2392 p++;
2393 v = (TYPE)ImAtof(p);
2394
2395 return v;
2396 }
2397
2398 //-------------------------------------------------------------------------
2399 // [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc.
2400 //-------------------------------------------------------------------------
2401 // - DragBehaviorT<>() [Internal]
2402 // - DragBehavior() [Internal]
2403 // - DragScalar()
2404 // - DragScalarN()
2405 // - DragFloat()
2406 // - DragFloat2()
2407 // - DragFloat3()
2408 // - DragFloat4()
2409 // - DragFloatRange2()
2410 // - DragInt()
2411 // - DragInt2()
2412 // - DragInt3()
2413 // - DragInt4()
2414 // - DragIntRange2()
2415 //-------------------------------------------------------------------------
2416
2417 // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls)
2418 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
2419 bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags)
2420 {
2421 ImGuiContext& g = *GImGui;
2422 const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
2423 const bool is_bounded = (v_min < v_max) || ((v_min == v_max) && (v_min != 0.0f || (flags & ImGuiSliderFlags_ClampZeroRange)));
2424 const bool is_wrapped = is_bounded && (flags & ImGuiSliderFlags_WrapAround);
2425 const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0;
2426 const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
2427
2428 // Default tweak speed
2429 if (v_speed == 0.0f && is_bounded && (v_max - v_min < FLT_MAX))
2430 v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio);
2431
2432 // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings
2433 float adjust_delta = 0.0f;
2434 if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR))
2435 {
2436 adjust_delta = g.IO.MouseDelta[axis];
2437 if (g.IO.KeyAlt)
2438 adjust_delta *= 1.0f / 100.0f;
2439 if (g.IO.KeyShift)
2440 adjust_delta *= 10.0f;
2441 }
2442 else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
2443 {
2444 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;
2445 const bool tweak_slow = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakSlow : ImGuiKey_NavKeyboardTweakSlow);
2446 const bool tweak_fast = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakFast : ImGuiKey_NavKeyboardTweakFast);
2447 const float tweak_factor = tweak_slow ? 1.0f / 10.0f : tweak_fast ? 10.0f : 1.0f;
2448 adjust_delta = GetNavTweakPressedAmount(axis) * tweak_factor;
2449 v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
2450 }
2451 adjust_delta *= v_speed;
2452
2453 // For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter.
2454 if (axis == ImGuiAxis_Y)
2455 adjust_delta = -adjust_delta;
2456
2457 // For logarithmic use our range is effectively 0..1 so scale the delta into that range
2458 if (is_logarithmic && (v_max - v_min < FLT_MAX) && ((v_max - v_min) > 0.000001f)) // Epsilon to avoid /0
2459 adjust_delta /= (float)(v_max - v_min);
2460
2461 // Clear current value on activation
2462 // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300.
2463 const bool is_just_activated = g.ActiveIdIsJustActivated;
2464 const bool is_already_past_limits_and_pushing_outward = is_bounded && !is_wrapped && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f));
2465 if (is_just_activated || is_already_past_limits_and_pushing_outward)
2466 {
2467 g.DragCurrentAccum = 0.0f;
2468 g.DragCurrentAccumDirty = false;
2469 }
2470 else if (adjust_delta != 0.0f)
2471 {
2472 g.DragCurrentAccum += adjust_delta;
2473 g.DragCurrentAccumDirty = true;
2474 }
2475
2476 if (!g.DragCurrentAccumDirty)
2477 return false;
2478
2479 TYPE v_cur = *v;
2480 FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f;
2481
2482 float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true
2483 const float zero_deadzone_halfsize = 0.0f; // Drag widgets have no deadzone (as it doesn't make sense)
2484 if (is_logarithmic)
2485 {
2486 // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound.
2487 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1;
2488 logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision);
2489
2490 // Convert to parametric space, apply delta, convert back
2491 float v_old_parametric = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
2492 float v_new_parametric = v_old_parametric + g.DragCurrentAccum;
2493 v_cur = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_new_parametric, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
2494 v_old_ref_for_accum_remainder = v_old_parametric;
2495 }
2496 else
2497 {
2498 v_cur += (SIGNEDTYPE)g.DragCurrentAccum;
2499 }
2500
2501 // Round to user desired precision based on format string
2502 if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat))
2503 v_cur = RoundScalarWithFormatT<TYPE>(format, data_type, v_cur);
2504
2505 // Preserve remainder after rounding has been applied. This also allow slow tweaking of values.
2506 g.DragCurrentAccumDirty = false;
2507 if (is_logarithmic)
2508 {
2509 // Convert to parametric space, apply delta, convert back
2510 float v_new_parametric = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_cur, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
2511 g.DragCurrentAccum -= (float)(v_new_parametric - v_old_ref_for_accum_remainder);
2512 }
2513 else
2514 {
2515 g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v);
2516 }
2517
2518 // Lose zero sign for float/double
2519 if (v_cur == (TYPE)-0)
2520 v_cur = (TYPE)0;
2521
2522 if (*v != v_cur && is_bounded)
2523 {
2524 if (is_wrapped)
2525 {
2526 // Wrap values
2527 if (v_cur < v_min)
2528 v_cur += v_max - v_min + (is_floating_point ? 0 : 1);
2529 if (v_cur > v_max)
2530 v_cur -= v_max - v_min + (is_floating_point ? 0 : 1);
2531 }
2532 else
2533 {
2534 // Clamp values + handle overflow/wrap-around for integer types.
2535 if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_floating_point))
2536 v_cur = v_min;
2537 if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_floating_point))
2538 v_cur = v_max;
2539 }
2540 }
2541
2542 // Apply result
2543 if (*v == v_cur)
2544 return false;
2545 *v = v_cur;
2546 return true;
2547 }
2548
2549 bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* p_v, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)
2550 {
2551 // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert.
2552 IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.");
2553
2554 ImGuiContext& g = *GImGui;
2555 if (g.ActiveId == id)
2556 {
2557 // Those are the things we can do easily outside the DragBehaviorT<> template, saves code generation.
2558 if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0])
2559 ClearActiveID();
2560 else if ((g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad) && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
2561 ClearActiveID();
2562 }
2563 if (g.ActiveId != id)
2564 return false;
2565 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
2566 return false;
2567
2568 switch (data_type)
2569 {
2570 case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = DragBehaviorT<ImS32, ImS32, float>(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS8*) p_min : IM_S8_MIN, p_max ? *(const ImS8*)p_max : IM_S8_MAX, format, flags); if (r) *(ImS8*)p_v = (ImS8)v32; return r; }
2571 case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = DragBehaviorT<ImU32, ImS32, float>(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU8*) p_min : IM_U8_MIN, p_max ? *(const ImU8*)p_max : IM_U8_MAX, format, flags); if (r) *(ImU8*)p_v = (ImU8)v32; return r; }
2572 case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = DragBehaviorT<ImS32, ImS32, float>(ImGuiDataType_S32, &v32, v_speed, p_min ? *(const ImS16*)p_min : IM_S16_MIN, p_max ? *(const ImS16*)p_max : IM_S16_MAX, format, flags); if (r) *(ImS16*)p_v = (ImS16)v32; return r; }
2573 case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = DragBehaviorT<ImU32, ImS32, float>(ImGuiDataType_U32, &v32, v_speed, p_min ? *(const ImU16*)p_min : IM_U16_MIN, p_max ? *(const ImU16*)p_max : IM_U16_MAX, format, flags); if (r) *(ImU16*)p_v = (ImU16)v32; return r; }
2574 case ImGuiDataType_S32: return DragBehaviorT<ImS32, ImS32, float >(data_type, (ImS32*)p_v, v_speed, p_min ? *(const ImS32* )p_min : IM_S32_MIN, p_max ? *(const ImS32* )p_max : IM_S32_MAX, format, flags);
2575 case ImGuiDataType_U32: return DragBehaviorT<ImU32, ImS32, float >(data_type, (ImU32*)p_v, v_speed, p_min ? *(const ImU32* )p_min : IM_U32_MIN, p_max ? *(const ImU32* )p_max : IM_U32_MAX, format, flags);
2576 case ImGuiDataType_S64: return DragBehaviorT<ImS64, ImS64, double>(data_type, (ImS64*)p_v, v_speed, p_min ? *(const ImS64* )p_min : IM_S64_MIN, p_max ? *(const ImS64* )p_max : IM_S64_MAX, format, flags);
2577 case ImGuiDataType_U64: return DragBehaviorT<ImU64, ImS64, double>(data_type, (ImU64*)p_v, v_speed, p_min ? *(const ImU64* )p_min : IM_U64_MIN, p_max ? *(const ImU64* )p_max : IM_U64_MAX, format, flags);
2578 case ImGuiDataType_Float: return DragBehaviorT<float, float, float >(data_type, (float*)p_v, v_speed, p_min ? *(const float* )p_min : -FLT_MAX, p_max ? *(const float* )p_max : FLT_MAX, format, flags);
2579 case ImGuiDataType_Double: return DragBehaviorT<double,double,double>(data_type, (double*)p_v, v_speed, p_min ? *(const double*)p_min : -DBL_MAX, p_max ? *(const double*)p_max : DBL_MAX, format, flags);
2580 case ImGuiDataType_COUNT: break;
2581 }
2582 IM_ASSERT(0);
2583 return false;
2584 }
2585
2586 // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a Drag widget, p_min and p_max are optional.
2587 // Read code of e.g. DragFloat(), DragInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
2588 bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)
2589 {
2590 ImGuiWindow* window = GetCurrentWindow();
2591 if (window->SkipItems)
2592 return false;
2593
2594 ImGuiContext& g = *GImGui;
2595 const ImGuiStyle& style = g.Style;
2596 const ImGuiID id = window->GetID(label);
2597 const float w = CalcItemWidth();
2598
2599 const ImVec2 label_size = CalcTextSize(label, NULL, true);
2600 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));
2601 const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
2602
2603 const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0;
2604 ItemSize(total_bb, style.FramePadding.y);
2605 if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0))
2606 return false;
2607
2608 // Default format string when passing NULL
2609 if (format == NULL)
2610 format = DataTypeGetInfo(data_type)->PrintFmt;
2611
2612 const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
2613 bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
2614 if (!temp_input_is_active)
2615 {
2616 // Tabbing or CTRL-clicking on Drag turns it into an InputText
2617 const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
2618 const bool double_clicked = (hovered && g.IO.MouseClickedCount[0] == 2 && TestKeyOwner(ImGuiKey_MouseLeft, id));
2619 const bool make_active = (clicked || double_clicked || g.NavActivateId == id);
2620 if (make_active && (clicked || double_clicked))
2621 SetKeyOwner(ImGuiKey_MouseLeft, id);
2622 if (make_active && temp_input_allowed)
2623 if ((clicked && g.IO.KeyCtrl) || double_clicked || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput)))
2624 temp_input_is_active = true;
2625
2626 // (Optional) simple click (without moving) turns Drag into an InputText
2627 if (g.IO.ConfigDragClickToInputText && temp_input_allowed && !temp_input_is_active)
2628 if (g.ActiveId == id && hovered && g.IO.MouseReleased[0] && !IsMouseDragPastThreshold(0, g.IO.MouseDragThreshold * DRAG_MOUSE_THRESHOLD_FACTOR))
2629 {
2630 g.NavActivateId = id;
2631 g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
2632 temp_input_is_active = true;
2633 }
2634
2635 if (make_active && !temp_input_is_active)
2636 {
2637 SetActiveID(id, window);
2638 SetFocusID(id, window);
2639 FocusWindow(window);
2640 g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
2641 }
2642 }
2643
2644 if (temp_input_is_active)
2645 {
2646 // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp)
2647 bool clamp_enabled = false;
2648 if ((flags & ImGuiSliderFlags_ClampOnInput) && (p_min != NULL || p_max != NULL))
2649 {
2650 const int clamp_range_dir = (p_min != NULL && p_max != NULL) ? DataTypeCompare(data_type, p_min, p_max) : 0; // -1 when *p_min < *p_max, == 0 when *p_min == *p_max
2651 if (p_min == NULL || p_max == NULL || clamp_range_dir < 0)
2652 clamp_enabled = true;
2653 else if (clamp_range_dir == 0)
2654 clamp_enabled = DataTypeIsZero(data_type, p_min) ? ((flags & ImGuiSliderFlags_ClampZeroRange) != 0) : true;
2655 }
2656 return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL);
2657 }
2658
2659 // Draw frame
2660 const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
2661 RenderNavCursor(frame_bb, id);
2662 RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
2663
2664 // Drag behavior
2665 const bool value_changed = DragBehavior(id, data_type, p_data, v_speed, p_min, p_max, format, flags);
2666 if (value_changed)
2667 MarkItemEdited(id);
2668
2669 // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
2670 char value_buf[64];
2671 const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
2672 if (g.LogEnabled)
2673 LogSetNextTextDecoration("{", "}");
2674 RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
2675
2676 if (label_size.x > 0.0f)
2677 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
2678
2679 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
2680 return value_changed;
2681 }
2682
2683 bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)
2684 {
2685 ImGuiWindow* window = GetCurrentWindow();
2686 if (window->SkipItems)
2687 return false;
2688
2689 ImGuiContext& g = *GImGui;
2690 bool value_changed = false;
2691 BeginGroup();
2692 PushID(label);
2693 PushMultiItemsWidths(components, CalcItemWidth());
2694 size_t type_size = GDataTypeInfo[data_type].Size;
2695 for (int i = 0; i < components; i++)
2696 {
2697 PushID(i);
2698 if (i > 0)
2699 SameLine(0, g.Style.ItemInnerSpacing.x);
2700 value_changed |= DragScalar("", data_type, p_data, v_speed, p_min, p_max, format, flags);
2701 PopID();
2702 PopItemWidth();
2703 p_data = (void*)((char*)p_data + type_size);
2704 }
2705 PopID();
2706
2707 const char* label_end = FindRenderedTextEnd(label);
2708 if (label != label_end)
2709 {
2710 SameLine(0, g.Style.ItemInnerSpacing.x);
2711 TextEx(label, label_end);
2712 }
2713
2714 EndGroup();
2715 return value_changed;
2716 }
2717
2718 bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
2719 {
2720 return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, flags);
2721 }
2722
2723 bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
2724 {
2725 return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, flags);
2726 }
2727
2728 bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
2729 {
2730 return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, flags);
2731 }
2732
2733 bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
2734 {
2735 return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, flags);
2736 }
2737
2738 // NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this.
2739 bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, ImGuiSliderFlags flags)
2740 {
2741 ImGuiWindow* window = GetCurrentWindow();
2742 if (window->SkipItems)
2743 return false;
2744
2745 ImGuiContext& g = *GImGui;
2746 PushID(label);
2747 BeginGroup();
2748 PushMultiItemsWidths(2, CalcItemWidth());
2749
2750 float min_min = (v_min >= v_max) ? -FLT_MAX : v_min;
2751 float min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max);
2752 ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0);
2753 bool value_changed = DragScalar("##min", ImGuiDataType_Float, v_current_min, v_speed, &min_min, &min_max, format, min_flags);
2754 PopItemWidth();
2755 SameLine(0, g.Style.ItemInnerSpacing.x);
2756
2757 float max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min);
2758 float max_max = (v_min >= v_max) ? FLT_MAX : v_max;
2759 ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0);
2760 value_changed |= DragScalar("##max", ImGuiDataType_Float, v_current_max, v_speed, &max_min, &max_max, format_max ? format_max : format, max_flags);
2761 PopItemWidth();
2762 SameLine(0, g.Style.ItemInnerSpacing.x);
2763
2764 TextEx(label, FindRenderedTextEnd(label));
2765 EndGroup();
2766 PopID();
2767
2768 return value_changed;
2769 }
2770
2771 // NB: v_speed is float to allow adjusting the drag speed with more precision
2772 bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
2773 {
2774 return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format, flags);
2775 }
2776
2777 bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
2778 {
2779 return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format, flags);
2780 }
2781
2782 bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
2783 {
2784 return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format, flags);
2785 }
2786
2787 bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
2788 {
2789 return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format, flags);
2790 }
2791
2792 // NB: You likely want to specify the ImGuiSliderFlags_AlwaysClamp when using this.
2793 bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max, ImGuiSliderFlags flags)
2794 {
2795 ImGuiWindow* window = GetCurrentWindow();
2796 if (window->SkipItems)
2797 return false;
2798
2799 ImGuiContext& g = *GImGui;
2800 PushID(label);
2801 BeginGroup();
2802 PushMultiItemsWidths(2, CalcItemWidth());
2803
2804 int min_min = (v_min >= v_max) ? INT_MIN : v_min;
2805 int min_max = (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max);
2806 ImGuiSliderFlags min_flags = flags | ((min_min == min_max) ? ImGuiSliderFlags_ReadOnly : 0);
2807 bool value_changed = DragInt("##min", v_current_min, v_speed, min_min, min_max, format, min_flags);
2808 PopItemWidth();
2809 SameLine(0, g.Style.ItemInnerSpacing.x);
2810
2811 int max_min = (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min);
2812 int max_max = (v_min >= v_max) ? INT_MAX : v_max;
2813 ImGuiSliderFlags max_flags = flags | ((max_min == max_max) ? ImGuiSliderFlags_ReadOnly : 0);
2814 value_changed |= DragInt("##max", v_current_max, v_speed, max_min, max_max, format_max ? format_max : format, max_flags);
2815 PopItemWidth();
2816 SameLine(0, g.Style.ItemInnerSpacing.x);
2817
2818 TextEx(label, FindRenderedTextEnd(label));
2819 EndGroup();
2820 PopID();
2821
2822 return value_changed;
2823 }
2824
2825 //-------------------------------------------------------------------------
2826 // [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc.
2827 //-------------------------------------------------------------------------
2828 // - ScaleRatioFromValueT<> [Internal]
2829 // - ScaleValueFromRatioT<> [Internal]
2830 // - SliderBehaviorT<>() [Internal]
2831 // - SliderBehavior() [Internal]
2832 // - SliderScalar()
2833 // - SliderScalarN()
2834 // - SliderFloat()
2835 // - SliderFloat2()
2836 // - SliderFloat3()
2837 // - SliderFloat4()
2838 // - SliderAngle()
2839 // - SliderInt()
2840 // - SliderInt2()
2841 // - SliderInt3()
2842 // - SliderInt4()
2843 // - VSliderScalar()
2844 // - VSliderFloat()
2845 // - VSliderInt()
2846 //-------------------------------------------------------------------------
2847
2848 // Convert a value v in the output space of a slider into a parametric position on the slider itself (the logical opposite of ScaleValueFromRatioT)
2849 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
2850 float ImGui::ScaleRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize)
2851 {
2852 if (v_min == v_max)
2853 return 0.0f;
2854 IM_UNUSED(data_type);
2855
2856 const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
2857 if (is_logarithmic)
2858 {
2859 bool flipped = v_max < v_min;
2860
2861 if (flipped) // Handle the case where the range is backwards
2862 ImSwap(v_min, v_max);
2863
2864 // Fudge min/max to avoid getting close to log(0)
2865 FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min;
2866 FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max;
2867
2868 // Awkward special cases - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon)
2869 if ((v_min == 0.0f) && (v_max < 0.0f))
2870 v_min_fudged = -logarithmic_zero_epsilon;
2871 else if ((v_max == 0.0f) && (v_min < 0.0f))
2872 v_max_fudged = -logarithmic_zero_epsilon;
2873
2874 float result;
2875 if (v_clamped <= v_min_fudged)
2876 result = 0.0f; // Workaround for values that are in-range but below our fudge
2877 else if (v_clamped >= v_max_fudged)
2878 result = 1.0f; // Workaround for values that are in-range but above our fudge
2879 else if ((v_min * v_max) < 0.0f) // Range crosses zero, so split into two portions
2880 {
2881 float zero_point_center = (-(float)v_min) / ((float)v_max - (float)v_min); // The zero point in parametric space. There's an argument we should take the logarithmic nature into account when calculating this, but for now this should do (and the most common case of a symmetrical range works fine)
2882 float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize;
2883 float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize;
2884 if (v == 0.0f)
2885 result = zero_point_center; // Special case for exactly zero
2886 else if (v < 0.0f)
2887 result = (1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(-v_min_fudged / logarithmic_zero_epsilon))) * zero_point_snap_L;
2888 else
2889 result = zero_point_snap_R + ((float)(ImLog((FLOATTYPE)v_clamped / logarithmic_zero_epsilon) / ImLog(v_max_fudged / logarithmic_zero_epsilon)) * (1.0f - zero_point_snap_R));
2890 }
2891 else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider
2892 result = 1.0f - (float)(ImLog(-(FLOATTYPE)v_clamped / -v_max_fudged) / ImLog(-v_min_fudged / -v_max_fudged));
2893 else
2894 result = (float)(ImLog((FLOATTYPE)v_clamped / v_min_fudged) / ImLog(v_max_fudged / v_min_fudged));
2895
2896 return flipped ? (1.0f - result) : result;
2897 }
2898 else
2899 {
2900 // Linear slider
2901 return (float)((FLOATTYPE)(SIGNEDTYPE)(v_clamped - v_min) / (FLOATTYPE)(SIGNEDTYPE)(v_max - v_min));
2902 }
2903 }
2904
2905 // Convert a parametric position on a slider into a value v in the output space (the logical opposite of ScaleRatioFromValueT)
2906 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
2907 TYPE ImGui::ScaleValueFromRatioT(ImGuiDataType data_type, float t, TYPE v_min, TYPE v_max, bool is_logarithmic, float logarithmic_zero_epsilon, float zero_deadzone_halfsize)
2908 {
2909 // We special-case the extents because otherwise our logarithmic fudging can lead to "mathematically correct"
2910 // but non-intuitive behaviors like a fully-left slider not actually reaching the minimum value. Also generally simpler.
2911 if (t <= 0.0f || v_min == v_max)
2912 return v_min;
2913 if (t >= 1.0f)
2914 return v_max;
2915
2916 TYPE result = (TYPE)0;
2917 if (is_logarithmic)
2918 {
2919 // Fudge min/max to avoid getting silly results close to zero
2920 FLOATTYPE v_min_fudged = (ImAbs((FLOATTYPE)v_min) < logarithmic_zero_epsilon) ? ((v_min < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_min;
2921 FLOATTYPE v_max_fudged = (ImAbs((FLOATTYPE)v_max) < logarithmic_zero_epsilon) ? ((v_max < 0.0f) ? -logarithmic_zero_epsilon : logarithmic_zero_epsilon) : (FLOATTYPE)v_max;
2922
2923 const bool flipped = v_max < v_min; // Check if range is "backwards"
2924 if (flipped)
2925 ImSwap(v_min_fudged, v_max_fudged);
2926
2927 // Awkward special case - we need ranges of the form (-100 .. 0) to convert to (-100 .. -epsilon), not (-100 .. epsilon)
2928 if ((v_max == 0.0f) && (v_min < 0.0f))
2929 v_max_fudged = -logarithmic_zero_epsilon;
2930
2931 float t_with_flip = flipped ? (1.0f - t) : t; // t, but flipped if necessary to account for us flipping the range
2932
2933 if ((v_min * v_max) < 0.0f) // Range crosses zero, so we have to do this in two parts
2934 {
2935 float zero_point_center = (-(float)ImMin(v_min, v_max)) / ImAbs((float)v_max - (float)v_min); // The zero point in parametric space
2936 float zero_point_snap_L = zero_point_center - zero_deadzone_halfsize;
2937 float zero_point_snap_R = zero_point_center + zero_deadzone_halfsize;
2938 if (t_with_flip >= zero_point_snap_L && t_with_flip <= zero_point_snap_R)
2939 result = (TYPE)0.0f; // Special case to make getting exactly zero possible (the epsilon prevents it otherwise)
2940 else if (t_with_flip < zero_point_center)
2941 result = (TYPE)-(logarithmic_zero_epsilon * ImPow(-v_min_fudged / logarithmic_zero_epsilon, (FLOATTYPE)(1.0f - (t_with_flip / zero_point_snap_L))));
2942 else
2943 result = (TYPE)(logarithmic_zero_epsilon * ImPow(v_max_fudged / logarithmic_zero_epsilon, (FLOATTYPE)((t_with_flip - zero_point_snap_R) / (1.0f - zero_point_snap_R))));
2944 }
2945 else if ((v_min < 0.0f) || (v_max < 0.0f)) // Entirely negative slider
2946 result = (TYPE)-(-v_max_fudged * ImPow(-v_min_fudged / -v_max_fudged, (FLOATTYPE)(1.0f - t_with_flip)));
2947 else
2948 result = (TYPE)(v_min_fudged * ImPow(v_max_fudged / v_min_fudged, (FLOATTYPE)t_with_flip));
2949 }
2950 else
2951 {
2952 // Linear slider
2953 const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
2954 if (is_floating_point)
2955 {
2956 result = ImLerp(v_min, v_max, t);
2957 }
2958 else if (t < 1.0)
2959 {
2960 // - For integer values we want the clicking position to match the grab box so we round above
2961 // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property..
2962 // - Not doing a *1.0 multiply at the end of a range as it tends to be lossy. While absolute aiming at a large s64/u64
2963 // range is going to be imprecise anyway, with this check we at least make the edge values matches expected limits.
2964 FLOATTYPE v_new_off_f = (SIGNEDTYPE)(v_max - v_min) * t;
2965 result = (TYPE)((SIGNEDTYPE)v_min + (SIGNEDTYPE)(v_new_off_f + (FLOATTYPE)(v_min > v_max ? -0.5 : 0.5)));
2966 }
2967 }
2968
2969 return result;
2970 }
2971
2972 // FIXME: Try to move more of the code into shared SliderBehavior()
2973 template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE>
2974 bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb)
2975 {
2976 ImGuiContext& g = *GImGui;
2977 const ImGuiStyle& style = g.Style;
2978
2979 const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X;
2980 const bool is_logarithmic = (flags & ImGuiSliderFlags_Logarithmic) != 0;
2981 const bool is_floating_point = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double);
2982 const float v_range_f = (float)(v_min < v_max ? v_max - v_min : v_min - v_max); // We don't need high precision for what we do with it.
2983
2984 // Calculate bounds
2985 const float grab_padding = 2.0f; // FIXME: Should be part of style.
2986 const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f;
2987 float grab_sz = style.GrabMinSize;
2988 if (!is_floating_point && v_range_f >= 0.0f) // v_range_f < 0 may happen on integer overflows
2989 grab_sz = ImMax(slider_sz / (v_range_f + 1), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit
2990 grab_sz = ImMin(grab_sz, slider_sz);
2991 const float slider_usable_sz = slider_sz - grab_sz;
2992 const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz * 0.5f;
2993 const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz * 0.5f;
2994
2995 float logarithmic_zero_epsilon = 0.0f; // Only valid when is_logarithmic is true
2996 float zero_deadzone_halfsize = 0.0f; // Only valid when is_logarithmic is true
2997 if (is_logarithmic)
2998 {
2999 // When using logarithmic sliders, we need to clamp to avoid hitting zero, but our choice of clamp value greatly affects slider precision. We attempt to use the specified precision to estimate a good lower bound.
3000 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 1;
3001 logarithmic_zero_epsilon = ImPow(0.1f, (float)decimal_precision);
3002 zero_deadzone_halfsize = (style.LogSliderDeadzone * 0.5f) / ImMax(slider_usable_sz, 1.0f);
3003 }
3004
3005 // Process interacting with the slider
3006 bool value_changed = false;
3007 if (g.ActiveId == id)
3008 {
3009 bool set_new_value = false;
3010 float clicked_t = 0.0f;
3011 if (g.ActiveIdSource == ImGuiInputSource_Mouse)
3012 {
3013 if (!g.IO.MouseDown[0])
3014 {
3015 ClearActiveID();
3016 }
3017 else
3018 {
3019 const float mouse_abs_pos = g.IO.MousePos[axis];
3020 if (g.ActiveIdIsJustActivated)
3021 {
3022 float grab_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3023 if (axis == ImGuiAxis_Y)
3024 grab_t = 1.0f - grab_t;
3025 const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
3026 const bool clicked_around_grab = (mouse_abs_pos >= grab_pos - grab_sz * 0.5f - 1.0f) && (mouse_abs_pos <= grab_pos + grab_sz * 0.5f + 1.0f); // No harm being extra generous here.
3027 g.SliderGrabClickOffset = (clicked_around_grab && is_floating_point) ? mouse_abs_pos - grab_pos : 0.0f;
3028 }
3029 if (slider_usable_sz > 0.0f)
3030 clicked_t = ImSaturate((mouse_abs_pos - g.SliderGrabClickOffset - slider_usable_pos_min) / slider_usable_sz);
3031 if (axis == ImGuiAxis_Y)
3032 clicked_t = 1.0f - clicked_t;
3033 set_new_value = true;
3034 }
3035 }
3036 else if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
3037 {
3038 if (g.ActiveIdIsJustActivated)
3039 {
3040 g.SliderCurrentAccum = 0.0f; // Reset any stored nav delta upon activation
3041 g.SliderCurrentAccumDirty = false;
3042 }
3043
3044 float input_delta = (axis == ImGuiAxis_X) ? GetNavTweakPressedAmount(axis) : -GetNavTweakPressedAmount(axis);
3045 if (input_delta != 0.0f)
3046 {
3047 const bool tweak_slow = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakSlow : ImGuiKey_NavKeyboardTweakSlow);
3048 const bool tweak_fast = IsKeyDown((g.NavInputSource == ImGuiInputSource_Gamepad) ? ImGuiKey_NavGamepadTweakFast : ImGuiKey_NavKeyboardTweakFast);
3049 const int decimal_precision = is_floating_point ? ImParseFormatPrecision(format, 3) : 0;
3050 if (decimal_precision > 0)
3051 {
3052 input_delta /= 100.0f; // Keyboard/Gamepad tweak speeds in % of slider bounds
3053 if (tweak_slow)
3054 input_delta /= 10.0f;
3055 }
3056 else
3057 {
3058 if ((v_range_f >= -100.0f && v_range_f <= 100.0f && v_range_f != 0.0f) || tweak_slow)
3059 input_delta = ((input_delta < 0.0f) ? -1.0f : +1.0f) / v_range_f; // Keyboard/Gamepad tweak speeds in integer steps
3060 else
3061 input_delta /= 100.0f;
3062 }
3063 if (tweak_fast)
3064 input_delta *= 10.0f;
3065
3066 g.SliderCurrentAccum += input_delta;
3067 g.SliderCurrentAccumDirty = true;
3068 }
3069
3070 float delta = g.SliderCurrentAccum;
3071 if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
3072 {
3073 ClearActiveID();
3074 }
3075 else if (g.SliderCurrentAccumDirty)
3076 {
3077 clicked_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3078
3079 if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits
3080 {
3081 set_new_value = false;
3082 g.SliderCurrentAccum = 0.0f; // If pushing up against the limits, don't continue to accumulate
3083 }
3084 else
3085 {
3086 set_new_value = true;
3087 float old_clicked_t = clicked_t;
3088 clicked_t = ImSaturate(clicked_t + delta);
3089
3090 // Calculate what our "new" clicked_t will be, and thus how far we actually moved the slider, and subtract this from the accumulator
3091 TYPE v_new = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3092 if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat))
3093 v_new = RoundScalarWithFormatT<TYPE>(format, data_type, v_new);
3094 float new_clicked_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, v_new, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3095
3096 if (delta > 0)
3097 g.SliderCurrentAccum -= ImMin(new_clicked_t - old_clicked_t, delta);
3098 else
3099 g.SliderCurrentAccum -= ImMax(new_clicked_t - old_clicked_t, delta);
3100 }
3101
3102 g.SliderCurrentAccumDirty = false;
3103 }
3104 }
3105
3106 if (set_new_value)
3107 if ((g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) || (flags & ImGuiSliderFlags_ReadOnly))
3108 set_new_value = false;
3109
3110 if (set_new_value)
3111 {
3112 TYPE v_new = ScaleValueFromRatioT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, clicked_t, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3113
3114 // Round to user desired precision based on format string
3115 if (is_floating_point && !(flags & ImGuiSliderFlags_NoRoundToFormat))
3116 v_new = RoundScalarWithFormatT<TYPE>(format, data_type, v_new);
3117
3118 // Apply result
3119 if (*v != v_new)
3120 {
3121 *v = v_new;
3122 value_changed = true;
3123 }
3124 }
3125 }
3126
3127 if (slider_sz < 1.0f)
3128 {
3129 *out_grab_bb = ImRect(bb.Min, bb.Min);
3130 }
3131 else
3132 {
3133 // Output grab position so it can be displayed by the caller
3134 float grab_t = ScaleRatioFromValueT<TYPE, SIGNEDTYPE, FLOATTYPE>(data_type, *v, v_min, v_max, is_logarithmic, logarithmic_zero_epsilon, zero_deadzone_halfsize);
3135 if (axis == ImGuiAxis_Y)
3136 grab_t = 1.0f - grab_t;
3137 const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
3138 if (axis == ImGuiAxis_X)
3139 *out_grab_bb = ImRect(grab_pos - grab_sz * 0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz * 0.5f, bb.Max.y - grab_padding);
3140 else
3141 *out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz * 0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz * 0.5f);
3142 }
3143
3144 return value_changed;
3145 }
3146
3147 // For 32-bit and larger types, slider bounds are limited to half the natural type range.
3148 // So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok.
3149 // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders.
3150 bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* p_v, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags, ImRect* out_grab_bb)
3151 {
3152 // Read imgui.cpp "API BREAKING CHANGES" section for 1.78 if you hit this assert.
3153 IM_ASSERT((flags == 1 || (flags & ImGuiSliderFlags_InvalidMask_) == 0) && "Invalid ImGuiSliderFlags flags! Has the legacy 'float power' argument been mistakenly cast to flags? Call function with ImGuiSliderFlags_Logarithmic flags instead.");
3154 IM_ASSERT((flags & ImGuiSliderFlags_WrapAround) == 0); // Not supported by SliderXXX(), only by DragXXX()
3155
3156 switch (data_type)
3157 {
3158 case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)p_v; bool r = SliderBehaviorT<ImS32, ImS32, float>(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)p_min, *(const ImS8*)p_max, format, flags, out_grab_bb); if (r) *(ImS8*)p_v = (ImS8)v32; return r; }
3159 case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)p_v; bool r = SliderBehaviorT<ImU32, ImS32, float>(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)p_min, *(const ImU8*)p_max, format, flags, out_grab_bb); if (r) *(ImU8*)p_v = (ImU8)v32; return r; }
3160 case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)p_v; bool r = SliderBehaviorT<ImS32, ImS32, float>(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)p_min, *(const ImS16*)p_max, format, flags, out_grab_bb); if (r) *(ImS16*)p_v = (ImS16)v32; return r; }
3161 case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)p_v; bool r = SliderBehaviorT<ImU32, ImS32, float>(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)p_min, *(const ImU16*)p_max, format, flags, out_grab_bb); if (r) *(ImU16*)p_v = (ImU16)v32; return r; }
3162 case ImGuiDataType_S32:
3163 IM_ASSERT(*(const ImS32*)p_min >= IM_S32_MIN / 2 && *(const ImS32*)p_max <= IM_S32_MAX / 2);
3164 return SliderBehaviorT<ImS32, ImS32, float >(bb, id, data_type, (ImS32*)p_v, *(const ImS32*)p_min, *(const ImS32*)p_max, format, flags, out_grab_bb);
3165 case ImGuiDataType_U32:
3166 IM_ASSERT(*(const ImU32*)p_max <= IM_U32_MAX / 2);
3167 return SliderBehaviorT<ImU32, ImS32, float >(bb, id, data_type, (ImU32*)p_v, *(const ImU32*)p_min, *(const ImU32*)p_max, format, flags, out_grab_bb);
3168 case ImGuiDataType_S64:
3169 IM_ASSERT(*(const ImS64*)p_min >= IM_S64_MIN / 2 && *(const ImS64*)p_max <= IM_S64_MAX / 2);
3170 return SliderBehaviorT<ImS64, ImS64, double>(bb, id, data_type, (ImS64*)p_v, *(const ImS64*)p_min, *(const ImS64*)p_max, format, flags, out_grab_bb);
3171 case ImGuiDataType_U64:
3172 IM_ASSERT(*(const ImU64*)p_max <= IM_U64_MAX / 2);
3173 return SliderBehaviorT<ImU64, ImS64, double>(bb, id, data_type, (ImU64*)p_v, *(const ImU64*)p_min, *(const ImU64*)p_max, format, flags, out_grab_bb);
3174 case ImGuiDataType_Float:
3175 IM_ASSERT(*(const float*)p_min >= -FLT_MAX / 2.0f && *(const float*)p_max <= FLT_MAX / 2.0f);
3176 return SliderBehaviorT<float, float, float >(bb, id, data_type, (float*)p_v, *(const float*)p_min, *(const float*)p_max, format, flags, out_grab_bb);
3177 case ImGuiDataType_Double:
3178 IM_ASSERT(*(const double*)p_min >= -DBL_MAX / 2.0f && *(const double*)p_max <= DBL_MAX / 2.0f);
3179 return SliderBehaviorT<double, double, double>(bb, id, data_type, (double*)p_v, *(const double*)p_min, *(const double*)p_max, format, flags, out_grab_bb);
3180 case ImGuiDataType_COUNT: break;
3181 }
3182 IM_ASSERT(0);
3183 return false;
3184 }
3185
3186 // Note: p_data, p_min and p_max are _pointers_ to a memory address holding the data. For a slider, they are all required.
3187 // Read code of e.g. SliderFloat(), SliderInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
3188 bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)
3189 {
3190 ImGuiWindow* window = GetCurrentWindow();
3191 if (window->SkipItems)
3192 return false;
3193
3194 ImGuiContext& g = *GImGui;
3195 const ImGuiStyle& style = g.Style;
3196 const ImGuiID id = window->GetID(label);
3197 const float w = CalcItemWidth();
3198
3199 const ImVec2 label_size = CalcTextSize(label, NULL, true);
3200 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y * 2.0f));
3201 const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
3202
3203 const bool temp_input_allowed = (flags & ImGuiSliderFlags_NoInput) == 0;
3204 ItemSize(total_bb, style.FramePadding.y);
3205 if (!ItemAdd(total_bb, id, &frame_bb, temp_input_allowed ? ImGuiItemFlags_Inputable : 0))
3206 return false;
3207
3208 // Default format string when passing NULL
3209 if (format == NULL)
3210 format = DataTypeGetInfo(data_type)->PrintFmt;
3211
3212 const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
3213 bool temp_input_is_active = temp_input_allowed && TempInputIsActive(id);
3214 if (!temp_input_is_active)
3215 {
3216 // Tabbing or CTRL-clicking on Slider turns it into an input box
3217 const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
3218 const bool make_active = (clicked || g.NavActivateId == id);
3219 if (make_active && clicked)
3220 SetKeyOwner(ImGuiKey_MouseLeft, id);
3221 if (make_active && temp_input_allowed)
3222 if ((clicked && g.IO.KeyCtrl) || (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput)))
3223 temp_input_is_active = true;
3224
3225 if (make_active && !temp_input_is_active)
3226 {
3227 SetActiveID(id, window);
3228 SetFocusID(id, window);
3229 FocusWindow(window);
3230 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
3231 }
3232 }
3233
3234 if (temp_input_is_active)
3235 {
3236 // Only clamp CTRL+Click input when ImGuiSliderFlags_ClampOnInput is set (generally via ImGuiSliderFlags_AlwaysClamp)
3237 const bool clamp_enabled = (flags & ImGuiSliderFlags_ClampOnInput) != 0;
3238 return TempInputScalar(frame_bb, id, label, data_type, p_data, format, clamp_enabled ? p_min : NULL, clamp_enabled ? p_max : NULL);
3239 }
3240
3241 // Draw frame
3242 const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
3243 RenderNavCursor(frame_bb, id);
3244 RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
3245
3246 // Slider behavior
3247 ImRect grab_bb;
3248 const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags, &grab_bb);
3249 if (value_changed)
3250 MarkItemEdited(id);
3251
3252 // Render grab
3253 if (grab_bb.Max.x > grab_bb.Min.x)
3254 window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
3255
3256 // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
3257 char value_buf[64];
3258 const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
3259 if (g.LogEnabled)
3260 LogSetNextTextDecoration("{", "}");
3261 RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f));
3262
3263 if (label_size.x > 0.0f)
3264 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
3265
3266 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (temp_input_allowed ? ImGuiItemStatusFlags_Inputable : 0));
3267 return value_changed;
3268 }
3269
3270 // Add multiple sliders on 1 line for compact edition of multiple components
3271 bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, ImGuiSliderFlags flags)
3272 {
3273 ImGuiWindow* window = GetCurrentWindow();
3274 if (window->SkipItems)
3275 return false;
3276
3277 ImGuiContext& g = *GImGui;
3278 bool value_changed = false;
3279 BeginGroup();
3280 PushID(label);
3281 PushMultiItemsWidths(components, CalcItemWidth());
3282 size_t type_size = GDataTypeInfo[data_type].Size;
3283 for (int i = 0; i < components; i++)
3284 {
3285 PushID(i);
3286 if (i > 0)
3287 SameLine(0, g.Style.ItemInnerSpacing.x);
3288 value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, flags);
3289 PopID();
3290 PopItemWidth();
3291 v = (void*)((char*)v + type_size);
3292 }
3293 PopID();
3294
3295 const char* label_end = FindRenderedTextEnd(label);
3296 if (label != label_end)
3297 {
3298 SameLine(0, g.Style.ItemInnerSpacing.x);
3299 TextEx(label, label_end);
3300 }
3301
3302 EndGroup();
3303 return value_changed;
3304 }
3305
3306 bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3307 {
3308 return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, flags);
3309 }
3310
3311 bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3312 {
3313 return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, flags);
3314 }
3315
3316 bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3317 {
3318 return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, flags);
3319 }
3320
3321 bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3322 {
3323 return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, flags);
3324 }
3325
3326 bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format, ImGuiSliderFlags flags)
3327 {
3328 if (format == NULL)
3329 format = "%.0f deg";
3330 float v_deg = (*v_rad) * 360.0f / (2 * IM_PI);
3331 bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, flags);
3332 if (value_changed)
3333 *v_rad = v_deg * (2 * IM_PI) / 360.0f;
3334 return value_changed;
3335 }
3336
3337 bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3338 {
3339 return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format, flags);
3340 }
3341
3342 bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3343 {
3344 return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format, flags);
3345 }
3346
3347 bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3348 {
3349 return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format, flags);
3350 }
3351
3352 bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3353 {
3354 return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format, flags);
3355 }
3356
3357 bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format, ImGuiSliderFlags flags)
3358 {
3359 ImGuiWindow* window = GetCurrentWindow();
3360 if (window->SkipItems)
3361 return false;
3362
3363 ImGuiContext& g = *GImGui;
3364 const ImGuiStyle& style = g.Style;
3365 const ImGuiID id = window->GetID(label);
3366
3367 const ImVec2 label_size = CalcTextSize(label, NULL, true);
3368 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
3369 const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
3370
3371 ItemSize(bb, style.FramePadding.y);
3372 if (!ItemAdd(frame_bb, id))
3373 return false;
3374
3375 // Default format string when passing NULL
3376 if (format == NULL)
3377 format = DataTypeGetInfo(data_type)->PrintFmt;
3378
3379 const bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags);
3380 const bool clicked = hovered && IsMouseClicked(0, ImGuiInputFlags_None, id);
3381 if (clicked || g.NavActivateId == id)
3382 {
3383 if (clicked)
3384 SetKeyOwner(ImGuiKey_MouseLeft, id);
3385 SetActiveID(id, window);
3386 SetFocusID(id, window);
3387 FocusWindow(window);
3388 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
3389 }
3390
3391 // Draw frame
3392 const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
3393 RenderNavCursor(frame_bb, id);
3394 RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding);
3395
3396 // Slider behavior
3397 ImRect grab_bb;
3398 const bool value_changed = SliderBehavior(frame_bb, id, data_type, p_data, p_min, p_max, format, flags | ImGuiSliderFlags_Vertical, &grab_bb);
3399 if (value_changed)
3400 MarkItemEdited(id);
3401
3402 // Render grab
3403 if (grab_bb.Max.y > grab_bb.Min.y)
3404 window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
3405
3406 // Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
3407 // For the vertical slider we allow centered text to overlap the frame padding
3408 char value_buf[64];
3409 const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, p_data, format);
3410 RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.0f));
3411 if (label_size.x > 0.0f)
3412 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
3413
3414 return value_changed;
3415 }
3416
3417 bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, ImGuiSliderFlags flags)
3418 {
3419 return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, flags);
3420 }
3421
3422 bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format, ImGuiSliderFlags flags)
3423 {
3424 return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format, flags);
3425 }
3426
3427 //-------------------------------------------------------------------------
3428 // [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc.
3429 //-------------------------------------------------------------------------
3430 // - ImParseFormatFindStart() [Internal]
3431 // - ImParseFormatFindEnd() [Internal]
3432 // - ImParseFormatTrimDecorations() [Internal]
3433 // - ImParseFormatSanitizeForPrinting() [Internal]
3434 // - ImParseFormatSanitizeForScanning() [Internal]
3435 // - ImParseFormatPrecision() [Internal]
3436 // - TempInputTextScalar() [Internal]
3437 // - InputScalar()
3438 // - InputScalarN()
3439 // - InputFloat()
3440 // - InputFloat2()
3441 // - InputFloat3()
3442 // - InputFloat4()
3443 // - InputInt()
3444 // - InputInt2()
3445 // - InputInt3()
3446 // - InputInt4()
3447 // - InputDouble()
3448 //-------------------------------------------------------------------------
3449
3450 // We don't use strchr() because our strings are usually very short and often start with '%'
3451 const char* ImParseFormatFindStart(const char* fmt)
3452 {
3453 while (char c = fmt[0])
3454 {
3455 if (c == '%' && fmt[1] != '%')
3456 return fmt;
3457 else if (c == '%')
3458 fmt++;
3459 fmt++;
3460 }
3461 return fmt;
3462 }
3463
3464 const char* ImParseFormatFindEnd(const char* fmt)
3465 {
3466 // Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format.
3467 if (fmt[0] != '%')
3468 return fmt;
3469 const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A'));
3470 const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a'));
3471 for (char c; (c = *fmt) != 0; fmt++)
3472 {
3473 if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0)
3474 return fmt + 1;
3475 if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0)
3476 return fmt + 1;
3477 }
3478 return fmt;
3479 }
3480
3481 // Extract the format out of a format string with leading or trailing decorations
3482 // fmt = "blah blah" -> return ""
3483 // fmt = "%.3f" -> return fmt
3484 // fmt = "hello %.3f" -> return fmt + 6
3485 // fmt = "%.3f hello" -> return buf written with "%.3f"
3486 const char* ImParseFormatTrimDecorations(const char* fmt, char* buf, size_t buf_size)
3487 {
3488 const char* fmt_start = ImParseFormatFindStart(fmt);
3489 if (fmt_start[0] != '%')
3490 return "";
3491 const char* fmt_end = ImParseFormatFindEnd(fmt_start);
3492 if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data.
3493 return fmt_start;
3494 ImStrncpy(buf, fmt_start, ImMin((size_t)(fmt_end - fmt_start) + 1, buf_size));
3495 return buf;
3496 }
3497
3498 // Sanitize format
3499 // - Zero terminate so extra characters after format (e.g. "%f123") don't confuse atof/atoi
3500 // - stb_sprintf.h supports several new modifiers which format numbers in a way that also makes them incompatible atof/atoi.
3501 void ImParseFormatSanitizeForPrinting(const char* fmt_in, char* fmt_out, size_t fmt_out_size)
3502 {
3503 const char* fmt_end = ImParseFormatFindEnd(fmt_in);
3504 IM_UNUSED(fmt_out_size);
3505 IM_ASSERT((size_t)(fmt_end - fmt_in + 1) < fmt_out_size); // Format is too long, let us know if this happens to you!
3506 while (fmt_in < fmt_end)
3507 {
3508 char c = *fmt_in++;
3509 if (c != '\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '.
3510 *(fmt_out++) = c;
3511 }
3512 *fmt_out = 0; // Zero-terminate
3513 }
3514
3515 // - For scanning we need to remove all width and precision fields and flags "%+3.7f" -> "%f". BUT don't strip types like "%I64d" which includes digits. ! "%07I64d" -> "%I64d"
3516 const char* ImParseFormatSanitizeForScanning(const char* fmt_in, char* fmt_out, size_t fmt_out_size)
3517 {
3518 const char* fmt_end = ImParseFormatFindEnd(fmt_in);
3519 const char* fmt_out_begin = fmt_out;
3520 IM_UNUSED(fmt_out_size);
3521 IM_ASSERT((size_t)(fmt_end - fmt_in + 1) < fmt_out_size); // Format is too long, let us know if this happens to you!
3522 bool has_type = false;
3523 while (fmt_in < fmt_end)
3524 {
3525 char c = *fmt_in++;
3526 if (!has_type && ((c >= '0' && c <= '9') || c == '.' || c == '+' || c == '#'))
3527 continue;
3528 has_type |= ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); // Stop skipping digits
3529 if (c != '\'' && c != '$' && c != '_') // Custom flags provided by stb_sprintf.h. POSIX 2008 also supports '.
3530 *(fmt_out++) = c;
3531 }
3532 *fmt_out = 0; // Zero-terminate
3533 return fmt_out_begin;
3534 }
3535
3536 template<typename TYPE>
3537 static const char* ImAtoi(const char* src, TYPE* output)
3538 {
3539 int negative = 0;
3540 if (*src == '-') { negative = 1; src++; }
3541 if (*src == '+') { src++; }
3542 TYPE v = 0;
3543 while (*src >= '0' && *src <= '9')
3544 v = (v * 10) + (*src++ - '0');
3545 *output = negative ? -v : v;
3546 return src;
3547 }
3548
3549 // Parse display precision back from the display format string
3550 // FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed.
3551 int ImParseFormatPrecision(const char* fmt, int default_precision)
3552 {
3553 fmt = ImParseFormatFindStart(fmt);
3554 if (fmt[0] != '%')
3555 return default_precision;
3556 fmt++;
3557 while (*fmt >= '0' && *fmt <= '9')
3558 fmt++;
3559 int precision = INT_MAX;
3560 if (*fmt == '.')
3561 {
3562 fmt = ImAtoi<int>(fmt + 1, &precision);
3563 if (precision < 0 || precision > 99)
3564 precision = default_precision;
3565 }
3566 if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
3567 precision = -1;
3568 if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX)
3569 precision = -1;
3570 return (precision == INT_MAX) ? default_precision : precision;
3571 }
3572
3573 // Create text input in place of another active widget (e.g. used when doing a CTRL+Click on drag/slider widgets)
3574 // FIXME: Facilitate using this in variety of other situations.
3575 // FIXME: Among other things, setting ImGuiItemFlags_AllowDuplicateId in LastItemData is currently correct but
3576 // the expected relationship between TempInputXXX functions and LastItemData is a little fishy.
3577 bool ImGui::TempInputText(const ImRect& bb, ImGuiID id, const char* label, char* buf, int buf_size, ImGuiInputTextFlags flags)
3578 {
3579 // On the first frame, g.TempInputTextId == 0, then on subsequent frames it becomes == id.
3580 // We clear ActiveID on the first frame to allow the InputText() taking it back.
3581 ImGuiContext& g = *GImGui;
3582 const bool init = (g.TempInputId != id);
3583 if (init)
3584 ClearActiveID();
3585
3586 g.CurrentWindow->DC.CursorPos = bb.Min;
3587 g.LastItemData.ItemFlags |= ImGuiItemFlags_AllowDuplicateId;
3588 bool value_changed = InputTextEx(label, NULL, buf, buf_size, bb.GetSize(), flags | ImGuiInputTextFlags_MergedItem);
3589 if (init)
3590 {
3591 // First frame we started displaying the InputText widget, we expect it to take the active id.
3592 IM_ASSERT(g.ActiveId == id);
3593 g.TempInputId = g.ActiveId;
3594 }
3595 return value_changed;
3596 }
3597
3598 // Note that Drag/Slider functions are only forwarding the min/max values clamping values if the ImGuiSliderFlags_AlwaysClamp flag is set!
3599 // This is intended: this way we allow CTRL+Click manual input to set a value out of bounds, for maximum flexibility.
3600 // However this may not be ideal for all uses, as some user code may break on out of bound values.
3601 bool ImGui::TempInputScalar(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* p_data, const char* format, const void* p_clamp_min, const void* p_clamp_max)
3602 {
3603 // FIXME: May need to clarify display behavior if format doesn't contain %.
3604 // "%d" -> "%d" / "There are %d items" -> "%d" / "items" -> "%d" (fallback). Also see #6405
3605 ImGuiContext& g = *GImGui;
3606 const ImGuiDataTypeInfo* type_info = DataTypeGetInfo(data_type);
3607 char fmt_buf[32];
3608 char data_buf[32];
3609 format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf));
3610 if (format[0] == 0)
3611 format = type_info->PrintFmt;
3612 DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, p_data, format);
3613 ImStrTrimBlanks(data_buf);
3614
3615 ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint;
3616 g.LastItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited; // Because TempInputText() uses ImGuiInputTextFlags_MergedItem it doesn't submit a new item, so we poke LastItemData.
3617 bool value_changed = false;
3618 if (TempInputText(bb, id, label, data_buf, IM_ARRAYSIZE(data_buf), flags))
3619 {
3620 // Backup old value
3621 size_t data_type_size = type_info->Size;
3622 ImGuiDataTypeStorage data_backup;
3623 memcpy(&data_backup, p_data, data_type_size);
3624
3625 // Apply new value (or operations) then clamp
3626 DataTypeApplyFromText(data_buf, data_type, p_data, format, NULL);
3627 if (p_clamp_min || p_clamp_max)
3628 {
3629 if (p_clamp_min && p_clamp_max && DataTypeCompare(data_type, p_clamp_min, p_clamp_max) > 0)
3630 ImSwap(p_clamp_min, p_clamp_max);
3631 DataTypeClamp(data_type, p_data, p_clamp_min, p_clamp_max);
3632 }
3633
3634 // Only mark as edited if new value is different
3635 g.LastItemData.ItemFlags &= ~ImGuiItemFlags_NoMarkEdited;
3636 value_changed = memcmp(&data_backup, p_data, data_type_size) != 0;
3637 if (value_changed)
3638 MarkItemEdited(id);
3639 }
3640 return value_changed;
3641 }
3642
3643 void ImGui::SetNextItemRefVal(ImGuiDataType data_type, void* p_data)
3644 {
3645 ImGuiContext& g = *GImGui;
3646 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasRefVal;
3647 memcpy(&g.NextItemData.RefVal, p_data, DataTypeGetInfo(data_type)->Size);
3648 }
3649
3650 // Note: p_data, p_step, p_step_fast are _pointers_ to a memory address holding the data. For an Input widget, p_step and p_step_fast are optional.
3651 // Read code of e.g. InputFloat(), InputInt() etc. or examples in 'Demo->Widgets->Data Types' to understand how to use this function directly.
3652 bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags)
3653 {
3654 ImGuiWindow* window = GetCurrentWindow();
3655 if (window->SkipItems)
3656 return false;
3657
3658 ImGuiContext& g = *GImGui;
3659 ImGuiStyle& style = g.Style;
3660 IM_ASSERT((flags & ImGuiInputTextFlags_EnterReturnsTrue) == 0); // Not supported by InputScalar(). Please open an issue if you this would be useful to you. Otherwise use IsItemDeactivatedAfterEdit()!
3661
3662 if (format == NULL)
3663 format = DataTypeGetInfo(data_type)->PrintFmt;
3664
3665 void* p_data_default = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasRefVal) ? &g.NextItemData.RefVal : &g.DataTypeZeroValue;
3666
3667 char buf[64];
3668 if ((flags & ImGuiInputTextFlags_DisplayEmptyRefVal) && DataTypeCompare(data_type, p_data, p_data_default) == 0)
3669 buf[0] = 0;
3670 else
3671 DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, p_data, format);
3672
3673 // Disable the MarkItemEdited() call in InputText but keep ImGuiItemStatusFlags_Edited.
3674 // We call MarkItemEdited() ourselves by comparing the actual data rather than the string.
3675 g.NextItemData.ItemFlags |= ImGuiItemFlags_NoMarkEdited;
3676 flags |= ImGuiInputTextFlags_AutoSelectAll | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint;
3677
3678 bool value_changed = false;
3679 if (p_step == NULL)
3680 {
3681 if (InputText(label, buf, IM_ARRAYSIZE(buf), flags))
3682 value_changed = DataTypeApplyFromText(buf, data_type, p_data, format, (flags & ImGuiInputTextFlags_ParseEmptyRefVal) ? p_data_default : NULL);
3683 }
3684 else
3685 {
3686 const float button_size = GetFrameHeight();
3687
3688 BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive()
3689 PushID(label);
3690 SetNextItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2));
3691 if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view
3692 value_changed = DataTypeApplyFromText(buf, data_type, p_data, format, (flags & ImGuiInputTextFlags_ParseEmptyRefVal) ? p_data_default : NULL);
3693 IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Inputable);
3694
3695 // Step buttons
3696 const ImVec2 backup_frame_padding = style.FramePadding;
3697 style.FramePadding.x = style.FramePadding.y;
3698 if (flags & ImGuiInputTextFlags_ReadOnly)
3699 BeginDisabled();
3700 PushItemFlag(ImGuiItemFlags_ButtonRepeat, true);
3701 SameLine(0, style.ItemInnerSpacing.x);
3702 if (ButtonEx("-", ImVec2(button_size, button_size)))
3703 {
3704 DataTypeApplyOp(data_type, '-', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);
3705 value_changed = true;
3706 }
3707 SameLine(0, style.ItemInnerSpacing.x);
3708 if (ButtonEx("+", ImVec2(button_size, button_size)))
3709 {
3710 DataTypeApplyOp(data_type, '+', p_data, p_data, g.IO.KeyCtrl && p_step_fast ? p_step_fast : p_step);
3711 value_changed = true;
3712 }
3713 PopItemFlag();
3714 if (flags & ImGuiInputTextFlags_ReadOnly)
3715 EndDisabled();
3716
3717 const char* label_end = FindRenderedTextEnd(label);
3718 if (label != label_end)
3719 {
3720 SameLine(0, style.ItemInnerSpacing.x);
3721 TextEx(label, label_end);
3722 }
3723 style.FramePadding = backup_frame_padding;
3724
3725 PopID();
3726 EndGroup();
3727 }
3728
3729 g.LastItemData.ItemFlags &= ~ImGuiItemFlags_NoMarkEdited;
3730 if (value_changed)
3731 MarkItemEdited(g.LastItemData.ID);
3732
3733 return value_changed;
3734 }
3735
3736 bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step, const void* p_step_fast, const char* format, ImGuiInputTextFlags flags)
3737 {
3738 ImGuiWindow* window = GetCurrentWindow();
3739 if (window->SkipItems)
3740 return false;
3741
3742 ImGuiContext& g = *GImGui;
3743 bool value_changed = false;
3744 BeginGroup();
3745 PushID(label);
3746 PushMultiItemsWidths(components, CalcItemWidth());
3747 size_t type_size = GDataTypeInfo[data_type].Size;
3748 for (int i = 0; i < components; i++)
3749 {
3750 PushID(i);
3751 if (i > 0)
3752 SameLine(0, g.Style.ItemInnerSpacing.x);
3753 value_changed |= InputScalar("", data_type, p_data, p_step, p_step_fast, format, flags);
3754 PopID();
3755 PopItemWidth();
3756 p_data = (void*)((char*)p_data + type_size);
3757 }
3758 PopID();
3759
3760 const char* label_end = FindRenderedTextEnd(label);
3761 if (label != label_end)
3762 {
3763 SameLine(0.0f, g.Style.ItemInnerSpacing.x);
3764 TextEx(label, label_end);
3765 }
3766
3767 EndGroup();
3768 return value_changed;
3769 }
3770
3771 bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags)
3772 {
3773 return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step > 0.0f ? &step : NULL), (void*)(step_fast > 0.0f ? &step_fast : NULL), format, flags);
3774 }
3775
3776 bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags)
3777 {
3778 return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags);
3779 }
3780
3781 bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags)
3782 {
3783 return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags);
3784 }
3785
3786 bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags)
3787 {
3788 return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags);
3789 }
3790
3791 bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags)
3792 {
3793 // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes.
3794 const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
3795 return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step > 0 ? &step : NULL), (void*)(step_fast > 0 ? &step_fast : NULL), format, flags);
3796 }
3797
3798 bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags)
3799 {
3800 return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", flags);
3801 }
3802
3803 bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags)
3804 {
3805 return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", flags);
3806 }
3807
3808 bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags)
3809 {
3810 return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", flags);
3811 }
3812
3813 bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags)
3814 {
3815 return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step > 0.0 ? &step : NULL), (void*)(step_fast > 0.0 ? &step_fast : NULL), format, flags);
3816 }
3817
3818 //-------------------------------------------------------------------------
3819 // [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint
3820 //-------------------------------------------------------------------------
3821 // - imstb_textedit.h include
3822 // - InputText()
3823 // - InputTextWithHint()
3824 // - InputTextMultiline()
3825 // - InputTextGetCharInfo() [Internal]
3826 // - InputTextReindexLines() [Internal]
3827 // - InputTextReindexLinesRange() [Internal]
3828 // - InputTextEx() [Internal]
3829 // - DebugNodeInputTextState() [Internal]
3830 //-------------------------------------------------------------------------
3831
3832 namespace ImStb
3833 {
3834 #include "imstb_textedit.h"
3835 }
3836
3837 bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
3838 {
3839 IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
3840 return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
3841 }
3842
3843 bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
3844 {
3845 return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
3846 }
3847
3848 bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data)
3849 {
3850 IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() or InputTextEx() manually if you need multi-line + hint.
3851 return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data);
3852 }
3853
3854 // This is only used in the path where the multiline widget is inactivate.
3855 static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
3856 {
3857 int line_count = 0;
3858 const char* s = text_begin;
3859 while (true)
3860 {
3861 const char* s_eol = strchr(s, '\n');
3862 line_count++;
3863 if (s_eol == NULL)
3864 {
3865 s = s + strlen(s);
3866 break;
3867 }
3868 s = s_eol + 1;
3869 }
3870 *out_text_end = s;
3871 return line_count;
3872 }
3873
3874 // FIXME: Ideally we'd share code with ImFont::CalcTextSizeA()
3875 static ImVec2 InputTextCalcTextSize(ImGuiContext* ctx, const char* text_begin, const char* text_end, const char** remaining, ImVec2* out_offset, bool stop_on_new_line)
3876 {
3877 ImGuiContext& g = *ctx;
3878 ImFont* font = g.Font;
3879 const float line_height = g.FontSize;
3880 const float scale = line_height / font->FontSize;
3881
3882 ImVec2 text_size = ImVec2(0, 0);
3883 float line_width = 0.0f;
3884
3885 const char* s = text_begin;
3886 while (s < text_end)
3887 {
3888 unsigned int c = (unsigned int)*s;
3889 if (c < 0x80)
3890 s += 1;
3891 else
3892 s += ImTextCharFromUtf8(&c, s, text_end);
3893
3894 if (c == '\n')
3895 {
3896 text_size.x = ImMax(text_size.x, line_width);
3897 text_size.y += line_height;
3898 line_width = 0.0f;
3899 if (stop_on_new_line)
3900 break;
3901 continue;
3902 }
3903 if (c == '\r')
3904 continue;
3905
3906 const float char_width = ((int)c < font->IndexAdvanceX.Size ? font->IndexAdvanceX.Data[c] : font->FallbackAdvanceX) * scale;
3907 line_width += char_width;
3908 }
3909
3910 if (text_size.x < line_width)
3911 text_size.x = line_width;
3912
3913 if (out_offset)
3914 *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
3915
3916 if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
3917 text_size.y += line_height;
3918
3919 if (remaining)
3920 *remaining = s;
3921
3922 return text_size;
3923 }
3924
3925 // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)
3926 // With our UTF-8 use of stb_textedit:
3927 // - STB_TEXTEDIT_GETCHAR is nothing more than a a "GETBYTE". It's only used to compare to ascii or to copy blocks of text so we are fine.
3928 // - One exception is the STB_TEXTEDIT_IS_SPACE feature which would expect a full char in order to handle full-width space such as 0x3000 (see ImCharIsBlankW).
3929 // - ...but we don't use that feature.
3930 namespace ImStb
3931 {
3932 static int STB_TEXTEDIT_STRINGLEN(const ImGuiInputTextState* obj) { return obj->TextLen; }
3933 static char STB_TEXTEDIT_GETCHAR(const ImGuiInputTextState* obj, int idx) { IM_ASSERT(idx <= obj->TextLen); return obj->TextA[idx]; }
3934 static float STB_TEXTEDIT_GETWIDTH(ImGuiInputTextState* obj, int line_start_idx, int char_idx) { unsigned int c; ImTextCharFromUtf8(&c, obj->TextA.Data + line_start_idx + char_idx, obj->TextA.Data + obj->TextLen); if ((ImWchar)c == '\n') return IMSTB_TEXTEDIT_GETWIDTH_NEWLINE; ImGuiContext& g = *obj->Ctx; return g.Font->GetCharAdvance((ImWchar)c) * g.FontScale; }
3935 static char STB_TEXTEDIT_NEWLINE = '\n';
3936 static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, ImGuiInputTextState* obj, int line_start_idx)
3937 {
3938 const char* text = obj->TextA.Data;
3939 const char* text_remaining = NULL;
3940 const ImVec2 size = InputTextCalcTextSize(obj->Ctx, text + line_start_idx, text + obj->TextLen, &text_remaining, NULL, true);
3941 r->x0 = 0.0f;
3942 r->x1 = size.x;
3943 r->baseline_y_delta = size.y;
3944 r->ymin = 0.0f;
3945 r->ymax = size.y;
3946 r->num_chars = (int)(text_remaining - (text + line_start_idx));
3947 }
3948
3949 #define IMSTB_TEXTEDIT_GETNEXTCHARINDEX IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL
3950 #define IMSTB_TEXTEDIT_GETPREVCHARINDEX IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL
3951
3952 static int IMSTB_TEXTEDIT_GETNEXTCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
3953 {
3954 if (idx >= obj->TextLen)
3955 return obj->TextLen + 1;
3956 unsigned int c;
3957 return idx + ImTextCharFromUtf8(&c, obj->TextA.Data + idx, obj->TextA.Data + obj->TextLen);
3958 }
3959
3960 static int IMSTB_TEXTEDIT_GETPREVCHARINDEX_IMPL(ImGuiInputTextState* obj, int idx)
3961 {
3962 if (idx <= 0)
3963 return -1;
3964 const char* p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, obj->TextA.Data + idx);
3965 return (int)(p - obj->TextA.Data);
3966 }
3967
3968 static bool ImCharIsSeparatorW(unsigned int c)
3969 {
3970 static const unsigned int separator_list[] =
3971 {
3972 ',', 0x3001, '.', 0x3002, ';', 0xFF1B, '(', 0xFF08, ')', 0xFF09, '{', 0xFF5B, '}', 0xFF5D,
3973 '[', 0x300C, ']', 0x300D, '|', 0xFF5C, '!', 0xFF01, '\\', 0xFFE5, '/', 0x30FB, 0xFF0F,
3974 '\n', '\r',
3975 };
3976 for (unsigned int separator : separator_list)
3977 if (c == separator)
3978 return true;
3979 return false;
3980 }
3981
3982 static int is_word_boundary_from_right(ImGuiInputTextState* obj, int idx)
3983 {
3984 // When ImGuiInputTextFlags_Password is set, we don't want actions such as CTRL+Arrow to leak the fact that underlying data are blanks or separators.
3985 if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
3986 return 0;
3987
3988 const char* curr_p = obj->TextA.Data + idx;
3989 const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
3990 unsigned int curr_c; ImTextCharFromUtf8(&curr_c, curr_p, obj->TextA.Data + obj->TextLen);
3991 unsigned int prev_c; ImTextCharFromUtf8(&prev_c, prev_p, obj->TextA.Data + obj->TextLen);
3992
3993 bool prev_white = ImCharIsBlankW(prev_c);
3994 bool prev_separ = ImCharIsSeparatorW(prev_c);
3995 bool curr_white = ImCharIsBlankW(curr_c);
3996 bool curr_separ = ImCharIsSeparatorW(curr_c);
3997 return ((prev_white || prev_separ) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
3998 }
3999 static int is_word_boundary_from_left(ImGuiInputTextState* obj, int idx)
4000 {
4001 if ((obj->Flags & ImGuiInputTextFlags_Password) || idx <= 0)
4002 return 0;
4003
4004 const char* curr_p = obj->TextA.Data + idx;
4005 const char* prev_p = ImTextFindPreviousUtf8Codepoint(obj->TextA.Data, curr_p);
4006 unsigned int prev_c; ImTextCharFromUtf8(&prev_c, curr_p, obj->TextA.Data + obj->TextLen);
4007 unsigned int curr_c; ImTextCharFromUtf8(&curr_c, prev_p, obj->TextA.Data + obj->TextLen);
4008
4009 bool prev_white = ImCharIsBlankW(prev_c);
4010 bool prev_separ = ImCharIsSeparatorW(prev_c);
4011 bool curr_white = ImCharIsBlankW(curr_c);
4012 bool curr_separ = ImCharIsSeparatorW(curr_c);
4013 return ((prev_white) && !(curr_separ || curr_white)) || (curr_separ && !prev_separ);
4014 }
4015 static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(ImGuiInputTextState* obj, int idx)
4016 {
4017 idx = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx);
4018 while (idx >= 0 && !is_word_boundary_from_right(obj, idx))
4019 idx = IMSTB_TEXTEDIT_GETPREVCHARINDEX(obj, idx);
4020 return idx < 0 ? 0 : idx;
4021 }
4022 static int STB_TEXTEDIT_MOVEWORDRIGHT_MAC(ImGuiInputTextState* obj, int idx)
4023 {
4024 int len = obj->TextLen;
4025 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4026 while (idx < len && !is_word_boundary_from_left(obj, idx))
4027 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4028 return idx > len ? len : idx;
4029 }
4030 static int STB_TEXTEDIT_MOVEWORDRIGHT_WIN(ImGuiInputTextState* obj, int idx)
4031 {
4032 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4033 int len = obj->TextLen;
4034 while (idx < len && !is_word_boundary_from_right(obj, idx))
4035 idx = IMSTB_TEXTEDIT_GETNEXTCHARINDEX(obj, idx);
4036 return idx > len ? len : idx;
4037 }
4038 static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(ImGuiInputTextState* obj, int idx) { ImGuiContext& g = *obj->Ctx; if (g.IO.ConfigMacOSXBehaviors) return STB_TEXTEDIT_MOVEWORDRIGHT_MAC(obj, idx); else return STB_TEXTEDIT_MOVEWORDRIGHT_WIN(obj, idx); }
4039 #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
4040 #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
4041
4042 static void STB_TEXTEDIT_DELETECHARS(ImGuiInputTextState* obj, int pos, int n)
4043 {
4044 char* dst = obj->TextA.Data + pos;
4045
4046 obj->Edited = true;
4047 obj->TextLen -= n;
4048
4049 // Offset remaining text (FIXME-OPT: Use memmove)
4050 const char* src = obj->TextA.Data + pos + n;
4051 while (char c = *src++)
4052 *dst++ = c;
4053 *dst = '\0';
4054 }
4055
4056 static bool STB_TEXTEDIT_INSERTCHARS(ImGuiInputTextState* obj, int pos, const char* new_text, int new_text_len)
4057 {
4058 const bool is_resizable = (obj->Flags & ImGuiInputTextFlags_CallbackResize) != 0;
4059 const int text_len = obj->TextLen;
4060 IM_ASSERT(pos <= text_len);
4061
4062 if (!is_resizable && (new_text_len + obj->TextLen + 1 > obj->BufCapacity))
4063 return false;
4064
4065 // Grow internal buffer if needed
4066 if (new_text_len + text_len + 1 > obj->TextA.Size)
4067 {
4068 if (!is_resizable)
4069 return false;
4070 obj->TextA.resize(text_len + ImClamp(new_text_len, 32, ImMax(256, new_text_len)) + 1);
4071 }
4072
4073 char* text = obj->TextA.Data;
4074 if (pos != text_len)
4075 memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos));
4076 memcpy(text + pos, new_text, (size_t)new_text_len);
4077
4078 obj->Edited = true;
4079 obj->TextLen += new_text_len;
4080 obj->TextA[obj->TextLen] = '\0';
4081
4082 return true;
4083 }
4084
4085 // We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols)
4086 #define STB_TEXTEDIT_K_LEFT 0x200000 // keyboard input to move cursor left
4087 #define STB_TEXTEDIT_K_RIGHT 0x200001 // keyboard input to move cursor right
4088 #define STB_TEXTEDIT_K_UP 0x200002 // keyboard input to move cursor up
4089 #define STB_TEXTEDIT_K_DOWN 0x200003 // keyboard input to move cursor down
4090 #define STB_TEXTEDIT_K_LINESTART 0x200004 // keyboard input to move cursor to start of line
4091 #define STB_TEXTEDIT_K_LINEEND 0x200005 // keyboard input to move cursor to end of line
4092 #define STB_TEXTEDIT_K_TEXTSTART 0x200006 // keyboard input to move cursor to start of text
4093 #define STB_TEXTEDIT_K_TEXTEND 0x200007 // keyboard input to move cursor to end of text
4094 #define STB_TEXTEDIT_K_DELETE 0x200008 // keyboard input to delete selection or character under cursor
4095 #define STB_TEXTEDIT_K_BACKSPACE 0x200009 // keyboard input to delete selection or character left of cursor
4096 #define STB_TEXTEDIT_K_UNDO 0x20000A // keyboard input to perform undo
4097 #define STB_TEXTEDIT_K_REDO 0x20000B // keyboard input to perform redo
4098 #define STB_TEXTEDIT_K_WORDLEFT 0x20000C // keyboard input to move cursor left one word
4099 #define STB_TEXTEDIT_K_WORDRIGHT 0x20000D // keyboard input to move cursor right one word
4100 #define STB_TEXTEDIT_K_PGUP 0x20000E // keyboard input to move cursor up a page
4101 #define STB_TEXTEDIT_K_PGDOWN 0x20000F // keyboard input to move cursor down a page
4102 #define STB_TEXTEDIT_K_SHIFT 0x400000
4103
4104 #define IMSTB_TEXTEDIT_IMPLEMENTATION
4105 #define IMSTB_TEXTEDIT_memmove memmove
4106 #include "imstb_textedit.h"
4107
4108 // stb_textedit internally allows for a single undo record to do addition and deletion, but somehow, calling
4109 // the stb_textedit_paste() function creates two separate records, so we perform it manually. (FIXME: Report to nothings/stb?)
4110 static void stb_textedit_replace(ImGuiInputTextState* str, STB_TexteditState* state, const IMSTB_TEXTEDIT_CHARTYPE* text, int text_len)
4111 {
4112 stb_text_makeundo_replace(str, state, 0, str->TextLen, text_len);
4113 ImStb::STB_TEXTEDIT_DELETECHARS(str, 0, str->TextLen);
4114 state->cursor = state->select_start = state->select_end = 0;
4115 if (text_len <= 0)
4116 return;
4117 if (ImStb::STB_TEXTEDIT_INSERTCHARS(str, 0, text, text_len))
4118 {
4119 state->cursor = state->select_start = state->select_end = text_len;
4120 state->has_preferred_x = 0;
4121 return;
4122 }
4123 IM_ASSERT(0); // Failed to insert character, normally shouldn't happen because of how we currently use stb_textedit_replace()
4124 }
4125
4126 } // namespace ImStb
4127
4128 // We added an extra indirection where 'Stb' is heap-allocated, in order facilitate the work of bindings generators.
4129 ImGuiInputTextState::ImGuiInputTextState()
4130 {
4131 memset(this, 0, sizeof(*this));
4132 Stb = IM_NEW(ImStbTexteditState);
4133 memset(Stb, 0, sizeof(*Stb));
4134 }
4135
4136 ImGuiInputTextState::~ImGuiInputTextState()
4137 {
4138 IM_DELETE(Stb);
4139 }
4140
4141 void ImGuiInputTextState::OnKeyPressed(int key)
4142 {
4143 stb_textedit_key(this, Stb, key);
4144 CursorFollow = true;
4145 CursorAnimReset();
4146 }
4147
4148 void ImGuiInputTextState::OnCharPressed(unsigned int c)
4149 {
4150 // Convert the key to a UTF8 byte sequence.
4151 // The changes we had to make to stb_textedit_key made it very much UTF-8 specific which is not too great.
4152 char utf8[5];
4153 ImTextCharToUtf8(utf8, c);
4154 stb_textedit_text(this, Stb, utf8, (int)strlen(utf8));
4155 CursorFollow = true;
4156 CursorAnimReset();
4157 }
4158
4159 // Those functions are not inlined in imgui_internal.h, allowing us to hide ImStbTexteditState from that header.
4160 void ImGuiInputTextState::CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking
4161 void ImGuiInputTextState::CursorClamp() { Stb->cursor = ImMin(Stb->cursor, TextLen); Stb->select_start = ImMin(Stb->select_start, TextLen); Stb->select_end = ImMin(Stb->select_end, TextLen); }
4162 bool ImGuiInputTextState::HasSelection() const { return Stb->select_start != Stb->select_end; }
4163 void ImGuiInputTextState::ClearSelection() { Stb->select_start = Stb->select_end = Stb->cursor; }
4164 int ImGuiInputTextState::GetCursorPos() const { return Stb->cursor; }
4165 int ImGuiInputTextState::GetSelectionStart() const { return Stb->select_start; }
4166 int ImGuiInputTextState::GetSelectionEnd() const { return Stb->select_end; }
4167 void ImGuiInputTextState::SelectAll() { Stb->select_start = 0; Stb->cursor = Stb->select_end = TextLen; Stb->has_preferred_x = 0; }
4168 void ImGuiInputTextState::ReloadUserBufAndSelectAll() { ReloadUserBuf = true; ReloadSelectionStart = 0; ReloadSelectionEnd = INT_MAX; }
4169 void ImGuiInputTextState::ReloadUserBufAndKeepSelection() { ReloadUserBuf = true; ReloadSelectionStart = Stb->select_start; ReloadSelectionEnd = Stb->select_end; }
4170 void ImGuiInputTextState::ReloadUserBufAndMoveToEnd() { ReloadUserBuf = true; ReloadSelectionStart = ReloadSelectionEnd = INT_MAX; }
4171
4172 ImGuiInputTextCallbackData::ImGuiInputTextCallbackData()
4173 {
4174 memset(this, 0, sizeof(*this));
4175 }
4176
4177 // Public API to manipulate UTF-8 text
4178 // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
4179 // FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
4180 void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count)
4181 {
4182 IM_ASSERT(pos + bytes_count <= BufTextLen);
4183 char* dst = Buf + pos;
4184 const char* src = Buf + pos + bytes_count;
4185 while (char c = *src++)
4186 *dst++ = c;
4187 *dst = '\0';
4188
4189 if (CursorPos >= pos + bytes_count)
4190 CursorPos -= bytes_count;
4191 else if (CursorPos >= pos)
4192 CursorPos = pos;
4193 SelectionStart = SelectionEnd = CursorPos;
4194 BufDirty = true;
4195 BufTextLen -= bytes_count;
4196 }
4197
4198 void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
4199 {
4200 // Accept null ranges
4201 if (new_text == new_text_end)
4202 return;
4203
4204 // Grow internal buffer if needed
4205 const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0;
4206 const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
4207 if (new_text_len + BufTextLen >= BufSize)
4208 {
4209 if (!is_resizable)
4210 return;
4211
4212 // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the mildly similar code (until we remove the U16 buffer altogether!)
4213 ImGuiContext& g = *Ctx;
4214 ImGuiInputTextState* edit_state = &g.InputTextState;
4215 IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID);
4216 IM_ASSERT(Buf == edit_state->TextA.Data);
4217 int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1;
4218 edit_state->TextA.resize(new_buf_size + 1);
4219 Buf = edit_state->TextA.Data;
4220 BufSize = edit_state->BufCapacity = new_buf_size;
4221 }
4222
4223 if (BufTextLen != pos)
4224 memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
4225 memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
4226 Buf[BufTextLen + new_text_len] = '\0';
4227
4228 if (CursorPos >= pos)
4229 CursorPos += new_text_len;
4230 SelectionStart = SelectionEnd = CursorPos;
4231 BufDirty = true;
4232 BufTextLen += new_text_len;
4233 }
4234
4235 // Return false to discard a character.
4236 static bool InputTextFilterCharacter(ImGuiContext* ctx, unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data, bool input_source_is_clipboard)
4237 {
4238 unsigned int c = *p_char;
4239
4240 // Filter non-printable (NB: isprint is unreliable! see #2467)
4241 bool apply_named_filters = true;
4242 if (c < 0x20)
4243 {
4244 bool pass = false;
4245 pass |= (c == '\n') && (flags & ImGuiInputTextFlags_Multiline) != 0; // Note that an Enter KEY will emit \r and be ignored (we poll for KEY in InputText() code)
4246 pass |= (c == '\t') && (flags & ImGuiInputTextFlags_AllowTabInput) != 0;
4247 if (!pass)
4248 return false;
4249 apply_named_filters = false; // Override named filters below so newline and tabs can still be inserted.
4250 }
4251
4252 if (input_source_is_clipboard == false)
4253 {
4254 // We ignore Ascii representation of delete (emitted from Backspace on OSX, see #2578, #2817)
4255 if (c == 127)
4256 return false;
4257
4258 // Filter private Unicode range. GLFW on OSX seems to send private characters for special keys like arrow keys (FIXME)
4259 if (c >= 0xE000 && c <= 0xF8FF)
4260 return false;
4261 }
4262
4263 // Filter Unicode ranges we are not handling in this build
4264 if (c > IM_UNICODE_CODEPOINT_MAX)
4265 return false;
4266
4267 // Generic named filters
4268 if (apply_named_filters && (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint)))
4269 {
4270 // The libc allows overriding locale, with e.g. 'setlocale(LC_NUMERIC, "de_DE.UTF-8");' which affect the output/input of printf/scanf to use e.g. ',' instead of '.'.
4271 // The standard mandate that programs starts in the "C" locale where the decimal point is '.'.
4272 // We don't really intend to provide widespread support for it, but out of empathy for people stuck with using odd API, we support the bare minimum aka overriding the decimal point.
4273 // Change the default decimal_point with:
4274 // ImGui::GetPlatformIO()->Platform_LocaleDecimalPoint = *localeconv()->decimal_point;
4275 // Users of non-default decimal point (in particular ',') may be affected by word-selection logic (is_word_boundary_from_right/is_word_boundary_from_left) functions.
4276 ImGuiContext& g = *ctx;
4277 const unsigned c_decimal_point = (unsigned int)g.PlatformIO.Platform_LocaleDecimalPoint;
4278 if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | (ImGuiInputTextFlags)ImGuiInputTextFlags_LocalizeDecimalPoint))
4279 if (c == '.' || c == ',')
4280 c = c_decimal_point;
4281
4282 // Full-width -> half-width conversion for numeric fields (https://en.wikipedia.org/wiki/Halfwidth_and_Fullwidth_Forms_(Unicode_block)
4283 // While this is mostly convenient, this has the side-effect for uninformed users accidentally inputting full-width characters that they may
4284 // scratch their head as to why it works in numerical fields vs in generic text fields it would require support in the font.
4285 if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsScientific | ImGuiInputTextFlags_CharsHexadecimal))
4286 if (c >= 0xFF01 && c <= 0xFF5E)
4287 c = c - 0xFF01 + 0x21;
4288
4289 // Allow 0-9 . - + * /
4290 if (flags & ImGuiInputTextFlags_CharsDecimal)
4291 if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
4292 return false;
4293
4294 // Allow 0-9 . - + * / e E
4295 if (flags & ImGuiInputTextFlags_CharsScientific)
4296 if (!(c >= '0' && c <= '9') && (c != c_decimal_point) && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E'))
4297 return false;
4298
4299 // Allow 0-9 a-F A-F
4300 if (flags & ImGuiInputTextFlags_CharsHexadecimal)
4301 if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
4302 return false;
4303
4304 // Turn a-z into A-Z
4305 if (flags & ImGuiInputTextFlags_CharsUppercase)
4306 if (c >= 'a' && c <= 'z')
4307 c += (unsigned int)('A' - 'a');
4308
4309 if (flags & ImGuiInputTextFlags_CharsNoBlank)
4310 if (ImCharIsBlankW(c))
4311 return false;
4312
4313 *p_char = c;
4314 }
4315
4316 // Custom callback filter
4317 if (flags & ImGuiInputTextFlags_CallbackCharFilter)
4318 {
4319 ImGuiContext& g = *GImGui;
4320 ImGuiInputTextCallbackData callback_data;
4321 callback_data.Ctx = &g;
4322 callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
4323 callback_data.EventChar = (ImWchar)c;
4324 callback_data.Flags = flags;
4325 callback_data.UserData = user_data;
4326 if (callback(&callback_data) != 0)
4327 return false;
4328 *p_char = callback_data.EventChar;
4329 if (!callback_data.EventChar)
4330 return false;
4331 }
4332
4333 return true;
4334 }
4335
4336 // Find the shortest single replacement we can make to get the new text from the old text.
4337 // Important: needs to be run before TextW is rewritten with the new characters because calling STB_TEXTEDIT_GETCHAR() at the end.
4338 // FIXME: Ideally we should transition toward (1) making InsertChars()/DeleteChars() update undo-stack (2) discourage (and keep reconcile) or obsolete (and remove reconcile) accessing buffer directly.
4339 static void InputTextReconcileUndoStateAfterUserCallback(ImGuiInputTextState* state, const char* new_buf_a, int new_length_a)
4340 {
4341 const char* old_buf = state->CallbackTextBackup.Data;
4342 const int old_length = state->CallbackTextBackup.Size - 1;
4343
4344 const int shorter_length = ImMin(old_length, new_length_a);
4345 int first_diff;
4346 for (first_diff = 0; first_diff < shorter_length; first_diff++)
4347 if (old_buf[first_diff] != new_buf_a[first_diff])
4348 break;
4349 if (first_diff == old_length && first_diff == new_length_a)
4350 return;
4351
4352 int old_last_diff = old_length - 1;
4353 int new_last_diff = new_length_a - 1;
4354 for (; old_last_diff >= first_diff && new_last_diff >= first_diff; old_last_diff--, new_last_diff--)
4355 if (old_buf[old_last_diff] != new_buf_a[new_last_diff])
4356 break;
4357
4358 const int insert_len = new_last_diff - first_diff + 1;
4359 const int delete_len = old_last_diff - first_diff + 1;
4360 if (insert_len > 0 || delete_len > 0)
4361 if (IMSTB_TEXTEDIT_CHARTYPE* p = stb_text_createundo(&state->Stb->undostate, first_diff, delete_len, insert_len))
4362 for (int i = 0; i < delete_len; i++)
4363 p[i] = old_buf[first_diff + i];
4364 }
4365
4366 // As InputText() retain textual data and we currently provide a path for user to not retain it (via local variables)
4367 // we need some form of hook to reapply data back to user buffer on deactivation frame. (#4714)
4368 // It would be more desirable that we discourage users from taking advantage of the "user not retaining data" trick,
4369 // but that more likely be attractive when we do have _NoLiveEdit flag available.
4370 void ImGui::InputTextDeactivateHook(ImGuiID id)
4371 {
4372 ImGuiContext& g = *GImGui;
4373 ImGuiInputTextState* state = &g.InputTextState;
4374 if (id == 0 || state->ID != id)
4375 return;
4376 g.InputTextDeactivatedState.ID = state->ID;
4377 if (state->Flags & ImGuiInputTextFlags_ReadOnly)
4378 {
4379 g.InputTextDeactivatedState.TextA.resize(0); // In theory this data won't be used, but clear to be neat.
4380 }
4381 else
4382 {
4383 IM_ASSERT(state->TextA.Data != 0);
4384 g.InputTextDeactivatedState.TextA.resize(state->TextLen + 1);
4385 memcpy(g.InputTextDeactivatedState.TextA.Data, state->TextA.Data, state->TextLen + 1);
4386 }
4387 }
4388
4389 // Edit a string of text
4390 // - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!".
4391 // This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match
4392 // Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator.
4393 // - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect.
4394 // - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h
4395 // (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are
4396 // doing UTF8 > U16 > UTF8 conversions on the go to easily interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188)
4397 bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data)
4398 {
4399 ImGuiWindow* window = GetCurrentWindow();
4400 if (window->SkipItems)
4401 return false;
4402
4403 IM_ASSERT(buf != NULL && buf_size >= 0);
4404 IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
4405 IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
4406 IM_ASSERT(!((flags & ImGuiInputTextFlags_ElideLeft) && (flags & ImGuiInputTextFlags_Multiline))); // Multiline will not work with left-trimming
4407
4408 ImGuiContext& g = *GImGui;
4409 ImGuiIO& io = g.IO;
4410 const ImGuiStyle& style = g.Style;
4411
4412 const bool RENDER_SELECTION_WHEN_INACTIVE = false;
4413 const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
4414
4415 if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope (including the scrollbar)
4416 BeginGroup();
4417 const ImGuiID id = window->GetID(label);
4418 const ImVec2 label_size = CalcTextSize(label, NULL, true);
4419 const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? g.FontSize * 8.0f : label_size.y) + style.FramePadding.y * 2.0f); // Arbitrary default of 8 lines high for multi-line
4420 const ImVec2 total_size = ImVec2(frame_size.x + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), frame_size.y);
4421
4422 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
4423 const ImRect total_bb(frame_bb.Min, frame_bb.Min + total_size);
4424
4425 ImGuiWindow* draw_window = window;
4426 ImVec2 inner_size = frame_size;
4427 ImGuiLastItemData item_data_backup;
4428 if (is_multiline)
4429 {
4430 ImVec2 backup_pos = window->DC.CursorPos;
4431 ItemSize(total_bb, style.FramePadding.y);
4432 if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable))
4433 {
4434 EndGroup();
4435 return false;
4436 }
4437 item_data_backup = g.LastItemData;
4438 window->DC.CursorPos = backup_pos;
4439
4440 // Prevent NavActivation from Tabbing when our widget accepts Tab inputs: this allows cycling through widgets without stopping.
4441 if (g.NavActivateId == id && (g.NavActivateFlags & ImGuiActivateFlags_FromTabbing) && (flags & ImGuiInputTextFlags_AllowTabInput))
4442 g.NavActivateId = 0;
4443
4444 // Prevent NavActivate reactivating in BeginChild() when we are already active.
4445 const ImGuiID backup_activate_id = g.NavActivateId;
4446 if (g.ActiveId == id) // Prevent reactivation
4447 g.NavActivateId = 0;
4448
4449 // We reproduce the contents of BeginChildFrame() in order to provide 'label' so our window internal data are easier to read/debug.
4450 PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
4451 PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
4452 PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
4453 PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Ensure no clip rect so mouse hover can reach FramePadding edges
4454 bool child_visible = BeginChildEx(label, id, frame_bb.GetSize(), ImGuiChildFlags_Borders, ImGuiWindowFlags_NoMove);
4455 g.NavActivateId = backup_activate_id;
4456 PopStyleVar(3);
4457 PopStyleColor();
4458 if (!child_visible)
4459 {
4460 EndChild();
4461 EndGroup();
4462 return false;
4463 }
4464 draw_window = g.CurrentWindow; // Child window
4465 draw_window->DC.NavLayersActiveMaskNext |= (1 << draw_window->DC.NavLayerCurrent); // This is to ensure that EndChild() will display a navigation highlight so we can "enter" into it.
4466 draw_window->DC.CursorPos += style.FramePadding;
4467 inner_size.x -= draw_window->ScrollbarSizes.x;
4468 }
4469 else
4470 {
4471 // Support for internal ImGuiInputTextFlags_MergedItem flag, which could be redesigned as an ItemFlags if needed (with test performed in ItemAdd)
4472 ItemSize(total_bb, style.FramePadding.y);
4473 if (!(flags & ImGuiInputTextFlags_MergedItem))
4474 if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_Inputable))
4475 return false;
4476 }
4477
4478 // Ensure mouse cursor is set even after switching to keyboard/gamepad mode. May generalize further? (#6417)
4479 bool hovered = ItemHoverable(frame_bb, id, g.LastItemData.ItemFlags | ImGuiItemFlags_NoNavDisableMouseHover);
4480 if (hovered)
4481 SetMouseCursor(ImGuiMouseCursor_TextInput);
4482 if (hovered && g.NavHighlightItemUnderNav)
4483 hovered = false;
4484
4485 // We are only allowed to access the state if we are already the active widget.
4486 ImGuiInputTextState* state = GetInputTextState(id);
4487
4488 if (g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly)
4489 flags |= ImGuiInputTextFlags_ReadOnly;
4490 const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0;
4491 const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
4492 const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0;
4493 const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0;
4494 if (is_resizable)
4495 IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag!
4496
4497 const bool input_requested_by_nav = (g.ActiveId != id) && ((g.NavActivateId == id) && ((g.NavActivateFlags & ImGuiActivateFlags_PreferInput) || (g.NavInputSource == ImGuiInputSource_Keyboard)));
4498
4499 const bool user_clicked = hovered && io.MouseClicked[0];
4500 const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetWindowScrollbarID(draw_window, ImGuiAxis_Y);
4501 const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetWindowScrollbarID(draw_window, ImGuiAxis_Y);
4502 bool clear_active_id = false;
4503 bool select_all = false;
4504
4505 float scroll_y = is_multiline ? draw_window->Scroll.y : FLT_MAX;
4506
4507 const bool init_reload_from_user_buf = (state != NULL && state->ReloadUserBuf);
4508 const bool init_changed_specs = (state != NULL && state->Stb->single_line != !is_multiline); // state != NULL means its our state.
4509 const bool init_make_active = (user_clicked || user_scroll_finish || input_requested_by_nav);
4510 const bool init_state = (init_make_active || user_scroll_active);
4511 if ((init_state && g.ActiveId != id) || init_changed_specs || init_reload_from_user_buf)
4512 {
4513 // Access state even if we don't own it yet.
4514 state = &g.InputTextState;
4515 state->CursorAnimReset();
4516 state->ReloadUserBuf = false;
4517
4518 // Backup state of deactivating item so they'll have a chance to do a write to output buffer on the same frame they report IsItemDeactivatedAfterEdit (#4714)
4519 InputTextDeactivateHook(state->ID);
4520
4521 // From the moment we focused we are normally ignoring the content of 'buf' (unless we are in read-only mode)
4522 const int buf_len = (int)strlen(buf);
4523 if (!init_reload_from_user_buf)
4524 {
4525 // Take a copy of the initial buffer value.
4526 state->TextToRevertTo.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string.
4527 memcpy(state->TextToRevertTo.Data, buf, buf_len + 1);
4528 }
4529
4530 // Preserve cursor position and undo/redo stack if we come back to same widget
4531 // FIXME: Since we reworked this on 2022/06, may want to differentiate recycle_cursor vs recycle_undostate?
4532 bool recycle_state = (state->ID == id && !init_changed_specs && !init_reload_from_user_buf);
4533 if (recycle_state && (state->TextLen != buf_len || (strncmp(state->TextA.Data, buf, buf_len) != 0)))
4534 recycle_state = false;
4535
4536 // Start edition
4537 state->ID = id;
4538 state->TextA.resize(buf_size + 1); // we use +1 to make sure that .Data is always pointing to at least an empty string.
4539 state->TextLen = (int)strlen(buf);
4540 memcpy(state->TextA.Data, buf, state->TextLen + 1);
4541
4542 // Find initial scroll position for right alignment
4543 state->Scroll = ImVec2(0.0f, 0.0f);
4544 if (flags & ImGuiInputTextFlags_ElideLeft)
4545 state->Scroll.x += ImMax(0.0f, CalcTextSize(buf).x - frame_size.x + style.FramePadding.x * 2.0f);
4546
4547 if (recycle_state)
4548 {
4549 // Recycle existing cursor/selection/undo stack but clamp position
4550 // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
4551 state->CursorClamp();
4552 }
4553 else
4554 {
4555 stb_textedit_initialize_state(state->Stb, !is_multiline);
4556 }
4557
4558 if (init_reload_from_user_buf)
4559 {
4560 state->Stb->select_start = state->ReloadSelectionStart;
4561 state->Stb->cursor = state->Stb->select_end = state->ReloadSelectionEnd;
4562 state->CursorClamp();
4563 }
4564 else if (!is_multiline)
4565 {
4566 if (flags & ImGuiInputTextFlags_AutoSelectAll)
4567 select_all = true;
4568 if (input_requested_by_nav && (!recycle_state || !(g.NavActivateFlags & ImGuiActivateFlags_TryToPreserveState)))
4569 select_all = true;
4570 if (user_clicked && io.KeyCtrl)
4571 select_all = true;
4572 }
4573
4574 if (flags & ImGuiInputTextFlags_AlwaysOverwrite)
4575 state->Stb->insert_mode = 1; // stb field name is indeed incorrect (see #2863)
4576 }
4577
4578 const bool is_osx = io.ConfigMacOSXBehaviors;
4579 if (g.ActiveId != id && init_make_active)
4580 {
4581 IM_ASSERT(state && state->ID == id);
4582 SetActiveID(id, window);
4583 SetFocusID(id, window);
4584 FocusWindow(window);
4585 }
4586 if (g.ActiveId == id)
4587 {
4588 // Declare some inputs, the other are registered and polled via Shortcut() routing system.
4589 // FIXME: The reason we don't use Shortcut() is we would need a routing flag to specify multiple mods, or to all mods combinaison into individual shortcuts.
4590 const ImGuiKey always_owned_keys[] = { ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_Enter, ImGuiKey_KeypadEnter, ImGuiKey_Delete, ImGuiKey_Backspace, ImGuiKey_Home, ImGuiKey_End };
4591 for (ImGuiKey key : always_owned_keys)
4592 SetKeyOwner(key, id);
4593 if (user_clicked)
4594 SetKeyOwner(ImGuiKey_MouseLeft, id);
4595 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
4596 if (is_multiline || (flags & ImGuiInputTextFlags_CallbackHistory))
4597 {
4598 g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
4599 SetKeyOwner(ImGuiKey_UpArrow, id);
4600 SetKeyOwner(ImGuiKey_DownArrow, id);
4601 }
4602 if (is_multiline)
4603 {
4604 SetKeyOwner(ImGuiKey_PageUp, id);
4605 SetKeyOwner(ImGuiKey_PageDown, id);
4606 }
4607 // FIXME: May be a problem to always steal Alt on OSX, would ideally still allow an uninterrupted Alt down-up to toggle menu
4608 if (is_osx)
4609 SetKeyOwner(ImGuiMod_Alt, id);
4610
4611 // Expose scroll in a manner that is agnostic to us using a child window
4612 if (is_multiline && state != NULL)
4613 state->Scroll.y = draw_window->Scroll.y;
4614 }
4615
4616 // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function)
4617 if (g.ActiveId == id && state == NULL)
4618 ClearActiveID();
4619
4620 // Release focus when we click outside
4621 if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560
4622 clear_active_id = true;
4623
4624 // Lock the decision of whether we are going to take the path displaying the cursor or selection
4625 bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active);
4626 bool render_selection = state && (state->HasSelection() || select_all) && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
4627 bool value_changed = false;
4628 bool validated = false;
4629
4630 // Select the buffer to render.
4631 const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state;
4632 const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0);
4633
4634 // Password pushes a temporary font with only a fallback glyph
4635 if (is_password && !is_displaying_hint)
4636 {
4637 const ImFontGlyph* glyph = g.Font->FindGlyph('*');
4638 ImFont* password_font = &g.InputTextPasswordFont;
4639 password_font->FontSize = g.Font->FontSize;
4640 password_font->Scale = g.Font->Scale;
4641 password_font->Ascent = g.Font->Ascent;
4642 password_font->Descent = g.Font->Descent;
4643 password_font->ContainerAtlas = g.Font->ContainerAtlas;
4644 password_font->FallbackGlyph = glyph;
4645 password_font->FallbackAdvanceX = glyph->AdvanceX;
4646 IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty());
4647 PushFont(password_font);
4648 }
4649
4650 // Process mouse inputs and character inputs
4651 if (g.ActiveId == id)
4652 {
4653 IM_ASSERT(state != NULL);
4654 state->Edited = false;
4655 state->BufCapacity = buf_size;
4656 state->Flags = flags;
4657
4658 // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
4659 // Down the line we should have a cleaner library-wide concept of Selected vs Active.
4660 g.ActiveIdAllowOverlap = !io.MouseDown[0];
4661
4662 // Edit in progress
4663 const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->Scroll.x;
4664 const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y) : (g.FontSize * 0.5f));
4665
4666 if (select_all)
4667 {
4668 state->SelectAll();
4669 state->SelectedAllMouseLock = true;
4670 }
4671 else if (hovered && io.MouseClickedCount[0] >= 2 && !io.KeyShift)
4672 {
4673 stb_textedit_click(state, state->Stb, mouse_x, mouse_y);
4674 const int multiclick_count = (io.MouseClickedCount[0] - 2);
4675 if ((multiclick_count % 2) == 0)
4676 {
4677 // Double-click: Select word
4678 // We always use the "Mac" word advance for double-click select vs CTRL+Right which use the platform dependent variant:
4679 // FIXME: There are likely many ways to improve this behavior, but there's no "right" behavior (depends on use-case, software, OS)
4680 const bool is_bol = (state->Stb->cursor == 0) || ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor - 1) == '\n';
4681 if (STB_TEXT_HAS_SELECTION(state->Stb) || !is_bol)
4682 state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
4683 //state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
4684 if (!STB_TEXT_HAS_SELECTION(state->Stb))
4685 ImStb::stb_textedit_prep_selection_at_cursor(state->Stb);
4686 state->Stb->cursor = ImStb::STB_TEXTEDIT_MOVEWORDRIGHT_MAC(state, state->Stb->cursor);
4687 state->Stb->select_end = state->Stb->cursor;
4688 ImStb::stb_textedit_clamp(state, state->Stb);
4689 }
4690 else
4691 {
4692 // Triple-click: Select line
4693 const bool is_eol = ImStb::STB_TEXTEDIT_GETCHAR(state, state->Stb->cursor) == '\n';
4694 state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART);
4695 state->OnKeyPressed(STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT);
4696 state->OnKeyPressed(STB_TEXTEDIT_K_RIGHT | STB_TEXTEDIT_K_SHIFT);
4697 if (!is_eol && is_multiline)
4698 {
4699 ImSwap(state->Stb->select_start, state->Stb->select_end);
4700 state->Stb->cursor = state->Stb->select_end;
4701 }
4702 state->CursorFollow = false;
4703 }
4704 state->CursorAnimReset();
4705 }
4706 else if (io.MouseClicked[0] && !state->SelectedAllMouseLock)
4707 {
4708 if (hovered)
4709 {
4710 if (io.KeyShift)
4711 stb_textedit_drag(state, state->Stb, mouse_x, mouse_y);
4712 else
4713 stb_textedit_click(state, state->Stb, mouse_x, mouse_y);
4714 state->CursorAnimReset();
4715 }
4716 }
4717 else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
4718 {
4719 stb_textedit_drag(state, state->Stb, mouse_x, mouse_y);
4720 state->CursorAnimReset();
4721 state->CursorFollow = true;
4722 }
4723 if (state->SelectedAllMouseLock && !io.MouseDown[0])
4724 state->SelectedAllMouseLock = false;
4725
4726 // We expect backends to emit a Tab key but some also emit a Tab character which we ignore (#2467, #1336)
4727 // (For Tab and Enter: Win32/SFML/Allegro are sending both keys and chars, GLFW and SDL are only sending keys. For Space they all send all threes)
4728 if ((flags & ImGuiInputTextFlags_AllowTabInput) && !is_readonly)
4729 {
4730 if (Shortcut(ImGuiKey_Tab, ImGuiInputFlags_Repeat, id))
4731 {
4732 unsigned int c = '\t'; // Insert TAB
4733 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
4734 state->OnCharPressed(c);
4735 }
4736 // FIXME: Implement Shift+Tab
4737 /*
4738 if (Shortcut(ImGuiKey_Tab | ImGuiMod_Shift, ImGuiInputFlags_Repeat, id))
4739 {
4740 }
4741 */
4742 }
4743
4744 // Process regular text input (before we check for Return because using some IME will effectively send a Return?)
4745 // We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters.
4746 const bool ignore_char_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeyCtrl);
4747 if (io.InputQueueCharacters.Size > 0)
4748 {
4749 if (!ignore_char_inputs && !is_readonly && !input_requested_by_nav)
4750 for (int n = 0; n < io.InputQueueCharacters.Size; n++)
4751 {
4752 // Insert character if they pass filtering
4753 unsigned int c = (unsigned int)io.InputQueueCharacters[n];
4754 if (c == '\t') // Skip Tab, see above.
4755 continue;
4756 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
4757 state->OnCharPressed(c);
4758 }
4759
4760 // Consume characters
4761 io.InputQueueCharacters.resize(0);
4762 }
4763 }
4764
4765 // Process other shortcuts/key-presses
4766 bool revert_edit = false;
4767 if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
4768 {
4769 IM_ASSERT(state != NULL);
4770
4771 const int row_count_per_page = ImMax((int)((inner_size.y - style.FramePadding.y) / g.FontSize), 1);
4772 state->Stb->row_count_per_page = row_count_per_page;
4773
4774 const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
4775 const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
4776 const bool is_startend_key_down = is_osx && io.KeyCtrl && !io.KeySuper && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
4777
4778 // Using Shortcut() with ImGuiInputFlags_RouteFocused (default policy) to allow routing operations for other code (e.g. calling window trying to use CTRL+A and CTRL+B: formet would be handled by InputText)
4779 // Otherwise we could simply assume that we own the keys as we are active.
4780 const ImGuiInputFlags f_repeat = ImGuiInputFlags_Repeat;
4781 const bool is_cut = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_X, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Delete, f_repeat, id)) && !is_readonly && !is_password && (!is_multiline || state->HasSelection());
4782 const bool is_copy = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_C, 0, id) || Shortcut(ImGuiMod_Ctrl | ImGuiKey_Insert, 0, id)) && !is_password && (!is_multiline || state->HasSelection());
4783 const bool is_paste = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_V, f_repeat, id) || Shortcut(ImGuiMod_Shift | ImGuiKey_Insert, f_repeat, id)) && !is_readonly;
4784 const bool is_undo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Z, f_repeat, id)) && !is_readonly && is_undoable;
4785 const bool is_redo = (Shortcut(ImGuiMod_Ctrl | ImGuiKey_Y, f_repeat, id) || (is_osx && Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift | ImGuiKey_Z, f_repeat, id))) && !is_readonly && is_undoable;
4786 const bool is_select_all = Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, 0, id);
4787
4788 // We allow validate/cancel with Nav source (gamepad) to makes it easier to undo an accidental NavInput press with no keyboard wired, but otherwise it isn't very useful.
4789 const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
4790 const bool is_enter_pressed = IsKeyPressed(ImGuiKey_Enter, true) || IsKeyPressed(ImGuiKey_KeypadEnter, true);
4791 const bool is_gamepad_validate = nav_gamepad_active && (IsKeyPressed(ImGuiKey_NavGamepadActivate, false) || IsKeyPressed(ImGuiKey_NavGamepadInput, false));
4792 const bool is_cancel = Shortcut(ImGuiKey_Escape, f_repeat, id) || (nav_gamepad_active && Shortcut(ImGuiKey_NavGamepadCancel, f_repeat, id));
4793
4794 // FIXME: Should use more Shortcut() and reduce IsKeyPressed()+SetKeyOwner(), but requires modifiers combination to be taken account of.
4795 // FIXME-OSX: Missing support for Alt(option)+Right/Left = go to end of line, or next line if already in end of line.
4796 if (IsKeyPressed(ImGuiKey_LeftArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }
4797 else if (IsKeyPressed(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }
4798 else if (IsKeyPressed(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); }
4799 else if (IsKeyPressed(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); }
4800 else if (IsKeyPressed(ImGuiKey_PageUp) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGUP | k_mask); scroll_y -= row_count_per_page * g.FontSize; }
4801 else if (IsKeyPressed(ImGuiKey_PageDown) && is_multiline) { state->OnKeyPressed(STB_TEXTEDIT_K_PGDOWN | k_mask); scroll_y += row_count_per_page * g.FontSize; }
4802 else if (IsKeyPressed(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
4803 else if (IsKeyPressed(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
4804 else if (IsKeyPressed(ImGuiKey_Delete) && !is_readonly && !is_cut)
4805 {
4806 if (!state->HasSelection())
4807 {
4808 // OSX doesn't seem to have Super+Delete to delete until end-of-line, so we don't emulate that (as opposed to Super+Backspace)
4809 if (is_wordmove_key_down)
4810 state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
4811 }
4812 state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask);
4813 }
4814 else if (IsKeyPressed(ImGuiKey_Backspace) && !is_readonly)
4815 {
4816 if (!state->HasSelection())
4817 {
4818 if (is_wordmove_key_down)
4819 state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT | STB_TEXTEDIT_K_SHIFT);
4820 else if (is_osx && io.KeyCtrl && !io.KeyAlt && !io.KeySuper)
4821 state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT);
4822 }
4823 state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
4824 }
4825 else if (is_enter_pressed || is_gamepad_validate)
4826 {
4827 // Determine if we turn Enter into a \n character
4828 bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
4829 if (!is_multiline || is_gamepad_validate || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
4830 {
4831 validated = true;
4832 if (io.ConfigInputTextEnterKeepActive && !is_multiline)
4833 state->SelectAll(); // No need to scroll
4834 else
4835 clear_active_id = true;
4836 }
4837 else if (!is_readonly)
4838 {
4839 unsigned int c = '\n'; // Insert new line
4840 if (InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data))
4841 state->OnCharPressed(c);
4842 }
4843 }
4844 else if (is_cancel)
4845 {
4846 if (flags & ImGuiInputTextFlags_EscapeClearsAll)
4847 {
4848 if (buf[0] != 0)
4849 {
4850 revert_edit = true;
4851 }
4852 else
4853 {
4854 render_cursor = render_selection = false;
4855 clear_active_id = true;
4856 }
4857 }
4858 else
4859 {
4860 clear_active_id = revert_edit = true;
4861 render_cursor = render_selection = false;
4862 }
4863 }
4864 else if (is_undo || is_redo)
4865 {
4866 state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO);
4867 state->ClearSelection();
4868 }
4869 else if (is_select_all)
4870 {
4871 state->SelectAll();
4872 state->CursorFollow = true;
4873 }
4874 else if (is_cut || is_copy)
4875 {
4876 // Cut, Copy
4877 if (g.PlatformIO.Platform_SetClipboardTextFn != NULL)
4878 {
4879 const int ib = state->HasSelection() ? ImMin(state->Stb->select_start, state->Stb->select_end) : 0;
4880 const int ie = state->HasSelection() ? ImMax(state->Stb->select_start, state->Stb->select_end) : state->TextLen;
4881
4882 char backup = state->TextA.Data[ie];
4883 state->TextA.Data[ie] = 0; // A bit of a hack since SetClipboardText only takes null terminated strings
4884 SetClipboardText(state->TextA.Data + ib);
4885 state->TextA.Data[ie] = backup;
4886 }
4887 if (is_cut)
4888 {
4889 if (!state->HasSelection())
4890 state->SelectAll();
4891 state->CursorFollow = true;
4892 stb_textedit_cut(state, state->Stb);
4893 }
4894 }
4895 else if (is_paste)
4896 {
4897 if (const char* clipboard = GetClipboardText())
4898 {
4899 // Filter pasted buffer
4900 const int clipboard_len = (int)strlen(clipboard);
4901 char* clipboard_filtered = (char*)IM_ALLOC(clipboard_len + 1);
4902 int clipboard_filtered_len = 0;
4903 for (const char* s = clipboard; *s != 0; )
4904 {
4905 unsigned int c;
4906 int len = ImTextCharFromUtf8(&c, s, NULL);
4907 s += len;
4908 if (!InputTextFilterCharacter(&g, &c, flags, callback, callback_user_data, true))
4909 continue;
4910 memcpy(clipboard_filtered + clipboard_filtered_len, s - len, len);
4911 clipboard_filtered_len += len;
4912 }
4913 clipboard_filtered[clipboard_filtered_len] = 0;
4914 if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
4915 {
4916 stb_textedit_paste(state, state->Stb, clipboard_filtered, clipboard_filtered_len);
4917 state->CursorFollow = true;
4918 }
4919 MemFree(clipboard_filtered);
4920 }
4921 }
4922
4923 // Update render selection flag after events have been handled, so selection highlight can be displayed during the same frame.
4924 render_selection |= state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor);
4925 }
4926
4927 // Process callbacks and apply result back to user's buffer.
4928 const char* apply_new_text = NULL;
4929 int apply_new_text_length = 0;
4930 if (g.ActiveId == id)
4931 {
4932 IM_ASSERT(state != NULL);
4933 if (revert_edit && !is_readonly)
4934 {
4935 if (flags & ImGuiInputTextFlags_EscapeClearsAll)
4936 {
4937 // Clear input
4938 IM_ASSERT(buf[0] != 0);
4939 apply_new_text = "";
4940 apply_new_text_length = 0;
4941 value_changed = true;
4942 IMSTB_TEXTEDIT_CHARTYPE empty_string;
4943 stb_textedit_replace(state, state->Stb, &empty_string, 0);
4944 }
4945 else if (strcmp(buf, state->TextToRevertTo.Data) != 0)
4946 {
4947 apply_new_text = state->TextToRevertTo.Data;
4948 apply_new_text_length = state->TextToRevertTo.Size - 1;
4949
4950 // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents.
4951 // Push records into the undo stack so we can CTRL+Z the revert operation itself
4952 value_changed = true;
4953 stb_textedit_replace(state, state->Stb, state->TextToRevertTo.Data, state->TextToRevertTo.Size - 1);
4954 }
4955 }
4956
4957 // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer
4958 // before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
4959 // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail.
4960 // This also allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage
4961 // (please note that if you use this property along ImGuiInputTextFlags_CallbackResize you can end up with your temporary string object
4962 // unnecessarily allocating once a frame, either store your string data, either if you don't then don't use ImGuiInputTextFlags_CallbackResize).
4963 const bool apply_edit_back_to_user_buffer = !revert_edit || (validated && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
4964 if (apply_edit_back_to_user_buffer)
4965 {
4966 // Apply new value immediately - copy modified buffer back
4967 // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
4968 // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
4969 // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
4970
4971 // User callback
4972 if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackEdit | ImGuiInputTextFlags_CallbackAlways)) != 0)
4973 {
4974 IM_ASSERT(callback != NULL);
4975
4976 // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
4977 ImGuiInputTextFlags event_flag = 0;
4978 ImGuiKey event_key = ImGuiKey_None;
4979 if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && Shortcut(ImGuiKey_Tab, 0, id))
4980 {
4981 event_flag = ImGuiInputTextFlags_CallbackCompletion;
4982 event_key = ImGuiKey_Tab;
4983 }
4984 else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_UpArrow))
4985 {
4986 event_flag = ImGuiInputTextFlags_CallbackHistory;
4987 event_key = ImGuiKey_UpArrow;
4988 }
4989 else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressed(ImGuiKey_DownArrow))
4990 {
4991 event_flag = ImGuiInputTextFlags_CallbackHistory;
4992 event_key = ImGuiKey_DownArrow;
4993 }
4994 else if ((flags & ImGuiInputTextFlags_CallbackEdit) && state->Edited)
4995 {
4996 event_flag = ImGuiInputTextFlags_CallbackEdit;
4997 }
4998 else if (flags & ImGuiInputTextFlags_CallbackAlways)
4999 {
5000 event_flag = ImGuiInputTextFlags_CallbackAlways;
5001 }
5002
5003 if (event_flag)
5004 {
5005 ImGuiInputTextCallbackData callback_data;
5006 callback_data.Ctx = &g;
5007 callback_data.EventFlag = event_flag;
5008 callback_data.Flags = flags;
5009 callback_data.UserData = callback_user_data;
5010
5011 // FIXME-OPT: Undo stack reconcile needs a backup of the data until we rework API, see #7925
5012 state->CallbackTextBackup.resize(state->TextLen + 1);
5013 memcpy(state->CallbackTextBackup.Data, state->TextA.Data, state->TextLen + 1);
5014
5015 char* callback_buf = is_readonly ? buf : state->TextA.Data;
5016 callback_data.EventKey = event_key;
5017 callback_data.Buf = callback_buf;
5018 callback_data.BufTextLen = state->TextLen;
5019 callback_data.BufSize = state->BufCapacity;
5020 callback_data.BufDirty = false;
5021
5022 const int utf8_cursor_pos = callback_data.CursorPos = state->Stb->cursor;
5023 const int utf8_selection_start = callback_data.SelectionStart = state->Stb->select_start;
5024 const int utf8_selection_end = callback_data.SelectionEnd = state->Stb->select_end;
5025
5026 // Call user code
5027 callback(&callback_data);
5028
5029 // Read back what user may have modified
5030 callback_buf = is_readonly ? buf : state->TextA.Data; // Pointer may have been invalidated by a resize callback
5031 IM_ASSERT(callback_data.Buf == callback_buf); // Invalid to modify those fields
5032 IM_ASSERT(callback_data.BufSize == state->BufCapacity);
5033 IM_ASSERT(callback_data.Flags == flags);
5034 const bool buf_dirty = callback_data.BufDirty;
5035 if (callback_data.CursorPos != utf8_cursor_pos || buf_dirty) { state->Stb->cursor = callback_data.CursorPos; state->CursorFollow = true; }
5036 if (callback_data.SelectionStart != utf8_selection_start || buf_dirty) { state->Stb->select_start = (callback_data.SelectionStart == callback_data.CursorPos) ? state->Stb->cursor : callback_data.SelectionStart; }
5037 if (callback_data.SelectionEnd != utf8_selection_end || buf_dirty) { state->Stb->select_end = (callback_data.SelectionEnd == callback_data.SelectionStart) ? state->Stb->select_start : callback_data.SelectionEnd; }
5038 if (buf_dirty)
5039 {
5040 // Callback may update buffer and thus set buf_dirty even in read-only mode.
5041 IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
5042 InputTextReconcileUndoStateAfterUserCallback(state, callback_data.Buf, callback_data.BufTextLen); // FIXME: Move the rest of this block inside function and rename to InputTextReconcileStateAfterUserCallback() ?
5043 state->TextLen = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
5044 state->CursorAnimReset();
5045 }
5046 }
5047 }
5048
5049 // Will copy result string if modified
5050 if (!is_readonly && strcmp(state->TextA.Data, buf) != 0)
5051 {
5052 apply_new_text = state->TextA.Data;
5053 apply_new_text_length = state->TextLen;
5054 value_changed = true;
5055 }
5056 }
5057 }
5058
5059 // Handle reapplying final data on deactivation (see InputTextDeactivateHook() for details)
5060 if (g.InputTextDeactivatedState.ID == id)
5061 {
5062 if (g.ActiveId != id && IsItemDeactivatedAfterEdit() && !is_readonly && strcmp(g.InputTextDeactivatedState.TextA.Data, buf) != 0)
5063 {
5064 apply_new_text = g.InputTextDeactivatedState.TextA.Data;
5065 apply_new_text_length = g.InputTextDeactivatedState.TextA.Size - 1;
5066 value_changed = true;
5067 //IMGUI_DEBUG_LOG("InputText(): apply Deactivated data for 0x%08X: \"%.*s\".\n", id, apply_new_text_length, apply_new_text);
5068 }
5069 g.InputTextDeactivatedState.ID = 0;
5070 }
5071
5072 // Copy result to user buffer. This can currently only happen when (g.ActiveId == id)
5073 if (apply_new_text != NULL)
5074 {
5075 //// We cannot test for 'backup_current_text_length != apply_new_text_length' here because we have no guarantee that the size
5076 //// of our owned buffer matches the size of the string object held by the user, and by design we allow InputText() to be used
5077 //// without any storage on user's side.
5078 IM_ASSERT(apply_new_text_length >= 0);
5079 if (is_resizable)
5080 {
5081 ImGuiInputTextCallbackData callback_data;
5082 callback_data.Ctx = &g;
5083 callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize;
5084 callback_data.Flags = flags;
5085 callback_data.Buf = buf;
5086 callback_data.BufTextLen = apply_new_text_length;
5087 callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1);
5088 callback_data.UserData = callback_user_data;
5089 callback(&callback_data);
5090 buf = callback_data.Buf;
5091 buf_size = callback_data.BufSize;
5092 apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1);
5093 IM_ASSERT(apply_new_text_length <= buf_size);
5094 }
5095 //IMGUI_DEBUG_PRINT("InputText(\"%s\"): apply_new_text length %d\n", label, apply_new_text_length);
5096
5097 // If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size.
5098 ImStrncpy(buf, apply_new_text, ImMin(apply_new_text_length + 1, buf_size));
5099 }
5100
5101 // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
5102 // Otherwise request text input ahead for next frame.
5103 if (g.ActiveId == id && clear_active_id)
5104 ClearActiveID();
5105 else if (g.ActiveId == id)
5106 g.WantTextInputNextFrame = 1;
5107
5108 // Render frame
5109 if (!is_multiline)
5110 {
5111 RenderNavCursor(frame_bb, id);
5112 RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
5113 }
5114
5115 const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + inner_size.x, frame_bb.Min.y + inner_size.y); // Not using frame_bb.Max because we have adjusted size
5116 ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
5117 ImVec2 text_size(0.0f, 0.0f);
5118
5119 // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line
5120 // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether.
5121 // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash.
5122 const int buf_display_max_length = 2 * 1024 * 1024;
5123 const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595
5124 const char* buf_display_end = NULL; // We have specialized paths below for setting the length
5125 if (is_displaying_hint)
5126 {
5127 buf_display = hint;
5128 buf_display_end = hint + strlen(hint);
5129 }
5130
5131 // Render text. We currently only render selection when the widget is active or while scrolling.
5132 // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive.
5133 if (render_cursor || render_selection)
5134 {
5135 IM_ASSERT(state != NULL);
5136 if (!is_displaying_hint)
5137 buf_display_end = buf_display + state->TextLen;
5138
5139 // Render text (with cursor and selection)
5140 // This is going to be messy. We need to:
5141 // - Display the text (this alone can be more easily clipped)
5142 // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
5143 // - Measure text height (for scrollbar)
5144 // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
5145 // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
5146 const char* text_begin = state->TextA.Data;
5147 const char* text_end = text_begin + state->TextLen;
5148 ImVec2 cursor_offset, select_start_offset;
5149
5150 {
5151 // Find lines numbers straddling cursor and selection min position
5152 int cursor_line_no = render_cursor ? -1 : -1000;
5153 int selmin_line_no = render_selection ? -1 : -1000;
5154 const char* cursor_ptr = render_cursor ? text_begin + state->Stb->cursor : NULL;
5155 const char* selmin_ptr = render_selection ? text_begin + ImMin(state->Stb->select_start, state->Stb->select_end) : NULL;
5156
5157 // Count lines and find line number for cursor and selection ends
5158 int line_count = 1;
5159 if (is_multiline)
5160 {
5161 for (const char* s = text_begin; (s = (const char*)memchr(s, '\n', (size_t)(text_end - s))) != NULL; s++)
5162 {
5163 if (cursor_line_no == -1 && s >= cursor_ptr) { cursor_line_no = line_count; }
5164 if (selmin_line_no == -1 && s >= selmin_ptr) { selmin_line_no = line_count; }
5165 line_count++;
5166 }
5167 }
5168 if (cursor_line_no == -1)
5169 cursor_line_no = line_count;
5170 if (selmin_line_no == -1)
5171 selmin_line_no = line_count;
5172
5173 // Calculate 2d position by finding the beginning of the line and measuring distance
5174 cursor_offset.x = InputTextCalcTextSize(&g, ImStrbol(cursor_ptr, text_begin), cursor_ptr).x;
5175 cursor_offset.y = cursor_line_no * g.FontSize;
5176 if (selmin_line_no >= 0)
5177 {
5178 select_start_offset.x = InputTextCalcTextSize(&g, ImStrbol(selmin_ptr, text_begin), selmin_ptr).x;
5179 select_start_offset.y = selmin_line_no * g.FontSize;
5180 }
5181
5182 // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
5183 if (is_multiline)
5184 text_size = ImVec2(inner_size.x, line_count * g.FontSize);
5185 }
5186
5187 // Scroll
5188 if (render_cursor && state->CursorFollow)
5189 {
5190 // Horizontal scroll in chunks of quarter width
5191 if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
5192 {
5193 const float scroll_increment_x = inner_size.x * 0.25f;
5194 const float visible_width = inner_size.x - style.FramePadding.x;
5195 if (cursor_offset.x < state->Scroll.x)
5196 state->Scroll.x = IM_TRUNC(ImMax(0.0f, cursor_offset.x - scroll_increment_x));
5197 else if (cursor_offset.x - visible_width >= state->Scroll.x)
5198 state->Scroll.x = IM_TRUNC(cursor_offset.x - visible_width + scroll_increment_x);
5199 }
5200 else
5201 {
5202 state->Scroll.y = 0.0f;
5203 }
5204
5205 // Vertical scroll
5206 if (is_multiline)
5207 {
5208 // Test if cursor is vertically visible
5209 if (cursor_offset.y - g.FontSize < scroll_y)
5210 scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
5211 else if (cursor_offset.y - (inner_size.y - style.FramePadding.y * 2.0f) >= scroll_y)
5212 scroll_y = cursor_offset.y - inner_size.y + style.FramePadding.y * 2.0f;
5213 const float scroll_max_y = ImMax((text_size.y + style.FramePadding.y * 2.0f) - inner_size.y, 0.0f);
5214 scroll_y = ImClamp(scroll_y, 0.0f, scroll_max_y);
5215 draw_pos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag
5216 draw_window->Scroll.y = scroll_y;
5217 }
5218
5219 state->CursorFollow = false;
5220 }
5221
5222 // Draw selection
5223 const ImVec2 draw_scroll = ImVec2(state->Scroll.x, 0.0f);
5224 if (render_selection)
5225 {
5226 const char* text_selected_begin = text_begin + ImMin(state->Stb->select_start, state->Stb->select_end);
5227 const char* text_selected_end = text_begin + ImMax(state->Stb->select_start, state->Stb->select_end);
5228
5229 ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests.
5230 float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
5231 float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
5232 ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll;
5233 for (const char* p = text_selected_begin; p < text_selected_end; )
5234 {
5235 if (rect_pos.y > clip_rect.w + g.FontSize)
5236 break;
5237 if (rect_pos.y < clip_rect.y)
5238 {
5239 p = (const char*)memchr((void*)p, '\n', text_selected_end - p);
5240 p = p ? p + 1 : text_selected_end;
5241 }
5242 else
5243 {
5244 ImVec2 rect_size = InputTextCalcTextSize(&g, p, text_selected_end, &p, NULL, true);
5245 if (rect_size.x <= 0.0f) rect_size.x = IM_TRUNC(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines
5246 ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos + ImVec2(rect_size.x, bg_offy_dn));
5247 rect.ClipWith(clip_rect);
5248 if (rect.Overlaps(clip_rect))
5249 draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
5250 rect_pos.x = draw_pos.x - draw_scroll.x;
5251 }
5252 rect_pos.y += g.FontSize;
5253 }
5254 }
5255
5256 // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash.
5257 // FIXME-OPT: Multiline could submit a smaller amount of contents to AddText() since we already iterated through it.
5258 if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
5259 {
5260 ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
5261 draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
5262 }
5263
5264 // Draw blinking cursor
5265 if (render_cursor)
5266 {
5267 state->CursorAnim += io.DeltaTime;
5268 bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f;
5269 ImVec2 cursor_screen_pos = ImTrunc(draw_pos + cursor_offset - draw_scroll);
5270 ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f);
5271 if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
5272 draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));
5273
5274 // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
5275 if (!is_readonly)
5276 {
5277 g.PlatformImeData.WantVisible = true;
5278 g.PlatformImeData.InputPos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize);
5279 g.PlatformImeData.InputLineHeight = g.FontSize;
5280 }
5281 }
5282 }
5283 else
5284 {
5285 // Render text only (no selection, no cursor)
5286 if (is_multiline)
5287 text_size = ImVec2(inner_size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width
5288 else if (!is_displaying_hint && g.ActiveId == id)
5289 buf_display_end = buf_display + state->TextLen;
5290 else if (!is_displaying_hint)
5291 buf_display_end = buf_display + strlen(buf_display);
5292
5293 if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length)
5294 {
5295 // Find render position for right alignment
5296 if (flags & ImGuiInputTextFlags_ElideLeft)
5297 draw_pos.x = ImMin(draw_pos.x, frame_bb.Max.x - CalcTextSize(buf_display, NULL).x - style.FramePadding.x);
5298
5299 const ImVec2 draw_scroll = /*state ? ImVec2(state->Scroll.x, 0.0f) :*/ ImVec2(0.0f, 0.0f); // Preserve scroll when inactive?
5300 ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text);
5301 draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect);
5302 }
5303 }
5304
5305 if (is_password && !is_displaying_hint)
5306 PopFont();
5307
5308 if (is_multiline)
5309 {
5310 // For focus requests to work on our multiline we need to ensure our child ItemAdd() call specifies the ImGuiItemFlags_Inputable (see #4761, #7870)...
5311 Dummy(ImVec2(text_size.x, text_size.y + style.FramePadding.y));
5312 g.NextItemData.ItemFlags |= (ImGuiItemFlags)ImGuiItemFlags_Inputable | ImGuiItemFlags_NoTabStop;
5313 EndChild();
5314 item_data_backup.StatusFlags |= (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredWindow);
5315
5316 // ...and then we need to undo the group overriding last item data, which gets a bit messy as EndGroup() tries to forward scrollbar being active...
5317 // FIXME: This quite messy/tricky, should attempt to get rid of the child window.
5318 EndGroup();
5319 if (g.LastItemData.ID == 0 || g.LastItemData.ID != GetWindowScrollbarID(draw_window, ImGuiAxis_Y))
5320 {
5321 g.LastItemData.ID = id;
5322 g.LastItemData.ItemFlags = item_data_backup.ItemFlags;
5323 g.LastItemData.StatusFlags = item_data_backup.StatusFlags;
5324 }
5325 }
5326
5327 // Log as text
5328 if (g.LogEnabled && (!is_password || is_displaying_hint))
5329 {
5330 LogSetNextTextDecoration("{", "}");
5331 LogRenderedText(&draw_pos, buf_display, buf_display_end);
5332 }
5333
5334 if (label_size.x > 0)
5335 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
5336
5337 if (value_changed)
5338 MarkItemEdited(id);
5339
5340 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Inputable);
5341 if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
5342 return validated;
5343 else
5344 return value_changed;
5345 }
5346
5347 void ImGui::DebugNodeInputTextState(ImGuiInputTextState* state)
5348 {
5349 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
5350 ImGuiContext& g = *GImGui;
5351 ImStb::STB_TexteditState* stb_state = state->Stb;
5352 ImStb::StbUndoState* undo_state = &stb_state->undostate;
5353 Text("ID: 0x%08X, ActiveID: 0x%08X", state->ID, g.ActiveId);
5354 DebugLocateItemOnHover(state->ID);
5355 Text("CurLenA: %d, Cursor: %d, Selection: %d..%d", state->TextLen, stb_state->cursor, stb_state->select_start, stb_state->select_end);
5356 Text("BufCapacityA: %d", state->BufCapacity);
5357 Text("(Internal Buffer: TextA Size: %d, Capacity: %d)", state->TextA.Size, state->TextA.Capacity);
5358 Text("has_preferred_x: %d (%.2f)", stb_state->has_preferred_x, stb_state->preferred_x);
5359 Text("undo_point: %d, redo_point: %d, undo_char_point: %d, redo_char_point: %d", undo_state->undo_point, undo_state->redo_point, undo_state->undo_char_point, undo_state->redo_char_point);
5360 if (BeginChild("undopoints", ImVec2(0.0f, GetTextLineHeight() * 10), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeY)) // Visualize undo state
5361 {
5362 PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
5363 for (int n = 0; n < IMSTB_TEXTEDIT_UNDOSTATECOUNT; n++)
5364 {
5365 ImStb::StbUndoRecord* undo_rec = &undo_state->undo_rec[n];
5366 const char undo_rec_type = (n < undo_state->undo_point) ? 'u' : (n >= undo_state->redo_point) ? 'r' : ' ';
5367 if (undo_rec_type == ' ')
5368 BeginDisabled();
5369 const int buf_preview_len = (undo_rec_type != ' ' && undo_rec->char_storage != -1) ? undo_rec->insert_length : 0;
5370 const char* buf_preview_str = undo_state->undo_char + undo_rec->char_storage;
5371 Text("%c [%02d] where %03d, insert %03d, delete %03d, char_storage %03d \"%.*s\"",
5372 undo_rec_type, n, undo_rec->where, undo_rec->insert_length, undo_rec->delete_length, undo_rec->char_storage, buf_preview_len, buf_preview_str);
5373 if (undo_rec_type == ' ')
5374 EndDisabled();
5375 }
5376 PopStyleVar();
5377 }
5378 EndChild();
5379 #else
5380 IM_UNUSED(state);
5381 #endif
5382 }
5383
5384 //-------------------------------------------------------------------------
5385 // [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc.
5386 //-------------------------------------------------------------------------
5387 // - ColorEdit3()
5388 // - ColorEdit4()
5389 // - ColorPicker3()
5390 // - RenderColorRectWithAlphaCheckerboard() [Internal]
5391 // - ColorPicker4()
5392 // - ColorButton()
5393 // - SetColorEditOptions()
5394 // - ColorTooltip() [Internal]
5395 // - ColorEditOptionsPopup() [Internal]
5396 // - ColorPickerOptionsPopup() [Internal]
5397 //-------------------------------------------------------------------------
5398
5399 bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
5400 {
5401 return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
5402 }
5403
5404 static void ColorEditRestoreH(const float* col, float* H)
5405 {
5406 ImGuiContext& g = *GImGui;
5407 IM_ASSERT(g.ColorEditCurrentID != 0);
5408 if (g.ColorEditSavedID != g.ColorEditCurrentID || g.ColorEditSavedColor != ImGui::ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0)))
5409 return;
5410 *H = g.ColorEditSavedHue;
5411 }
5412
5413 // ColorEdit supports RGB and HSV inputs. In case of RGB input resulting color may have undefined hue and/or saturation.
5414 // Since widget displays both RGB and HSV values we must preserve hue and saturation to prevent these values resetting.
5415 static void ColorEditRestoreHS(const float* col, float* H, float* S, float* V)
5416 {
5417 ImGuiContext& g = *GImGui;
5418 IM_ASSERT(g.ColorEditCurrentID != 0);
5419 if (g.ColorEditSavedID != g.ColorEditCurrentID || g.ColorEditSavedColor != ImGui::ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0)))
5420 return;
5421
5422 // When S == 0, H is undefined.
5423 // When H == 1 it wraps around to 0.
5424 if (*S == 0.0f || (*H == 0.0f && g.ColorEditSavedHue == 1))
5425 *H = g.ColorEditSavedHue;
5426
5427 // When V == 0, S is undefined.
5428 if (*V == 0.0f)
5429 *S = g.ColorEditSavedSat;
5430 }
5431
5432 // Edit colors components (each component in 0.0f..1.0f range).
5433 // See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
5434 // With typical options: Left-click on color square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.
5435 bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
5436 {
5437 ImGuiWindow* window = GetCurrentWindow();
5438 if (window->SkipItems)
5439 return false;
5440
5441 ImGuiContext& g = *GImGui;
5442 const ImGuiStyle& style = g.Style;
5443 const float square_sz = GetFrameHeight();
5444 const char* label_display_end = FindRenderedTextEnd(label);
5445 float w_full = CalcItemWidth();
5446 g.NextItemData.ClearFlags();
5447
5448 BeginGroup();
5449 PushID(label);
5450 const bool set_current_color_edit_id = (g.ColorEditCurrentID == 0);
5451 if (set_current_color_edit_id)
5452 g.ColorEditCurrentID = window->IDStack.back();
5453
5454 // If we're not showing any slider there's no point in doing any HSV conversions
5455 const ImGuiColorEditFlags flags_untouched = flags;
5456 if (flags & ImGuiColorEditFlags_NoInputs)
5457 flags = (flags & (~ImGuiColorEditFlags_DisplayMask_)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions;
5458
5459 // Context menu: display and modify options (before defaults are applied)
5460 if (!(flags & ImGuiColorEditFlags_NoOptions))
5461 ColorEditOptionsPopup(col, flags);
5462
5463 // Read stored options
5464 if (!(flags & ImGuiColorEditFlags_DisplayMask_))
5465 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DisplayMask_);
5466 if (!(flags & ImGuiColorEditFlags_DataTypeMask_))
5467 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_DataTypeMask_);
5468 if (!(flags & ImGuiColorEditFlags_PickerMask_))
5469 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_);
5470 if (!(flags & ImGuiColorEditFlags_InputMask_))
5471 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_InputMask_);
5472 flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_));
5473 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check that only 1 is selected
5474 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check that only 1 is selected
5475
5476 const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
5477 const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
5478 const int components = alpha ? 4 : 3;
5479 const float w_button = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);
5480 const float w_inputs = ImMax(w_full - w_button, 1.0f);
5481 w_full = w_inputs + w_button;
5482
5483 // Convert to the formats we need
5484 float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
5485 if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB))
5486 ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
5487 else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV))
5488 {
5489 // Hue is lost when converting from grayscale rgb (saturation=0). Restore it.
5490 ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
5491 ColorEditRestoreHS(col, &f[0], &f[1], &f[2]);
5492 }
5493 int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };
5494
5495 bool value_changed = false;
5496 bool value_changed_as_float = false;
5497
5498 const ImVec2 pos = window->DC.CursorPos;
5499 const float inputs_offset_x = (style.ColorButtonPosition == ImGuiDir_Left) ? w_button : 0.0f;
5500 window->DC.CursorPos.x = pos.x + inputs_offset_x;
5501
5502 if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
5503 {
5504 // RGB/HSV 0..255 Sliders
5505 const float w_items = w_inputs - style.ItemInnerSpacing.x * (components - 1);
5506
5507 const bool hide_prefix = (IM_TRUNC(w_items / components) <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
5508 static const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
5509 static const char* fmt_table_int[3][4] =
5510 {
5511 { "%3d", "%3d", "%3d", "%3d" }, // Short display
5512 { "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA
5513 { "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA
5514 };
5515 static const char* fmt_table_float[3][4] =
5516 {
5517 { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
5518 { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
5519 { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
5520 };
5521 const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1;
5522
5523 float prev_split = 0.0f;
5524 for (int n = 0; n < components; n++)
5525 {
5526 if (n > 0)
5527 SameLine(0, style.ItemInnerSpacing.x);
5528 float next_split = IM_TRUNC(w_items * (n + 1) / components);
5529 SetNextItemWidth(ImMax(next_split - prev_split, 1.0f));
5530 prev_split = next_split;
5531
5532 // FIXME: When ImGuiColorEditFlags_HDR flag is passed HS values snap in weird ways when SV values go below 0.
5533 if (flags & ImGuiColorEditFlags_Float)
5534 {
5535 value_changed |= DragFloat(ids[n], &f[n], 1.0f / 255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]);
5536 value_changed_as_float |= value_changed;
5537 }
5538 else
5539 {
5540 value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]);
5541 }
5542 if (!(flags & ImGuiColorEditFlags_NoOptions))
5543 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5544 }
5545 }
5546 else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
5547 {
5548 // RGB Hexadecimal Input
5549 char buf[64];
5550 if (alpha)
5551 ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255), ImClamp(i[3], 0, 255));
5552 else
5553 ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0], 0, 255), ImClamp(i[1], 0, 255), ImClamp(i[2], 0, 255));
5554 SetNextItemWidth(w_inputs);
5555 if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsUppercase))
5556 {
5557 value_changed = true;
5558 char* p = buf;
5559 while (*p == '#' || ImCharIsBlankA(*p))
5560 p++;
5561 i[0] = i[1] = i[2] = 0;
5562 i[3] = 0xFF; // alpha default to 255 is not parsed by scanf (e.g. inputting #FFFFFF omitting alpha)
5563 int r;
5564 if (alpha)
5565 r = sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)
5566 else
5567 r = sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
5568 IM_UNUSED(r); // Fixes C6031: Return value ignored: 'sscanf'.
5569 }
5570 if (!(flags & ImGuiColorEditFlags_NoOptions))
5571 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5572 }
5573
5574 ImGuiWindow* picker_active_window = NULL;
5575 if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
5576 {
5577 const float button_offset_x = ((flags & ImGuiColorEditFlags_NoInputs) || (style.ColorButtonPosition == ImGuiDir_Left)) ? 0.0f : w_inputs + style.ItemInnerSpacing.x;
5578 window->DC.CursorPos = ImVec2(pos.x + button_offset_x, pos.y);
5579
5580 const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
5581 if (ColorButton("##ColorButton", col_v4, flags))
5582 {
5583 if (!(flags & ImGuiColorEditFlags_NoPicker))
5584 {
5585 // Store current color and open a picker
5586 g.ColorPickerRef = col_v4;
5587 OpenPopup("picker");
5588 SetNextWindowPos(g.LastItemData.Rect.GetBL() + ImVec2(0.0f, style.ItemSpacing.y));
5589 }
5590 }
5591 if (!(flags & ImGuiColorEditFlags_NoOptions))
5592 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5593
5594 if (BeginPopup("picker"))
5595 {
5596 if (g.CurrentWindow->BeginCount == 1)
5597 {
5598 picker_active_window = g.CurrentWindow;
5599 if (label != label_display_end)
5600 {
5601 TextEx(label, label_display_end);
5602 Spacing();
5603 }
5604 ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_PickerMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
5605 ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayMask_ | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
5606 SetNextItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
5607 value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
5608 }
5609 EndPopup();
5610 }
5611 }
5612
5613 if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
5614 {
5615 // Position not necessarily next to last submitted button (e.g. if style.ColorButtonPosition == ImGuiDir_Left),
5616 // but we need to use SameLine() to setup baseline correctly. Might want to refactor SameLine() to simplify this.
5617 SameLine(0.0f, style.ItemInnerSpacing.x);
5618 window->DC.CursorPos.x = pos.x + ((flags & ImGuiColorEditFlags_NoInputs) ? w_button : w_full + style.ItemInnerSpacing.x);
5619 TextEx(label, label_display_end);
5620 }
5621
5622 // Convert back
5623 if (value_changed && picker_active_window == NULL)
5624 {
5625 if (!value_changed_as_float)
5626 for (int n = 0; n < 4; n++)
5627 f[n] = i[n] / 255.0f;
5628 if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB))
5629 {
5630 g.ColorEditSavedHue = f[0];
5631 g.ColorEditSavedSat = f[1];
5632 ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
5633 g.ColorEditSavedID = g.ColorEditCurrentID;
5634 g.ColorEditSavedColor = ColorConvertFloat4ToU32(ImVec4(f[0], f[1], f[2], 0));
5635 }
5636 if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV))
5637 ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
5638
5639 col[0] = f[0];
5640 col[1] = f[1];
5641 col[2] = f[2];
5642 if (alpha)
5643 col[3] = f[3];
5644 }
5645
5646 if (set_current_color_edit_id)
5647 g.ColorEditCurrentID = 0;
5648 PopID();
5649 EndGroup();
5650
5651 // Drag and Drop Target
5652 // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
5653 if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(g.LastItemData.ItemFlags & ImGuiItemFlags_ReadOnly) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget())
5654 {
5655 bool accepted_drag_drop = false;
5656 if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
5657 {
5658 memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512 //-V1086
5659 value_changed = accepted_drag_drop = true;
5660 }
5661 if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
5662 {
5663 memcpy((float*)col, payload->Data, sizeof(float) * components);
5664 value_changed = accepted_drag_drop = true;
5665 }
5666
5667 // Drag-drop payloads are always RGB
5668 if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV))
5669 ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]);
5670 EndDragDropTarget();
5671 }
5672
5673 // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().
5674 if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)
5675 g.LastItemData.ID = g.ActiveId;
5676
5677 if (value_changed && g.LastItemData.ID != 0) // In case of ID collision, the second EndGroup() won't catch g.ActiveId
5678 MarkItemEdited(g.LastItemData.ID);
5679
5680 return value_changed;
5681 }
5682
5683 bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
5684 {
5685 float col4[4] = { col[0], col[1], col[2], 1.0f };
5686 if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
5687 return false;
5688 col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
5689 return true;
5690 }
5691
5692 // Helper for ColorPicker4()
5693 static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w, float alpha)
5694 {
5695 ImU32 alpha8 = IM_F32_TO_INT8_SAT(alpha);
5696 ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32(0,0,0,alpha8));
5697 ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32(255,255,255,alpha8));
5698 ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32(0,0,0,alpha8));
5699 ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32(255,255,255,alpha8));
5700 }
5701
5702 // Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
5703 // (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.)
5704 // FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..)
5705 // FIXME: this is trying to be aware of style.Alpha but not fully correct. Also, the color wheel will have overlapping glitches with (style.Alpha < 1.0)
5706 bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
5707 {
5708 ImGuiContext& g = *GImGui;
5709 ImGuiWindow* window = GetCurrentWindow();
5710 if (window->SkipItems)
5711 return false;
5712
5713 ImDrawList* draw_list = window->DrawList;
5714 ImGuiStyle& style = g.Style;
5715 ImGuiIO& io = g.IO;
5716
5717 const float width = CalcItemWidth();
5718 const bool is_readonly = ((g.NextItemData.ItemFlags | g.CurrentItemFlags) & ImGuiItemFlags_ReadOnly) != 0;
5719 g.NextItemData.ClearFlags();
5720
5721 PushID(label);
5722 const bool set_current_color_edit_id = (g.ColorEditCurrentID == 0);
5723 if (set_current_color_edit_id)
5724 g.ColorEditCurrentID = window->IDStack.back();
5725 BeginGroup();
5726
5727 if (!(flags & ImGuiColorEditFlags_NoSidePreview))
5728 flags |= ImGuiColorEditFlags_NoSmallPreview;
5729
5730 // Context menu: display and store options.
5731 if (!(flags & ImGuiColorEditFlags_NoOptions))
5732 ColorPickerOptionsPopup(col, flags);
5733
5734 // Read stored options
5735 if (!(flags & ImGuiColorEditFlags_PickerMask_))
5736 flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_PickerMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_PickerMask_;
5737 if (!(flags & ImGuiColorEditFlags_InputMask_))
5738 flags |= ((g.ColorEditOptions & ImGuiColorEditFlags_InputMask_) ? g.ColorEditOptions : ImGuiColorEditFlags_DefaultOptions_) & ImGuiColorEditFlags_InputMask_;
5739 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check that only 1 is selected
5740 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check that only 1 is selected
5741 if (!(flags & ImGuiColorEditFlags_NoOptions))
5742 flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
5743
5744 // Setup
5745 int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;
5746 bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
5747 ImVec2 picker_pos = window->DC.CursorPos;
5748 float square_sz = GetFrameHeight();
5749 float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars
5750 float sv_picker_size = ImMax(bars_width * 1, width - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
5751 float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
5752 float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
5753 float bars_triangles_half_sz = IM_TRUNC(bars_width * 0.20f);
5754
5755 float backup_initial_col[4];
5756 memcpy(backup_initial_col, col, components * sizeof(float));
5757
5758 float wheel_thickness = sv_picker_size * 0.08f;
5759 float wheel_r_outer = sv_picker_size * 0.50f;
5760 float wheel_r_inner = wheel_r_outer - wheel_thickness;
5761 ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size * 0.5f);
5762
5763 // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
5764 float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);
5765 ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
5766 ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
5767 ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
5768
5769 float H = col[0], S = col[1], V = col[2];
5770 float R = col[0], G = col[1], B = col[2];
5771 if (flags & ImGuiColorEditFlags_InputRGB)
5772 {
5773 // Hue is lost when converting from grayscale rgb (saturation=0). Restore it.
5774 ColorConvertRGBtoHSV(R, G, B, H, S, V);
5775 ColorEditRestoreHS(col, &H, &S, &V);
5776 }
5777 else if (flags & ImGuiColorEditFlags_InputHSV)
5778 {
5779 ColorConvertHSVtoRGB(H, S, V, R, G, B);
5780 }
5781
5782 bool value_changed = false, value_changed_h = false, value_changed_sv = false;
5783
5784 PushItemFlag(ImGuiItemFlags_NoNav, true);
5785 if (flags & ImGuiColorEditFlags_PickerHueWheel)
5786 {
5787 // Hue wheel + SV triangle logic
5788 InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
5789 if (IsItemActive() && !is_readonly)
5790 {
5791 ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;
5792 ImVec2 current_off = g.IO.MousePos - wheel_center;
5793 float initial_dist2 = ImLengthSqr(initial_off);
5794 if (initial_dist2 >= (wheel_r_inner - 1) * (wheel_r_inner - 1) && initial_dist2 <= (wheel_r_outer + 1) * (wheel_r_outer + 1))
5795 {
5796 // Interactive with Hue wheel
5797 H = ImAtan2(current_off.y, current_off.x) / IM_PI * 0.5f;
5798 if (H < 0.0f)
5799 H += 1.0f;
5800 value_changed = value_changed_h = true;
5801 }
5802 float cos_hue_angle = ImCos(-H * 2.0f * IM_PI);
5803 float sin_hue_angle = ImSin(-H * 2.0f * IM_PI);
5804 if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
5805 {
5806 // Interacting with SV triangle
5807 ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
5808 if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
5809 current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
5810 float uu, vv, ww;
5811 ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
5812 V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
5813 S = ImClamp(uu / V, 0.0001f, 1.0f);
5814 value_changed = value_changed_sv = true;
5815 }
5816 }
5817 if (!(flags & ImGuiColorEditFlags_NoOptions))
5818 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5819 }
5820 else if (flags & ImGuiColorEditFlags_PickerHueBar)
5821 {
5822 // SV rectangle logic
5823 InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size));
5824 if (IsItemActive() && !is_readonly)
5825 {
5826 S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size - 1));
5827 V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
5828 ColorEditRestoreH(col, &H); // Greatly reduces hue jitter and reset to 0 when hue == 255 and color is rapidly modified using SV square.
5829 value_changed = value_changed_sv = true;
5830 }
5831 if (!(flags & ImGuiColorEditFlags_NoOptions))
5832 OpenPopupOnItemClick("context", ImGuiPopupFlags_MouseButtonRight);
5833
5834 // Hue bar logic
5835 SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
5836 InvisibleButton("hue", ImVec2(bars_width, sv_picker_size));
5837 if (IsItemActive() && !is_readonly)
5838 {
5839 H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
5840 value_changed = value_changed_h = true;
5841 }
5842 }
5843
5844 // Alpha bar logic
5845 if (alpha_bar)
5846 {
5847 SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
5848 InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size));
5849 if (IsItemActive())
5850 {
5851 col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size - 1));
5852 value_changed = true;
5853 }
5854 }
5855 PopItemFlag(); // ImGuiItemFlags_NoNav
5856
5857 if (!(flags & ImGuiColorEditFlags_NoSidePreview))
5858 {
5859 SameLine(0, style.ItemInnerSpacing.x);
5860 BeginGroup();
5861 }
5862
5863 if (!(flags & ImGuiColorEditFlags_NoLabel))
5864 {
5865 const char* label_display_end = FindRenderedTextEnd(label);
5866 if (label != label_display_end)
5867 {
5868 if ((flags & ImGuiColorEditFlags_NoSidePreview))
5869 SameLine(0, style.ItemInnerSpacing.x);
5870 TextEx(label, label_display_end);
5871 }
5872 }
5873
5874 if (!(flags & ImGuiColorEditFlags_NoSidePreview))
5875 {
5876 PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);
5877 ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
5878 if ((flags & ImGuiColorEditFlags_NoLabel))
5879 Text("Current");
5880
5881 ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip;
5882 ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2));
5883 if (ref_col != NULL)
5884 {
5885 Text("Original");
5886 ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
5887 if (ColorButton("##original", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)))
5888 {
5889 memcpy(col, ref_col, components * sizeof(float));
5890 value_changed = true;
5891 }
5892 }
5893 PopItemFlag();
5894 EndGroup();
5895 }
5896
5897 // Convert back color to RGB
5898 if (value_changed_h || value_changed_sv)
5899 {
5900 if (flags & ImGuiColorEditFlags_InputRGB)
5901 {
5902 ColorConvertHSVtoRGB(H, S, V, col[0], col[1], col[2]);
5903 g.ColorEditSavedHue = H;
5904 g.ColorEditSavedSat = S;
5905 g.ColorEditSavedID = g.ColorEditCurrentID;
5906 g.ColorEditSavedColor = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 0));
5907 }
5908 else if (flags & ImGuiColorEditFlags_InputHSV)
5909 {
5910 col[0] = H;
5911 col[1] = S;
5912 col[2] = V;
5913 }
5914 }
5915
5916 // R,G,B and H,S,V slider color editor
5917 bool value_changed_fix_hue_wrap = false;
5918 if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
5919 {
5920 PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
5921 ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags_DataTypeMask_ | ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
5922 ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
5923 if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)
5924 if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB))
5925 {
5926 // FIXME: Hackily differentiating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget.
5927 // For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050)
5928 value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap);
5929 value_changed = true;
5930 }
5931 if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)
5932 value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_DisplayHSV);
5933 if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags_DisplayMask_) == 0)
5934 value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_DisplayHex);
5935 PopItemWidth();
5936 }
5937
5938 // Try to cancel hue wrap (after ColorEdit4 call), if any
5939 if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB))
5940 {
5941 float new_H, new_S, new_V;
5942 ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
5943 if (new_H <= 0 && H > 0)
5944 {
5945 if (new_V <= 0 && V != new_V)
5946 ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
5947 else if (new_S <= 0)
5948 ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
5949 }
5950 }
5951
5952 if (value_changed)
5953 {
5954 if (flags & ImGuiColorEditFlags_InputRGB)
5955 {
5956 R = col[0];
5957 G = col[1];
5958 B = col[2];
5959 ColorConvertRGBtoHSV(R, G, B, H, S, V);
5960 ColorEditRestoreHS(col, &H, &S, &V); // Fix local Hue as display below will use it immediately.
5961 }
5962 else if (flags & ImGuiColorEditFlags_InputHSV)
5963 {
5964 H = col[0];
5965 S = col[1];
5966 V = col[2];
5967 ColorConvertHSVtoRGB(H, S, V, R, G, B);
5968 }
5969 }
5970
5971 const int style_alpha8 = IM_F32_TO_INT8_SAT(style.Alpha);
5972 const ImU32 col_black = IM_COL32(0,0,0,style_alpha8);
5973 const ImU32 col_white = IM_COL32(255,255,255,style_alpha8);
5974 const ImU32 col_midgrey = IM_COL32(128,128,128,style_alpha8);
5975 const ImU32 col_hues[6 + 1] = { IM_COL32(255,0,0,style_alpha8), IM_COL32(255,255,0,style_alpha8), IM_COL32(0,255,0,style_alpha8), IM_COL32(0,255,255,style_alpha8), IM_COL32(0,0,255,style_alpha8), IM_COL32(255,0,255,style_alpha8), IM_COL32(255,0,0,style_alpha8) };
5976
5977 ImVec4 hue_color_f(1, 1, 1, style.Alpha); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z);
5978 ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
5979 ImU32 user_col32_striped_of_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, style.Alpha)); // Important: this is still including the main rendering/style alpha!!
5980
5981 ImVec2 sv_cursor_pos;
5982
5983 if (flags & ImGuiColorEditFlags_PickerHueWheel)
5984 {
5985 // Render Hue Wheel
5986 const float aeps = 0.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
5987 const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
5988 for (int n = 0; n < 6; n++)
5989 {
5990 const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps;
5991 const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;
5992 const int vert_start_idx = draw_list->VtxBuffer.Size;
5993 draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
5994 draw_list->PathStroke(col_white, 0, wheel_thickness);
5995 const int vert_end_idx = draw_list->VtxBuffer.Size;
5996
5997 // Paint colors over existing vertices
5998 ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner);
5999 ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner);
6000 ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col_hues[n], col_hues[n + 1]);
6001 }
6002
6003 // Render Cursor + preview on Hue Wheel
6004 float cos_hue_angle = ImCos(H * 2.0f * IM_PI);
6005 float sin_hue_angle = ImSin(H * 2.0f * IM_PI);
6006 ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner + wheel_r_outer) * 0.5f);
6007 float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;
6008 int hue_cursor_segments = draw_list->_CalcCircleAutoSegmentCount(hue_cursor_rad); // Lock segment count so the +1 one matches others.
6009 draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);
6010 draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad + 1, col_midgrey, hue_cursor_segments);
6011 draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, col_white, hue_cursor_segments);
6012
6013 // Render SV triangle (rotated according to hue)
6014 ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
6015 ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
6016 ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
6017 ImVec2 uv_white = GetFontTexUvWhitePixel();
6018 draw_list->PrimReserve(3, 3);
6019 draw_list->PrimVtx(tra, uv_white, hue_color32);
6020 draw_list->PrimVtx(trb, uv_white, col_black);
6021 draw_list->PrimVtx(trc, uv_white, col_white);
6022 draw_list->AddTriangle(tra, trb, trc, col_midgrey, 1.5f);
6023 sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
6024 }
6025 else if (flags & ImGuiColorEditFlags_PickerHueBar)
6026 {
6027 // Render SV Square
6028 draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), col_white, hue_color32, hue_color32, col_white);
6029 draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0, 0, col_black, col_black);
6030 RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size, sv_picker_size), 0.0f);
6031 sv_cursor_pos.x = ImClamp(IM_ROUND(picker_pos.x + ImSaturate(S) * sv_picker_size), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much
6032 sv_cursor_pos.y = ImClamp(IM_ROUND(picker_pos.y + ImSaturate(1 - V) * sv_picker_size), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2);
6033
6034 // Render Hue Bar
6035 for (int i = 0; i < 6; ++i)
6036 draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), col_hues[i], col_hues[i], col_hues[i + 1], col_hues[i + 1]);
6037 float bar0_line_y = IM_ROUND(picker_pos.y + H * sv_picker_size);
6038 RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
6039 RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha);
6040 }
6041
6042 // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
6043 float sv_cursor_rad = value_changed_sv ? wheel_thickness * 0.55f : wheel_thickness * 0.40f;
6044 int sv_cursor_segments = draw_list->_CalcCircleAutoSegmentCount(sv_cursor_rad); // Lock segment count so the +1 one matches others.
6045 draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, user_col32_striped_of_alpha, sv_cursor_segments);
6046 draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad + 1, col_midgrey, sv_cursor_segments);
6047 draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, col_white, sv_cursor_segments);
6048
6049 // Render alpha bar
6050 if (alpha_bar)
6051 {
6052 float alpha = ImSaturate(col[3]);
6053 ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
6054 RenderColorRectWithAlphaCheckerboard(draw_list, bar1_bb.Min, bar1_bb.Max, 0, bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
6055 draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, user_col32_striped_of_alpha, user_col32_striped_of_alpha, user_col32_striped_of_alpha & ~IM_COL32_A_MASK, user_col32_striped_of_alpha & ~IM_COL32_A_MASK);
6056 float bar1_line_y = IM_ROUND(picker_pos.y + (1.0f - alpha) * sv_picker_size);
6057 RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
6058 RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f, style.Alpha);
6059 }
6060
6061 EndGroup();
6062
6063 if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0)
6064 value_changed = false;
6065 if (value_changed && g.LastItemData.ID != 0) // In case of ID collision, the second EndGroup() won't catch g.ActiveId
6066 MarkItemEdited(g.LastItemData.ID);
6067
6068 if (set_current_color_edit_id)
6069 g.ColorEditCurrentID = 0;
6070 PopID();
6071
6072 return value_changed;
6073 }
6074
6075 // A little color square. Return true when clicked.
6076 // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
6077 // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
6078 // Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set.
6079 bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, const ImVec2& size_arg)
6080 {
6081 ImGuiWindow* window = GetCurrentWindow();
6082 if (window->SkipItems)
6083 return false;
6084
6085 ImGuiContext& g = *GImGui;
6086 const ImGuiID id = window->GetID(desc_id);
6087 const float default_size = GetFrameHeight();
6088 const ImVec2 size(size_arg.x == 0.0f ? default_size : size_arg.x, size_arg.y == 0.0f ? default_size : size_arg.y);
6089 const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
6090 ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
6091 if (!ItemAdd(bb, id))
6092 return false;
6093
6094 bool hovered, held;
6095 bool pressed = ButtonBehavior(bb, id, &hovered, &held);
6096
6097 if (flags & ImGuiColorEditFlags_NoAlpha)
6098 flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);
6099
6100 ImVec4 col_rgb = col;
6101 if (flags & ImGuiColorEditFlags_InputHSV)
6102 ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z);
6103
6104 ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f);
6105 float grid_step = ImMin(size.x, size.y) / 2.99f;
6106 float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
6107 ImRect bb_inner = bb;
6108 float off = 0.0f;
6109 if ((flags & ImGuiColorEditFlags_NoBorder) == 0)
6110 {
6111 off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts.
6112 bb_inner.Expand(off);
6113 }
6114 if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f)
6115 {
6116 float mid_x = IM_ROUND((bb_inner.Min.x + bb_inner.Max.x) * 0.5f);
6117 RenderColorRectWithAlphaCheckerboard(window->DrawList, ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawFlags_RoundCornersRight);
6118 window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawFlags_RoundCornersLeft);
6119 }
6120 else
6121 {
6122 // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
6123 ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha;
6124 if (col_source.w < 1.0f)
6125 RenderColorRectWithAlphaCheckerboard(window->DrawList, bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
6126 else
6127 window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding);
6128 }
6129 RenderNavCursor(bb, id);
6130 if ((flags & ImGuiColorEditFlags_NoBorder) == 0)
6131 {
6132 if (g.Style.FrameBorderSize > 0.0f)
6133 RenderFrameBorder(bb.Min, bb.Max, rounding);
6134 else
6135 window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border
6136 }
6137
6138 // Drag and Drop Source
6139 // NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test.
6140 if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource())
6141 {
6142 if (flags & ImGuiColorEditFlags_NoAlpha)
6143 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once);
6144 else
6145 SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once);
6146 ColorButton(desc_id, col, flags);
6147 SameLine();
6148 TextEx("Color");
6149 EndDragDropSource();
6150 }
6151
6152 // Tooltip
6153 if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered && IsItemHovered(ImGuiHoveredFlags_ForTooltip))
6154 ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));
6155
6156 return pressed;
6157 }
6158
6159 // Initialize/override default color options
6160 void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
6161 {
6162 ImGuiContext& g = *GImGui;
6163 if ((flags & ImGuiColorEditFlags_DisplayMask_) == 0)
6164 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DisplayMask_;
6165 if ((flags & ImGuiColorEditFlags_DataTypeMask_) == 0)
6166 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_DataTypeMask_;
6167 if ((flags & ImGuiColorEditFlags_PickerMask_) == 0)
6168 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_PickerMask_;
6169 if ((flags & ImGuiColorEditFlags_InputMask_) == 0)
6170 flags |= ImGuiColorEditFlags_DefaultOptions_ & ImGuiColorEditFlags_InputMask_;
6171 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DisplayMask_)); // Check only 1 option is selected
6172 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_DataTypeMask_)); // Check only 1 option is selected
6173 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_PickerMask_)); // Check only 1 option is selected
6174 IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags_InputMask_)); // Check only 1 option is selected
6175 g.ColorEditOptions = flags;
6176 }
6177
6178 // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
6179 void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)
6180 {
6181 ImGuiContext& g = *GImGui;
6182
6183 if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
6184 return;
6185 const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
6186 if (text_end > text)
6187 {
6188 TextEx(text, text_end);
6189 Separator();
6190 }
6191
6192 ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
6193 ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
6194 int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
6195 ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags_InputMask_ | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);
6196 SameLine();
6197 if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags_InputMask_))
6198 {
6199 if (flags & ImGuiColorEditFlags_NoAlpha)
6200 Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]);
6201 else
6202 Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]);
6203 }
6204 else if (flags & ImGuiColorEditFlags_InputHSV)
6205 {
6206 if (flags & ImGuiColorEditFlags_NoAlpha)
6207 Text("H: %.3f, S: %.3f, V: %.3f", col[0], col[1], col[2]);
6208 else
6209 Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col[0], col[1], col[2], col[3]);
6210 }
6211 EndTooltip();
6212 }
6213
6214 void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
6215 {
6216 bool allow_opt_inputs = !(flags & ImGuiColorEditFlags_DisplayMask_);
6217 bool allow_opt_datatype = !(flags & ImGuiColorEditFlags_DataTypeMask_);
6218 if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
6219 return;
6220
6221 ImGuiContext& g = *GImGui;
6222 PushItemFlag(ImGuiItemFlags_NoMarkEdited, true);
6223 ImGuiColorEditFlags opts = g.ColorEditOptions;
6224 if (allow_opt_inputs)
6225 {
6226 if (RadioButton("RGB", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayRGB;
6227 if (RadioButton("HSV", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHSV;
6228 if (RadioButton("Hex", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags_DisplayMask_) | ImGuiColorEditFlags_DisplayHex;
6229 }
6230 if (allow_opt_datatype)
6231 {
6232 if (allow_opt_inputs) Separator();
6233 if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Uint8;
6234 if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags_DataTypeMask_) | ImGuiColorEditFlags_Float;
6235 }
6236
6237 if (allow_opt_inputs || allow_opt_datatype)
6238 Separator();
6239 if (Button("Copy as..", ImVec2(-1, 0)))
6240 OpenPopup("Copy");
6241 if (BeginPopup("Copy"))
6242 {
6243 int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
6244 char buf[64];
6245 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
6246 if (Selectable(buf))
6247 SetClipboardText(buf);
6248 ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca);
6249 if (Selectable(buf))
6250 SetClipboardText(buf);
6251 ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", cr, cg, cb);
6252 if (Selectable(buf))
6253 SetClipboardText(buf);
6254 if (!(flags & ImGuiColorEditFlags_NoAlpha))
6255 {
6256 ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", cr, cg, cb, ca);
6257 if (Selectable(buf))
6258 SetClipboardText(buf);
6259 }
6260 EndPopup();
6261 }
6262
6263 g.ColorEditOptions = opts;
6264 PopItemFlag();
6265 EndPopup();
6266 }
6267
6268 void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags)
6269 {
6270 bool allow_opt_picker = !(flags & ImGuiColorEditFlags_PickerMask_);
6271 bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
6272 if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context"))
6273 return;
6274
6275 ImGuiContext& g = *GImGui;
6276 PushItemFlag(ImGuiItemFlags_NoMarkEdited, true);
6277 if (allow_opt_picker)
6278 {
6279 ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function
6280 PushItemWidth(picker_size.x);
6281 for (int picker_type = 0; picker_type < 2; picker_type++)
6282 {
6283 // Draw small/thumbnail version of each picker type (over an invisible button for selection)
6284 if (picker_type > 0) Separator();
6285 PushID(picker_type);
6286 ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_NoSidePreview | (flags & ImGuiColorEditFlags_NoAlpha);
6287 if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;
6288 if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;
6289 ImVec2 backup_pos = GetCursorScreenPos();
6290 if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
6291 g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags_PickerMask_) | (picker_flags & ImGuiColorEditFlags_PickerMask_);
6292 SetCursorScreenPos(backup_pos);
6293 ImVec4 previewing_ref_col;
6294 memcpy(&previewing_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4));
6295 ColorPicker4("##previewing_picker", &previewing_ref_col.x, picker_flags);
6296 PopID();
6297 }
6298 PopItemWidth();
6299 }
6300 if (allow_opt_alpha_bar)
6301 {
6302 if (allow_opt_picker) Separator();
6303 CheckboxFlags("Alpha Bar", &g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
6304 }
6305 PopItemFlag();
6306 EndPopup();
6307 }
6308
6309 //-------------------------------------------------------------------------
6310 // [SECTION] Widgets: TreeNode, CollapsingHeader, etc.
6311 //-------------------------------------------------------------------------
6312 // - TreeNode()
6313 // - TreeNodeV()
6314 // - TreeNodeEx()
6315 // - TreeNodeExV()
6316 // - TreeNodeBehavior() [Internal]
6317 // - TreePush()
6318 // - TreePop()
6319 // - GetTreeNodeToLabelSpacing()
6320 // - SetNextItemOpen()
6321 // - CollapsingHeader()
6322 //-------------------------------------------------------------------------
6323
6324 bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
6325 {
6326 va_list args;
6327 va_start(args, fmt);
6328 bool is_open = TreeNodeExV(str_id, 0, fmt, args);
6329 va_end(args);
6330 return is_open;
6331 }
6332
6333 bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
6334 {
6335 va_list args;
6336 va_start(args, fmt);
6337 bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
6338 va_end(args);
6339 return is_open;
6340 }
6341
6342 bool ImGui::TreeNode(const char* label)
6343 {
6344 ImGuiWindow* window = GetCurrentWindow();
6345 if (window->SkipItems)
6346 return false;
6347 ImGuiID id = window->GetID(label);
6348 return TreeNodeBehavior(id, ImGuiTreeNodeFlags_None, label, NULL);
6349 }
6350
6351 bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
6352 {
6353 return TreeNodeExV(str_id, 0, fmt, args);
6354 }
6355
6356 bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
6357 {
6358 return TreeNodeExV(ptr_id, 0, fmt, args);
6359 }
6360
6361 bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
6362 {
6363 ImGuiWindow* window = GetCurrentWindow();
6364 if (window->SkipItems)
6365 return false;
6366 ImGuiID id = window->GetID(label);
6367 return TreeNodeBehavior(id, flags, label, NULL);
6368 }
6369
6370 bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
6371 {
6372 va_list args;
6373 va_start(args, fmt);
6374 bool is_open = TreeNodeExV(str_id, flags, fmt, args);
6375 va_end(args);
6376 return is_open;
6377 }
6378
6379 bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
6380 {
6381 va_list args;
6382 va_start(args, fmt);
6383 bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
6384 va_end(args);
6385 return is_open;
6386 }
6387
6388 bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
6389 {
6390 ImGuiWindow* window = GetCurrentWindow();
6391 if (window->SkipItems)
6392 return false;
6393
6394 ImGuiID id = window->GetID(str_id);
6395 const char* label, *label_end;
6396 ImFormatStringToTempBufferV(&label, &label_end, fmt, args);
6397 return TreeNodeBehavior(id, flags, label, label_end);
6398 }
6399
6400 bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
6401 {
6402 ImGuiWindow* window = GetCurrentWindow();
6403 if (window->SkipItems)
6404 return false;
6405
6406 ImGuiID id = window->GetID(ptr_id);
6407 const char* label, *label_end;
6408 ImFormatStringToTempBufferV(&label, &label_end, fmt, args);
6409 return TreeNodeBehavior(id, flags, label, label_end);
6410 }
6411
6412 bool ImGui::TreeNodeGetOpen(ImGuiID storage_id)
6413 {
6414 ImGuiContext& g = *GImGui;
6415 ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage;
6416 return storage->GetInt(storage_id, 0) != 0;
6417 }
6418
6419 void ImGui::TreeNodeSetOpen(ImGuiID storage_id, bool open)
6420 {
6421 ImGuiContext& g = *GImGui;
6422 ImGuiStorage* storage = g.CurrentWindow->DC.StateStorage;
6423 storage->SetInt(storage_id, open ? 1 : 0);
6424 }
6425
6426 bool ImGui::TreeNodeUpdateNextOpen(ImGuiID storage_id, ImGuiTreeNodeFlags flags)
6427 {
6428 if (flags & ImGuiTreeNodeFlags_Leaf)
6429 return true;
6430
6431 // We only write to the tree storage if the user clicks, or explicitly use the SetNextItemOpen function
6432 ImGuiContext& g = *GImGui;
6433 ImGuiWindow* window = g.CurrentWindow;
6434 ImGuiStorage* storage = window->DC.StateStorage;
6435
6436 bool is_open;
6437 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasOpen)
6438 {
6439 if (g.NextItemData.OpenCond & ImGuiCond_Always)
6440 {
6441 is_open = g.NextItemData.OpenVal;
6442 TreeNodeSetOpen(storage_id, is_open);
6443 }
6444 else
6445 {
6446 // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
6447 const int stored_value = storage->GetInt(storage_id, -1);
6448 if (stored_value == -1)
6449 {
6450 is_open = g.NextItemData.OpenVal;
6451 TreeNodeSetOpen(storage_id, is_open);
6452 }
6453 else
6454 {
6455 is_open = stored_value != 0;
6456 }
6457 }
6458 }
6459 else
6460 {
6461 is_open = storage->GetInt(storage_id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
6462 }
6463
6464 // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
6465 // NB- If we are above max depth we still allow manually opened nodes to be logged.
6466 if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand)
6467 is_open = true;
6468
6469 return is_open;
6470 }
6471
6472 // Store ImGuiTreeNodeStackData for just submitted node.
6473 // Currently only supports 32 level deep and we are fine with (1 << Depth) overflowing into a zero, easy to increase.
6474 static void TreeNodeStoreStackData(ImGuiTreeNodeFlags flags)
6475 {
6476 ImGuiContext& g = *GImGui;
6477 ImGuiWindow* window = g.CurrentWindow;
6478
6479 g.TreeNodeStack.resize(g.TreeNodeStack.Size + 1);
6480 ImGuiTreeNodeStackData* tree_node_data = &g.TreeNodeStack.back();
6481 tree_node_data->ID = g.LastItemData.ID;
6482 tree_node_data->TreeFlags = flags;
6483 tree_node_data->ItemFlags = g.LastItemData.ItemFlags;
6484 tree_node_data->NavRect = g.LastItemData.NavRect;
6485 window->DC.TreeHasStackDataDepthMask |= (1 << window->DC.TreeDepth);
6486 }
6487
6488 // When using public API, currently 'id == storage_id' is always true, but we separate the values to facilitate advanced user code doing storage queries outside of UI loop.
6489 bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
6490 {
6491 ImGuiWindow* window = GetCurrentWindow();
6492 if (window->SkipItems)
6493 return false;
6494
6495 ImGuiContext& g = *GImGui;
6496 const ImGuiStyle& style = g.Style;
6497 const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
6498 const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, ImMin(window->DC.CurrLineTextBaseOffset, style.FramePadding.y));
6499
6500 if (!label_end)
6501 label_end = FindRenderedTextEnd(label);
6502 const ImVec2 label_size = CalcTextSize(label, label_end, false);
6503
6504 const float text_offset_x = g.FontSize + (display_frame ? padding.x * 3 : padding.x * 2); // Collapsing arrow width + Spacing
6505 const float text_offset_y = ImMax(padding.y, window->DC.CurrLineTextBaseOffset); // Latch before ItemSize changes it
6506 const float text_width = g.FontSize + label_size.x + padding.x * 2; // Include collapsing arrow
6507
6508 // We vertically grow up to current line height up the typical widget height.
6509 const float frame_height = ImMax(ImMin(window->DC.CurrLineSize.y, g.FontSize + style.FramePadding.y * 2), label_size.y + padding.y * 2);
6510 const bool span_all_columns = (flags & ImGuiTreeNodeFlags_SpanAllColumns) != 0 && (g.CurrentTable != NULL);
6511 ImRect frame_bb;
6512 frame_bb.Min.x = span_all_columns ? window->ParentWorkRect.Min.x : (flags & ImGuiTreeNodeFlags_SpanFullWidth) ? window->WorkRect.Min.x : window->DC.CursorPos.x;
6513 frame_bb.Min.y = window->DC.CursorPos.y;
6514 frame_bb.Max.x = span_all_columns ? window->ParentWorkRect.Max.x : (flags & ImGuiTreeNodeFlags_SpanTextWidth) ? window->DC.CursorPos.x + text_width + padding.x : window->WorkRect.Max.x;
6515 frame_bb.Max.y = window->DC.CursorPos.y + frame_height;
6516 if (display_frame)
6517 {
6518 const float outer_extend = IM_TRUNC(window->WindowPadding.x * 0.5f); // Framed header expand a little outside of current limits
6519 frame_bb.Min.x -= outer_extend;
6520 frame_bb.Max.x += outer_extend;
6521 }
6522
6523 ImVec2 text_pos(window->DC.CursorPos.x + text_offset_x, window->DC.CursorPos.y + text_offset_y);
6524 ItemSize(ImVec2(text_width, frame_height), padding.y);
6525
6526 // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
6527 ImRect interact_bb = frame_bb;
6528 if ((flags & (ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_SpanAvailWidth | ImGuiTreeNodeFlags_SpanFullWidth | ImGuiTreeNodeFlags_SpanTextWidth | ImGuiTreeNodeFlags_SpanAllColumns)) == 0)
6529 interact_bb.Max.x = frame_bb.Min.x + text_width + (label_size.x > 0.0f ? style.ItemSpacing.x * 2.0f : 0.0f);
6530
6531 // Compute open and multi-select states before ItemAdd() as it clear NextItem data.
6532 ImGuiID storage_id = (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasStorageID) ? g.NextItemData.StorageId : id;
6533 bool is_open = TreeNodeUpdateNextOpen(storage_id, flags);
6534
6535 bool is_visible;
6536 if (span_all_columns)
6537 {
6538 // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable..
6539 const float backup_clip_rect_min_x = window->ClipRect.Min.x;
6540 const float backup_clip_rect_max_x = window->ClipRect.Max.x;
6541 window->ClipRect.Min.x = window->ParentWorkRect.Min.x;
6542 window->ClipRect.Max.x = window->ParentWorkRect.Max.x;
6543 is_visible = ItemAdd(interact_bb, id);
6544 window->ClipRect.Min.x = backup_clip_rect_min_x;
6545 window->ClipRect.Max.x = backup_clip_rect_max_x;
6546 }
6547 else
6548 {
6549 is_visible = ItemAdd(interact_bb, id);
6550 }
6551 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
6552 g.LastItemData.DisplayRect = frame_bb;
6553
6554 // If a NavLeft request is happening and ImGuiTreeNodeFlags_NavLeftJumpsBackHere enabled:
6555 // Store data for the current depth to allow returning to this node from any child item.
6556 // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
6557 // It will become tempting to enable ImGuiTreeNodeFlags_NavLeftJumpsBackHere by default or move it to ImGuiStyle.
6558 bool store_tree_node_stack_data = false;
6559 if (!(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
6560 {
6561 if ((flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && is_open && !g.NavIdIsAlive)
6562 if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
6563 store_tree_node_stack_data = true;
6564 }
6565
6566 const bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0;
6567 if (!is_visible)
6568 {
6569 if (store_tree_node_stack_data && is_open)
6570 TreeNodeStoreStackData(flags); // Call before TreePushOverrideID()
6571 if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
6572 TreePushOverrideID(id);
6573 IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
6574 return is_open;
6575 }
6576
6577 if (span_all_columns)
6578 {
6579 TablePushBackgroundChannel();
6580 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasClipRect;
6581 g.LastItemData.ClipRect = window->ClipRect;
6582 }
6583
6584 ImGuiButtonFlags button_flags = ImGuiTreeNodeFlags_None;
6585 if ((flags & ImGuiTreeNodeFlags_AllowOverlap) || (g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap))
6586 button_flags |= ImGuiButtonFlags_AllowOverlap;
6587 if (!is_leaf)
6588 button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
6589
6590 // We allow clicking on the arrow section with keyboard modifiers held, in order to easily
6591 // allow browsing a tree while preserving selection with code implementing multi-selection patterns.
6592 // When clicking on the rest of the tree node we always disallow keyboard modifiers.
6593 const float arrow_hit_x1 = (text_pos.x - text_offset_x) - style.TouchExtraPadding.x;
6594 const float arrow_hit_x2 = (text_pos.x - text_offset_x) + (g.FontSize + padding.x * 2.0f) + style.TouchExtraPadding.x;
6595 const bool is_mouse_x_over_arrow = (g.IO.MousePos.x >= arrow_hit_x1 && g.IO.MousePos.x < arrow_hit_x2);
6596
6597 const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
6598 if (is_multi_select) // We absolutely need to distinguish open vs select so _OpenOnArrow comes by default
6599 flags |= (flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 ? ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick : ImGuiTreeNodeFlags_OpenOnArrow;
6600
6601 // Open behaviors can be altered with the _OpenOnArrow and _OnOnDoubleClick flags.
6602 // Some alteration have subtle effects (e.g. toggle on MouseUp vs MouseDown events) due to requirements for multi-selection and drag and drop support.
6603 // - Single-click on label = Toggle on MouseUp (default, when _OpenOnArrow=0)
6604 // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=0)
6605 // - Single-click on arrow = Toggle on MouseDown (when _OpenOnArrow=1)
6606 // - Double-click on label = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1)
6607 // - Double-click on arrow = Toggle on MouseDoubleClick (when _OpenOnDoubleClick=1 and _OpenOnArrow=0)
6608 // It is rather standard that arrow click react on Down rather than Up.
6609 // We set ImGuiButtonFlags_PressedOnClickRelease on OpenOnDoubleClick because we want the item to be active on the initial MouseDown in order for drag and drop to work.
6610 if (is_mouse_x_over_arrow)
6611 button_flags |= ImGuiButtonFlags_PressedOnClick;
6612 else if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
6613 button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
6614 else
6615 button_flags |= ImGuiButtonFlags_PressedOnClickRelease;
6616
6617 bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0;
6618 const bool was_selected = selected;
6619
6620 // Multi-selection support (header)
6621 if (is_multi_select)
6622 {
6623 // Handle multi-select + alter button flags for it
6624 MultiSelectItemHeader(id, &selected, &button_flags);
6625 if (is_mouse_x_over_arrow)
6626 button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease;
6627 }
6628 else
6629 {
6630 if (window != g.HoveredWindow || !is_mouse_x_over_arrow)
6631 button_flags |= ImGuiButtonFlags_NoKeyModsAllowed;
6632 }
6633
6634 bool hovered, held;
6635 bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
6636 bool toggled = false;
6637 if (!is_leaf)
6638 {
6639 if (pressed && g.DragDropHoldJustPressedId != id)
6640 {
6641 if ((flags & ImGuiTreeNodeFlags_OpenOnMask_) == 0 || (g.NavActivateId == id && !is_multi_select))
6642 toggled = true; // Single click
6643 if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
6644 toggled |= is_mouse_x_over_arrow && !g.NavHighlightItemUnderNav; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job
6645 if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)
6646 toggled = true; // Double click
6647 }
6648 else if (pressed && g.DragDropHoldJustPressedId == id)
6649 {
6650 IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);
6651 if (!is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
6652 toggled = true;
6653 else
6654 pressed = false; // Cancel press so it doesn't trigger selection.
6655 }
6656
6657 if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)
6658 {
6659 toggled = true;
6660 NavClearPreferredPosForAxis(ImGuiAxis_X);
6661 NavMoveRequestCancel();
6662 }
6663 if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?
6664 {
6665 toggled = true;
6666 NavClearPreferredPosForAxis(ImGuiAxis_X);
6667 NavMoveRequestCancel();
6668 }
6669
6670 if (toggled)
6671 {
6672 is_open = !is_open;
6673 window->DC.StateStorage->SetInt(storage_id, is_open);
6674 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen;
6675 }
6676 }
6677
6678 // Multi-selection support (footer)
6679 if (is_multi_select)
6680 {
6681 bool pressed_copy = pressed && !toggled;
6682 MultiSelectItemFooter(id, &selected, &pressed_copy);
6683 if (pressed)
6684 SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, interact_bb);
6685 }
6686
6687 if (selected != was_selected)
6688 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;
6689
6690 // Render
6691 {
6692 const ImU32 text_col = GetColorU32(ImGuiCol_Text);
6693 ImGuiNavRenderCursorFlags nav_render_cursor_flags = ImGuiNavRenderCursorFlags_Compact;
6694 if (is_multi_select)
6695 nav_render_cursor_flags |= ImGuiNavRenderCursorFlags_AlwaysDraw; // Always show the nav rectangle
6696 if (display_frame)
6697 {
6698 // Framed type
6699 const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
6700 RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, true, style.FrameRounding);
6701 RenderNavCursor(frame_bb, id, nav_render_cursor_flags);
6702 if (flags & ImGuiTreeNodeFlags_Bullet)
6703 RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.60f, text_pos.y + g.FontSize * 0.5f), text_col);
6704 else if (!is_leaf)
6705 RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 1.0f);
6706 else // Leaf without bullet, left-adjusted text
6707 text_pos.x -= text_offset_x - padding.x;
6708 if (flags & ImGuiTreeNodeFlags_ClipLabelForTrailingButton)
6709 frame_bb.Max.x -= g.FontSize + style.FramePadding.x;
6710 if (g.LogEnabled)
6711 LogSetNextTextDecoration("###", "###");
6712 }
6713 else
6714 {
6715 // Unframed typed for tree nodes
6716 if (hovered || selected)
6717 {
6718 const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
6719 RenderFrame(frame_bb.Min, frame_bb.Max, bg_col, false);
6720 }
6721 RenderNavCursor(frame_bb, id, nav_render_cursor_flags);
6722 if (flags & ImGuiTreeNodeFlags_Bullet)
6723 RenderBullet(window->DrawList, ImVec2(text_pos.x - text_offset_x * 0.5f, text_pos.y + g.FontSize * 0.5f), text_col);
6724 else if (!is_leaf)
6725 RenderArrow(window->DrawList, ImVec2(text_pos.x - text_offset_x + padding.x, text_pos.y + g.FontSize * 0.15f), text_col, is_open ? ((flags & ImGuiTreeNodeFlags_UpsideDownArrow) ? ImGuiDir_Up : ImGuiDir_Down) : ImGuiDir_Right, 0.70f);
6726 if (g.LogEnabled)
6727 LogSetNextTextDecoration(">", NULL);
6728 }
6729
6730 if (span_all_columns)
6731 TablePopBackgroundChannel();
6732
6733 // Label
6734 if (display_frame)
6735 RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
6736 else
6737 RenderText(text_pos, label, label_end, false);
6738 }
6739
6740 if (store_tree_node_stack_data && is_open)
6741 TreeNodeStoreStackData(flags); // Call before TreePushOverrideID()
6742 if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
6743 TreePushOverrideID(id); // Could use TreePush(label) but this avoid computing twice
6744
6745 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0));
6746 return is_open;
6747 }
6748
6749 void ImGui::TreePush(const char* str_id)
6750 {
6751 ImGuiWindow* window = GetCurrentWindow();
6752 Indent();
6753 window->DC.TreeDepth++;
6754 PushID(str_id);
6755 }
6756
6757 void ImGui::TreePush(const void* ptr_id)
6758 {
6759 ImGuiWindow* window = GetCurrentWindow();
6760 Indent();
6761 window->DC.TreeDepth++;
6762 PushID(ptr_id);
6763 }
6764
6765 void ImGui::TreePushOverrideID(ImGuiID id)
6766 {
6767 ImGuiContext& g = *GImGui;
6768 ImGuiWindow* window = g.CurrentWindow;
6769 Indent();
6770 window->DC.TreeDepth++;
6771 PushOverrideID(id);
6772 }
6773
6774 void ImGui::TreePop()
6775 {
6776 ImGuiContext& g = *GImGui;
6777 ImGuiWindow* window = g.CurrentWindow;
6778 Unindent();
6779
6780 window->DC.TreeDepth--;
6781 ImU32 tree_depth_mask = (1 << window->DC.TreeDepth);
6782
6783 if (window->DC.TreeHasStackDataDepthMask & tree_depth_mask) // Only set during request
6784 {
6785 ImGuiTreeNodeStackData* data = &g.TreeNodeStack.back();
6786 IM_ASSERT(data->ID == window->IDStack.back());
6787 if (data->TreeFlags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere)
6788 {
6789 // Handle Left arrow to move to parent tree node (when ImGuiTreeNodeFlags_NavLeftJumpsBackHere is enabled)
6790 if (g.NavIdIsAlive && g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
6791 NavMoveRequestResolveWithPastTreeNode(&g.NavMoveResultLocal, data);
6792 }
6793 g.TreeNodeStack.pop_back();
6794 window->DC.TreeHasStackDataDepthMask &= ~tree_depth_mask;
6795 }
6796
6797 IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much.
6798 PopID();
6799 }
6800
6801 // Horizontal distance preceding label when using TreeNode() or Bullet()
6802 float ImGui::GetTreeNodeToLabelSpacing()
6803 {
6804 ImGuiContext& g = *GImGui;
6805 return g.FontSize + (g.Style.FramePadding.x * 2.0f);
6806 }
6807
6808 // Set next TreeNode/CollapsingHeader open state.
6809 void ImGui::SetNextItemOpen(bool is_open, ImGuiCond cond)
6810 {
6811 ImGuiContext& g = *GImGui;
6812 if (g.CurrentWindow->SkipItems)
6813 return;
6814 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasOpen;
6815 g.NextItemData.OpenVal = is_open;
6816 g.NextItemData.OpenCond = (ImU8)(cond ? cond : ImGuiCond_Always);
6817 }
6818
6819 // Set next TreeNode/CollapsingHeader storage id.
6820 void ImGui::SetNextItemStorageID(ImGuiID storage_id)
6821 {
6822 ImGuiContext& g = *GImGui;
6823 if (g.CurrentWindow->SkipItems)
6824 return;
6825 g.NextItemData.HasFlags |= ImGuiNextItemDataFlags_HasStorageID;
6826 g.NextItemData.StorageId = storage_id;
6827 }
6828
6829 // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
6830 // This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode().
6831 bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
6832 {
6833 ImGuiWindow* window = GetCurrentWindow();
6834 if (window->SkipItems)
6835 return false;
6836 ImGuiID id = window->GetID(label);
6837 return TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader, label);
6838 }
6839
6840 // p_visible == NULL : regular collapsing header
6841 // p_visible != NULL && *p_visible == true : show a small close button on the corner of the header, clicking the button will set *p_visible = false
6842 // p_visible != NULL && *p_visible == false : do not show the header at all
6843 // Do not mistake this with the Open state of the header itself, which you can adjust with SetNextItemOpen() or ImGuiTreeNodeFlags_DefaultOpen.
6844 bool ImGui::CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags)
6845 {
6846 ImGuiWindow* window = GetCurrentWindow();
6847 if (window->SkipItems)
6848 return false;
6849
6850 if (p_visible && !*p_visible)
6851 return false;
6852
6853 ImGuiID id = window->GetID(label);
6854 flags |= ImGuiTreeNodeFlags_CollapsingHeader;
6855 if (p_visible)
6856 flags |= ImGuiTreeNodeFlags_AllowOverlap | (ImGuiTreeNodeFlags)ImGuiTreeNodeFlags_ClipLabelForTrailingButton;
6857 bool is_open = TreeNodeBehavior(id, flags, label);
6858 if (p_visible != NULL)
6859 {
6860 // Create a small overlapping close button
6861 // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
6862 // FIXME: CloseButton can overlap into text, need find a way to clip the text somehow.
6863 ImGuiContext& g = *GImGui;
6864 ImGuiLastItemData last_item_backup = g.LastItemData;
6865 float button_size = g.FontSize;
6866 float button_x = ImMax(g.LastItemData.Rect.Min.x, g.LastItemData.Rect.Max.x - g.Style.FramePadding.x - button_size);
6867 float button_y = g.LastItemData.Rect.Min.y + g.Style.FramePadding.y;
6868 ImGuiID close_button_id = GetIDWithSeed("#CLOSE", NULL, id);
6869 if (CloseButton(close_button_id, ImVec2(button_x, button_y)))
6870 *p_visible = false;
6871 g.LastItemData = last_item_backup;
6872 }
6873
6874 return is_open;
6875 }
6876
6877 //-------------------------------------------------------------------------
6878 // [SECTION] Widgets: Selectable
6879 //-------------------------------------------------------------------------
6880 // - Selectable()
6881 //-------------------------------------------------------------------------
6882
6883 // Tip: pass a non-visible label (e.g. "##hello") then you can use the space to draw other text or image.
6884 // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id.
6885 // With this scheme, ImGuiSelectableFlags_SpanAllColumns and ImGuiSelectableFlags_AllowOverlap are also frequently used flags.
6886 // FIXME: Selectable() with (size.x == 0.0f) and (SelectableTextAlign.x > 0.0f) followed by SameLine() is currently not supported.
6887 bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
6888 {
6889 ImGuiWindow* window = GetCurrentWindow();
6890 if (window->SkipItems)
6891 return false;
6892
6893 ImGuiContext& g = *GImGui;
6894 const ImGuiStyle& style = g.Style;
6895
6896 // Submit label or explicit size to ItemSize(), whereas ItemAdd() will submit a larger/spanning rectangle.
6897 ImGuiID id = window->GetID(label);
6898 ImVec2 label_size = CalcTextSize(label, NULL, true);
6899 ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
6900 ImVec2 pos = window->DC.CursorPos;
6901 pos.y += window->DC.CurrLineTextBaseOffset;
6902 ItemSize(size, 0.0f);
6903
6904 // Fill horizontal space
6905 // We don't support (size < 0.0f) in Selectable() because the ItemSpacing extension would make explicitly right-aligned sizes not visibly match other widgets.
6906 const bool span_all_columns = (flags & ImGuiSelectableFlags_SpanAllColumns) != 0;
6907 const float min_x = span_all_columns ? window->ParentWorkRect.Min.x : pos.x;
6908 const float max_x = span_all_columns ? window->ParentWorkRect.Max.x : window->WorkRect.Max.x;
6909 if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_SpanAvailWidth))
6910 size.x = ImMax(label_size.x, max_x - min_x);
6911
6912 // Text stays at the submission position, but bounding box may be extended on both sides
6913 const ImVec2 text_min = pos;
6914 const ImVec2 text_max(min_x + size.x, pos.y + size.y);
6915
6916 // Selectables are meant to be tightly packed together with no click-gap, so we extend their box to cover spacing between selectable.
6917 // FIXME: Not part of layout so not included in clipper calculation, but ItemSize currently doesn't allow offsetting CursorPos.
6918 ImRect bb(min_x, pos.y, text_max.x, text_max.y);
6919 if ((flags & ImGuiSelectableFlags_NoPadWithHalfSpacing) == 0)
6920 {
6921 const float spacing_x = span_all_columns ? 0.0f : style.ItemSpacing.x;
6922 const float spacing_y = style.ItemSpacing.y;
6923 const float spacing_L = IM_TRUNC(spacing_x * 0.50f);
6924 const float spacing_U = IM_TRUNC(spacing_y * 0.50f);
6925 bb.Min.x -= spacing_L;
6926 bb.Min.y -= spacing_U;
6927 bb.Max.x += (spacing_x - spacing_L);
6928 bb.Max.y += (spacing_y - spacing_U);
6929 }
6930 //if (g.IO.KeyCtrl) { GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(0, 255, 0, 255)); }
6931
6932 const bool disabled_item = (flags & ImGuiSelectableFlags_Disabled) != 0;
6933 const ImGuiItemFlags extra_item_flags = disabled_item ? (ImGuiItemFlags)ImGuiItemFlags_Disabled : ImGuiItemFlags_None;
6934 bool is_visible;
6935 if (span_all_columns)
6936 {
6937 // Modify ClipRect for the ItemAdd(), faster than doing a PushColumnsBackground/PushTableBackgroundChannel for every Selectable..
6938 const float backup_clip_rect_min_x = window->ClipRect.Min.x;
6939 const float backup_clip_rect_max_x = window->ClipRect.Max.x;
6940 window->ClipRect.Min.x = window->ParentWorkRect.Min.x;
6941 window->ClipRect.Max.x = window->ParentWorkRect.Max.x;
6942 is_visible = ItemAdd(bb, id, NULL, extra_item_flags);
6943 window->ClipRect.Min.x = backup_clip_rect_min_x;
6944 window->ClipRect.Max.x = backup_clip_rect_max_x;
6945 }
6946 else
6947 {
6948 is_visible = ItemAdd(bb, id, NULL, extra_item_flags);
6949 }
6950
6951 const bool is_multi_select = (g.LastItemData.ItemFlags & ImGuiItemFlags_IsMultiSelect) != 0;
6952 if (!is_visible)
6953 if (!is_multi_select || !g.BoxSelectState.UnclipMode || !g.BoxSelectState.UnclipRect.Overlaps(bb)) // Extra layer of "no logic clip" for box-select support (would be more overhead to add to ItemAdd)
6954 return false;
6955
6956 const bool disabled_global = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
6957 if (disabled_item && !disabled_global) // Only testing this as an optimization
6958 BeginDisabled();
6959
6960 // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,
6961 // which would be advantageous since most selectable are not selected.
6962 if (span_all_columns)
6963 {
6964 if (g.CurrentTable)
6965 TablePushBackgroundChannel();
6966 else if (window->DC.CurrentColumns)
6967 PushColumnsBackground();
6968 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasClipRect;
6969 g.LastItemData.ClipRect = window->ClipRect;
6970 }
6971
6972 // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries
6973 ImGuiButtonFlags button_flags = 0;
6974 if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }
6975 if (flags & ImGuiSelectableFlags_NoSetKeyOwner) { button_flags |= ImGuiButtonFlags_NoSetKeyOwner; }
6976 if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; }
6977 if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; }
6978 if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }
6979 if ((flags & ImGuiSelectableFlags_AllowOverlap) || (g.LastItemData.ItemFlags & ImGuiItemFlags_AllowOverlap)) { button_flags |= ImGuiButtonFlags_AllowOverlap; }
6980
6981 // Multi-selection support (header)
6982 const bool was_selected = selected;
6983 if (is_multi_select)
6984 {
6985 // Handle multi-select + alter button flags for it
6986 MultiSelectItemHeader(id, &selected, &button_flags);
6987 }
6988
6989 bool hovered, held;
6990 bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
6991
6992 // Multi-selection support (footer)
6993 if (is_multi_select)
6994 {
6995 MultiSelectItemFooter(id, &selected, &pressed);
6996 }
6997 else
6998 {
6999 // Auto-select when moved into
7000 // - This will be more fully fleshed in the range-select branch
7001 // - This is not exposed as it won't nicely work with some user side handling of shift/control
7002 // - We cannot do 'if (g.NavJustMovedToId != id) { selected = false; pressed = was_selected; }' for two reasons
7003 // - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope())
7004 // - (2) usage will fail with clipped items
7005 // The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API.
7006 if ((flags & ImGuiSelectableFlags_SelectOnNav) && g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == g.CurrentFocusScopeId)
7007 if (g.NavJustMovedToId == id)
7008 selected = pressed = true;
7009 }
7010
7011 // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with keyboard/gamepad
7012 if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))
7013 {
7014 if (!g.NavHighlightItemUnderNav && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)
7015 {
7016 SetNavID(id, window->DC.NavLayerCurrent, g.CurrentFocusScopeId, WindowRectAbsToRel(window, bb)); // (bb == NavRect)
7017 if (g.IO.ConfigNavCursorVisibleAuto)
7018 g.NavCursorVisible = false;
7019 }
7020 }
7021 if (pressed)
7022 MarkItemEdited(id);
7023
7024 if (selected != was_selected)
7025 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;
7026
7027 // Render
7028 if (is_visible)
7029 {
7030 const bool highlighted = hovered || (flags & ImGuiSelectableFlags_Highlight);
7031 if (highlighted || selected)
7032 {
7033 // Between 1.91.0 and 1.91.4 we made selected Selectable use an arbitrary lerp between _Header and _HeaderHovered. Removed that now. (#8106)
7034 ImU32 col = GetColorU32((held && highlighted) ? ImGuiCol_HeaderActive : highlighted ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
7035 RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
7036 }
7037 if (g.NavId == id)
7038 {
7039 ImGuiNavRenderCursorFlags nav_render_cursor_flags = ImGuiNavRenderCursorFlags_Compact | ImGuiNavRenderCursorFlags_NoRounding;
7040 if (is_multi_select)
7041 nav_render_cursor_flags |= ImGuiNavRenderCursorFlags_AlwaysDraw; // Always show the nav rectangle
7042 RenderNavCursor(bb, id, nav_render_cursor_flags);
7043 }
7044 }
7045
7046 if (span_all_columns)
7047 {
7048 if (g.CurrentTable)
7049 TablePopBackgroundChannel();
7050 else if (window->DC.CurrentColumns)
7051 PopColumnsBackground();
7052 }
7053
7054 if (is_visible)
7055 RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb);
7056
7057 // Automatically close popups
7058 if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_NoAutoClosePopups) && (g.LastItemData.ItemFlags & ImGuiItemFlags_AutoClosePopups))
7059 CloseCurrentPopup();
7060
7061 if (disabled_item && !disabled_global)
7062 EndDisabled();
7063
7064 // Selectable() always returns a pressed state!
7065 // Users of BeginMultiSelect()/EndMultiSelect() scope: you may call ImGui::IsItemToggledSelection() to retrieve
7066 // selection toggle, only useful if you need that state updated (e.g. for rendering purpose) before reaching EndMultiSelect().
7067 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
7068 return pressed; //-V1020
7069 }
7070
7071 bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
7072 {
7073 if (Selectable(label, *p_selected, flags, size_arg))
7074 {
7075 *p_selected = !*p_selected;
7076 return true;
7077 }
7078 return false;
7079 }
7080
7081
7082 //-------------------------------------------------------------------------
7083 // [SECTION] Widgets: Typing-Select support
7084 //-------------------------------------------------------------------------
7085
7086 // [Experimental] Currently not exposed in public API.
7087 // Consume character inputs and return search request, if any.
7088 // This would typically only be called on the focused window or location you want to grab inputs for, e.g.
7089 // if (ImGui::IsWindowFocused(...))
7090 // if (ImGuiTypingSelectRequest* req = ImGui::GetTypingSelectRequest())
7091 // focus_idx = ImGui::TypingSelectFindMatch(req, my_items.size(), [](void*, int n) { return my_items[n]->Name; }, &my_items, -1);
7092 // However the code is written in a way where calling it from multiple locations is safe (e.g. to obtain buffer).
7093 ImGuiTypingSelectRequest* ImGui::GetTypingSelectRequest(ImGuiTypingSelectFlags flags)
7094 {
7095 ImGuiContext& g = *GImGui;
7096 ImGuiTypingSelectState* data = &g.TypingSelectState;
7097 ImGuiTypingSelectRequest* out_request = &data->Request;
7098
7099 // Clear buffer
7100 const float TYPING_SELECT_RESET_TIMER = 1.80f; // FIXME: Potentially move to IO config.
7101 const int TYPING_SELECT_SINGLE_CHAR_COUNT_FOR_LOCK = 4; // Lock single char matching when repeating same char 4 times
7102 if (data->SearchBuffer[0] != 0)
7103 {
7104 bool clear_buffer = false;
7105 clear_buffer |= (g.NavFocusScopeId != data->FocusScope);
7106 clear_buffer |= (data->LastRequestTime + TYPING_SELECT_RESET_TIMER < g.Time);
7107 clear_buffer |= g.NavAnyRequest;
7108 clear_buffer |= g.ActiveId != 0 && g.NavActivateId == 0; // Allow temporary SPACE activation to not interfere
7109 clear_buffer |= IsKeyPressed(ImGuiKey_Escape) || IsKeyPressed(ImGuiKey_Enter);
7110 clear_buffer |= IsKeyPressed(ImGuiKey_Backspace) && (flags & ImGuiTypingSelectFlags_AllowBackspace) == 0;
7111 //if (clear_buffer) { IMGUI_DEBUG_LOG("GetTypingSelectRequest(): Clear SearchBuffer.\n"); }
7112 if (clear_buffer)
7113 data->Clear();
7114 }
7115
7116 // Append to buffer
7117 const int buffer_max_len = IM_ARRAYSIZE(data->SearchBuffer) - 1;
7118 int buffer_len = (int)strlen(data->SearchBuffer);
7119 bool select_request = false;
7120 for (ImWchar w : g.IO.InputQueueCharacters)
7121 {
7122 const int w_len = ImTextCountUtf8BytesFromStr(&w, &w + 1);
7123 if (w < 32 || (buffer_len == 0 && ImCharIsBlankW(w)) || (buffer_len + w_len > buffer_max_len)) // Ignore leading blanks
7124 continue;
7125 char w_buf[5];
7126 ImTextCharToUtf8(w_buf, (unsigned int)w);
7127 if (data->SingleCharModeLock && w_len == out_request->SingleCharSize && memcmp(w_buf, data->SearchBuffer, w_len) == 0)
7128 {
7129 select_request = true; // Same character: don't need to append to buffer.
7130 continue;
7131 }
7132 if (data->SingleCharModeLock)
7133 {
7134 data->Clear(); // Different character: clear
7135 buffer_len = 0;
7136 }
7137 memcpy(data->SearchBuffer + buffer_len, w_buf, w_len + 1); // Append
7138 buffer_len += w_len;
7139 select_request = true;
7140 }
7141 g.IO.InputQueueCharacters.resize(0);
7142
7143 // Handle backspace
7144 if ((flags & ImGuiTypingSelectFlags_AllowBackspace) && IsKeyPressed(ImGuiKey_Backspace, ImGuiInputFlags_Repeat))
7145 {
7146 char* p = (char*)(void*)ImTextFindPreviousUtf8Codepoint(data->SearchBuffer, data->SearchBuffer + buffer_len);
7147 *p = 0;
7148 buffer_len = (int)(p - data->SearchBuffer);
7149 }
7150
7151 // Return request if any
7152 if (buffer_len == 0)
7153 return NULL;
7154 if (select_request)
7155 {
7156 data->FocusScope = g.NavFocusScopeId;
7157 data->LastRequestFrame = g.FrameCount;
7158 data->LastRequestTime = (float)g.Time;
7159 }
7160 out_request->Flags = flags;
7161 out_request->SearchBufferLen = buffer_len;
7162 out_request->SearchBuffer = data->SearchBuffer;
7163 out_request->SelectRequest = (data->LastRequestFrame == g.FrameCount);
7164 out_request->SingleCharMode = false;
7165 out_request->SingleCharSize = 0;
7166
7167 // Calculate if buffer contains the same character repeated.
7168 // - This can be used to implement a special search mode on first character.
7169 // - Performed on UTF-8 codepoint for correctness.
7170 // - SingleCharMode is always set for first input character, because it usually leads to a "next".
7171 if (flags & ImGuiTypingSelectFlags_AllowSingleCharMode)
7172 {
7173 const char* buf_begin = out_request->SearchBuffer;
7174 const char* buf_end = out_request->SearchBuffer + out_request->SearchBufferLen;
7175 const int c0_len = ImTextCountUtf8BytesFromChar(buf_begin, buf_end);
7176 const char* p = buf_begin + c0_len;
7177 for (; p < buf_end; p += c0_len)
7178 if (memcmp(buf_begin, p, (size_t)c0_len) != 0)
7179 break;
7180 const int single_char_count = (p == buf_end) ? (out_request->SearchBufferLen / c0_len) : 0;
7181 out_request->SingleCharMode = (single_char_count > 0 || data->SingleCharModeLock);
7182 out_request->SingleCharSize = (ImS8)c0_len;
7183 data->SingleCharModeLock |= (single_char_count >= TYPING_SELECT_SINGLE_CHAR_COUNT_FOR_LOCK); // From now on we stop search matching to lock to single char mode.
7184 }
7185
7186 return out_request;
7187 }
7188
7189 static int ImStrimatchlen(const char* s1, const char* s1_end, const char* s2)
7190 {
7191 int match_len = 0;
7192 while (s1 < s1_end && ImToUpper(*s1++) == ImToUpper(*s2++))
7193 match_len++;
7194 return match_len;
7195 }
7196
7197 // Default handler for finding a result for typing-select. You may implement your own.
7198 // You might want to display a tooltip to visualize the current request SearchBuffer
7199 // When SingleCharMode is set:
7200 // - it is better to NOT display a tooltip of other on-screen display indicator.
7201 // - the index of the currently focused item is required.
7202 // if your SetNextItemSelectionUserData() values are indices, you can obtain it from ImGuiMultiSelectIO::NavIdItem, otherwise from g.NavLastValidSelectionUserData.
7203 int ImGui::TypingSelectFindMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx)
7204 {
7205 if (req == NULL || req->SelectRequest == false) // Support NULL parameter so both calls can be done from same spot.
7206 return -1;
7207 int idx = -1;
7208 if (req->SingleCharMode && (req->Flags & ImGuiTypingSelectFlags_AllowSingleCharMode))
7209 idx = TypingSelectFindNextSingleCharMatch(req, items_count, get_item_name_func, user_data, nav_item_idx);
7210 else
7211 idx = TypingSelectFindBestLeadingMatch(req, items_count, get_item_name_func, user_data);
7212 if (idx != -1)
7213 SetNavCursorVisibleAfterMove();
7214 return idx;
7215 }
7216
7217 // Special handling when a single character is repeated: perform search on a single letter and goes to next.
7218 int ImGui::TypingSelectFindNextSingleCharMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data, int nav_item_idx)
7219 {
7220 // FIXME: Assume selection user data is index. Would be extremely practical.
7221 //if (nav_item_idx == -1)
7222 // nav_item_idx = (int)g.NavLastValidSelectionUserData;
7223
7224 int first_match_idx = -1;
7225 bool return_next_match = false;
7226 for (int idx = 0; idx < items_count; idx++)
7227 {
7228 const char* item_name = get_item_name_func(user_data, idx);
7229 if (ImStrimatchlen(req->SearchBuffer, req->SearchBuffer + req->SingleCharSize, item_name) < req->SingleCharSize)
7230 continue;
7231 if (return_next_match) // Return next matching item after current item.
7232 return idx;
7233 if (first_match_idx == -1 && nav_item_idx == -1) // Return first match immediately if we don't have a nav_item_idx value.
7234 return idx;
7235 if (first_match_idx == -1) // Record first match for wrapping.
7236 first_match_idx = idx;
7237 if (nav_item_idx == idx) // Record that we encountering nav_item so we can return next match.
7238 return_next_match = true;
7239 }
7240 return first_match_idx; // First result
7241 }
7242
7243 int ImGui::TypingSelectFindBestLeadingMatch(ImGuiTypingSelectRequest* req, int items_count, const char* (*get_item_name_func)(void*, int), void* user_data)
7244 {
7245 int longest_match_idx = -1;
7246 int longest_match_len = 0;
7247 for (int idx = 0; idx < items_count; idx++)
7248 {
7249 const char* item_name = get_item_name_func(user_data, idx);
7250 const int match_len = ImStrimatchlen(req->SearchBuffer, req->SearchBuffer + req->SearchBufferLen, item_name);
7251 if (match_len <= longest_match_len)
7252 continue;
7253 longest_match_idx = idx;
7254 longest_match_len = match_len;
7255 if (match_len == req->SearchBufferLen)
7256 break;
7257 }
7258 return longest_match_idx;
7259 }
7260
7261 void ImGui::DebugNodeTypingSelectState(ImGuiTypingSelectState* data)
7262 {
7263 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
7264 Text("SearchBuffer = \"%s\"", data->SearchBuffer);
7265 Text("SingleCharMode = %d, Size = %d, Lock = %d", data->Request.SingleCharMode, data->Request.SingleCharSize, data->SingleCharModeLock);
7266 Text("LastRequest = time: %.2f, frame: %d", data->LastRequestTime, data->LastRequestFrame);
7267 #else
7268 IM_UNUSED(data);
7269 #endif
7270 }
7271
7272 //-------------------------------------------------------------------------
7273 // [SECTION] Widgets: Box-Select support
7274 // This has been extracted away from Multi-Select logic in the hope that it could eventually be used elsewhere, but hasn't been yet.
7275 //-------------------------------------------------------------------------
7276 // Extra logic in MultiSelectItemFooter() and ImGuiListClipper::Step()
7277 //-------------------------------------------------------------------------
7278 // - BoxSelectPreStartDrag() [Internal]
7279 // - BoxSelectActivateDrag() [Internal]
7280 // - BoxSelectDeactivateDrag() [Internal]
7281 // - BoxSelectScrollWithMouseDrag() [Internal]
7282 // - BeginBoxSelect() [Internal]
7283 // - EndBoxSelect() [Internal]
7284 //-------------------------------------------------------------------------
7285
7286 // Call on the initial click.
7287 static void BoxSelectPreStartDrag(ImGuiID id, ImGuiSelectionUserData clicked_item)
7288 {
7289 ImGuiContext& g = *GImGui;
7290 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7291 bs->ID = id;
7292 bs->IsStarting = true; // Consider starting box-select.
7293 bs->IsStartedFromVoid = (clicked_item == ImGuiSelectionUserData_Invalid);
7294 bs->IsStartedSetNavIdOnce = bs->IsStartedFromVoid;
7295 bs->KeyMods = g.IO.KeyMods;
7296 bs->StartPosRel = bs->EndPosRel = ImGui::WindowPosAbsToRel(g.CurrentWindow, g.IO.MousePos);
7297 bs->ScrollAccum = ImVec2(0.0f, 0.0f);
7298 }
7299
7300 static void BoxSelectActivateDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window)
7301 {
7302 ImGuiContext& g = *GImGui;
7303 IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Activate\n", bs->ID);
7304 bs->IsActive = true;
7305 bs->Window = window;
7306 bs->IsStarting = false;
7307 ImGui::SetActiveID(bs->ID, window);
7308 ImGui::SetActiveIdUsingAllKeyboardKeys();
7309 if (bs->IsStartedFromVoid && (bs->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0)
7310 bs->RequestClear = true;
7311 }
7312
7313 static void BoxSelectDeactivateDrag(ImGuiBoxSelectState* bs)
7314 {
7315 ImGuiContext& g = *GImGui;
7316 bs->IsActive = bs->IsStarting = false;
7317 if (g.ActiveId == bs->ID)
7318 {
7319 IMGUI_DEBUG_LOG_SELECTION("[selection] BeginBoxSelect() 0X%08X: Deactivate\n", bs->ID);
7320 ImGui::ClearActiveID();
7321 }
7322 bs->ID = 0;
7323 }
7324
7325 static void BoxSelectScrollWithMouseDrag(ImGuiBoxSelectState* bs, ImGuiWindow* window, const ImRect& inner_r)
7326 {
7327 ImGuiContext& g = *GImGui;
7328 IM_ASSERT(bs->Window == window);
7329 for (int n = 0; n < 2; n++) // each axis
7330 {
7331 const float mouse_pos = g.IO.MousePos[n];
7332 const float dist = (mouse_pos > inner_r.Max[n]) ? mouse_pos - inner_r.Max[n] : (mouse_pos < inner_r.Min[n]) ? mouse_pos - inner_r.Min[n] : 0.0f;
7333 const float scroll_curr = window->Scroll[n];
7334 if (dist == 0.0f || (dist < 0.0f && scroll_curr < 0.0f) || (dist > 0.0f && scroll_curr >= window->ScrollMax[n]))
7335 continue;
7336
7337 const float speed_multiplier = ImLinearRemapClamp(g.FontSize, g.FontSize * 5.0f, 1.0f, 4.0f, ImAbs(dist)); // x1 to x4 depending on distance
7338 const float scroll_step = g.FontSize * 35.0f * speed_multiplier * ImSign(dist) * g.IO.DeltaTime;
7339 bs->ScrollAccum[n] += scroll_step;
7340
7341 // Accumulate into a stored value so we can handle high-framerate
7342 const float scroll_step_i = ImFloor(bs->ScrollAccum[n]);
7343 if (scroll_step_i == 0.0f)
7344 continue;
7345 if (n == 0)
7346 ImGui::SetScrollX(window, scroll_curr + scroll_step_i);
7347 else
7348 ImGui::SetScrollY(window, scroll_curr + scroll_step_i);
7349 bs->ScrollAccum[n] -= scroll_step_i;
7350 }
7351 }
7352
7353 bool ImGui::BeginBoxSelect(const ImRect& scope_rect, ImGuiWindow* window, ImGuiID box_select_id, ImGuiMultiSelectFlags ms_flags)
7354 {
7355 ImGuiContext& g = *GImGui;
7356 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7357 KeepAliveID(box_select_id);
7358 if (bs->ID != box_select_id)
7359 return false;
7360
7361 // IsStarting is set by MultiSelectItemFooter() when considering a possible box-select. We validate it here and lock geometry.
7362 bs->UnclipMode = false;
7363 bs->RequestClear = false;
7364 if (bs->IsStarting && IsMouseDragPastThreshold(0))
7365 BoxSelectActivateDrag(bs, window);
7366 else if ((bs->IsStarting || bs->IsActive) && g.IO.MouseDown[0] == false)
7367 BoxSelectDeactivateDrag(bs);
7368 if (!bs->IsActive)
7369 return false;
7370
7371 // Current frame absolute prev/current rectangles are used to toggle selection.
7372 // They are derived from positions relative to scrolling space.
7373 ImVec2 start_pos_abs = WindowPosRelToAbs(window, bs->StartPosRel);
7374 ImVec2 prev_end_pos_abs = WindowPosRelToAbs(window, bs->EndPosRel); // Clamped already
7375 ImVec2 curr_end_pos_abs = g.IO.MousePos;
7376 if (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) // Box-select scrolling only happens with ScopeWindow
7377 curr_end_pos_abs = ImClamp(curr_end_pos_abs, scope_rect.Min, scope_rect.Max);
7378 bs->BoxSelectRectPrev.Min = ImMin(start_pos_abs, prev_end_pos_abs);
7379 bs->BoxSelectRectPrev.Max = ImMax(start_pos_abs, prev_end_pos_abs);
7380 bs->BoxSelectRectCurr.Min = ImMin(start_pos_abs, curr_end_pos_abs);
7381 bs->BoxSelectRectCurr.Max = ImMax(start_pos_abs, curr_end_pos_abs);
7382
7383 // Box-select 2D mode detects horizontal changes (vertical ones are already picked by Clipper)
7384 // Storing an extra rect used by widgets supporting box-select.
7385 if (ms_flags & ImGuiMultiSelectFlags_BoxSelect2d)
7386 if (bs->BoxSelectRectPrev.Min.x != bs->BoxSelectRectCurr.Min.x || bs->BoxSelectRectPrev.Max.x != bs->BoxSelectRectCurr.Max.x)
7387 {
7388 bs->UnclipMode = true;
7389 bs->UnclipRect = bs->BoxSelectRectPrev; // FIXME-OPT: UnclipRect x coordinates could be intersection of Prev and Curr rect on X axis.
7390 bs->UnclipRect.Add(bs->BoxSelectRectCurr);
7391 }
7392
7393 //GetForegroundDrawList()->AddRect(bs->UnclipRect.Min, bs->UnclipRect.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f);
7394 //GetForegroundDrawList()->AddRect(bs->BoxSelectRectPrev.Min, bs->BoxSelectRectPrev.Max, IM_COL32(255,0,0,200), 0.0f, 0, 3.0f);
7395 //GetForegroundDrawList()->AddRect(bs->BoxSelectRectCurr.Min, bs->BoxSelectRectCurr.Max, IM_COL32(0,255,0,200), 0.0f, 0, 1.0f);
7396 return true;
7397 }
7398
7399 void ImGui::EndBoxSelect(const ImRect& scope_rect, ImGuiMultiSelectFlags ms_flags)
7400 {
7401 ImGuiContext& g = *GImGui;
7402 ImGuiWindow* window = g.CurrentWindow;
7403 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7404 IM_ASSERT(bs->IsActive);
7405 bs->UnclipMode = false;
7406
7407 // Render selection rectangle
7408 bs->EndPosRel = WindowPosAbsToRel(window, ImClamp(g.IO.MousePos, scope_rect.Min, scope_rect.Max)); // Clamp stored position according to current scrolling view
7409 ImRect box_select_r = bs->BoxSelectRectCurr;
7410 box_select_r.ClipWith(scope_rect);
7411 window->DrawList->AddRectFilled(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_SeparatorHovered, 0.30f)); // FIXME-MULTISELECT: Styling
7412 window->DrawList->AddRect(box_select_r.Min, box_select_r.Max, GetColorU32(ImGuiCol_NavCursor)); // FIXME-MULTISELECT: Styling
7413
7414 // Scroll
7415 const bool enable_scroll = (ms_flags & ImGuiMultiSelectFlags_ScopeWindow) && (ms_flags & ImGuiMultiSelectFlags_BoxSelectNoScroll) == 0;
7416 if (enable_scroll)
7417 {
7418 ImRect scroll_r = scope_rect;
7419 scroll_r.Expand(-g.FontSize);
7420 //GetForegroundDrawList()->AddRect(scroll_r.Min, scroll_r.Max, IM_COL32(0, 255, 0, 255));
7421 if (!scroll_r.Contains(g.IO.MousePos))
7422 BoxSelectScrollWithMouseDrag(bs, window, scroll_r);
7423 }
7424 }
7425
7426 //-------------------------------------------------------------------------
7427 // [SECTION] Widgets: Multi-Select support
7428 //-------------------------------------------------------------------------
7429 // - DebugLogMultiSelectRequests() [Internal]
7430 // - CalcScopeRect() [Internal]
7431 // - BeginMultiSelect()
7432 // - EndMultiSelect()
7433 // - SetNextItemSelectionUserData()
7434 // - MultiSelectItemHeader() [Internal]
7435 // - MultiSelectItemFooter() [Internal]
7436 // - DebugNodeMultiSelectState() [Internal]
7437 //-------------------------------------------------------------------------
7438
7439 static void DebugLogMultiSelectRequests(const char* function, const ImGuiMultiSelectIO* io)
7440 {
7441 ImGuiContext& g = *GImGui;
7442 IM_UNUSED(function);
7443 for (const ImGuiSelectionRequest& req : io->Requests)
7444 {
7445 if (req.Type == ImGuiSelectionRequestType_SetAll) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetAll %d (= %s)\n", function, req.Selected, req.Selected ? "SelectAll" : "Clear");
7446 if (req.Type == ImGuiSelectionRequestType_SetRange) IMGUI_DEBUG_LOG_SELECTION("[selection] %s: Request: SetRange %" IM_PRId64 "..%" IM_PRId64 " (0x%" IM_PRIX64 "..0x%" IM_PRIX64 ") = %d (dir %d)\n", function, req.RangeFirstItem, req.RangeLastItem, req.RangeFirstItem, req.RangeLastItem, req.Selected, req.RangeDirection);
7447 }
7448 }
7449
7450 static ImRect CalcScopeRect(ImGuiMultiSelectTempData* ms, ImGuiWindow* window)
7451 {
7452 ImGuiContext& g = *GImGui;
7453 if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect)
7454 {
7455 // Warning: this depends on CursorMaxPos so it means to be called by EndMultiSelect() only
7456 return ImRect(ms->ScopeRectMin, ImMax(window->DC.CursorMaxPos, ms->ScopeRectMin));
7457 }
7458 else
7459 {
7460 // When a table, pull HostClipRect, which allows us to predict ClipRect before first row/layout is performed. (#7970)
7461 ImRect scope_rect = window->InnerClipRect;
7462 if (g.CurrentTable != NULL)
7463 scope_rect = g.CurrentTable->HostClipRect;
7464
7465 // Add inner table decoration (#7821) // FIXME: Why not baking in InnerClipRect?
7466 scope_rect.Min = ImMin(scope_rect.Min + ImVec2(window->DecoInnerSizeX1, window->DecoInnerSizeY1), scope_rect.Max);
7467 return scope_rect;
7468 }
7469 }
7470
7471 // Return ImGuiMultiSelectIO structure.
7472 // Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect().
7473 // Passing 'selection_size' and 'items_count' parameters is currently optional.
7474 // - 'selection_size' is useful to disable some shortcut routing: e.g. ImGuiMultiSelectFlags_ClearOnEscape won't claim Escape key when selection_size 0,
7475 // allowing a first press to clear selection THEN the second press to leave child window and return to parent.
7476 // - 'items_count' is stored in ImGuiMultiSelectIO which makes it a convenient way to pass the information to your ApplyRequest() handler (but you may pass it differently).
7477 // - If they are costly for you to compute (e.g. external intrusive selection without maintaining size), you may avoid them and pass -1.
7478 // - If you can easily tell if your selection is empty or not, you may pass 0/1, or you may enable ImGuiMultiSelectFlags_ClearOnEscape flag dynamically.
7479 ImGuiMultiSelectIO* ImGui::BeginMultiSelect(ImGuiMultiSelectFlags flags, int selection_size, int items_count)
7480 {
7481 ImGuiContext& g = *GImGui;
7482 ImGuiWindow* window = g.CurrentWindow;
7483
7484 if (++g.MultiSelectTempDataStacked > g.MultiSelectTempData.Size)
7485 g.MultiSelectTempData.resize(g.MultiSelectTempDataStacked, ImGuiMultiSelectTempData());
7486 ImGuiMultiSelectTempData* ms = &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1];
7487 IM_STATIC_ASSERT(offsetof(ImGuiMultiSelectTempData, IO) == 0); // Clear() relies on that.
7488 g.CurrentMultiSelect = ms;
7489 if ((flags & (ImGuiMultiSelectFlags_ScopeWindow | ImGuiMultiSelectFlags_ScopeRect)) == 0)
7490 flags |= ImGuiMultiSelectFlags_ScopeWindow;
7491 if (flags & ImGuiMultiSelectFlags_SingleSelect)
7492 flags &= ~(ImGuiMultiSelectFlags_BoxSelect2d | ImGuiMultiSelectFlags_BoxSelect1d);
7493 if (flags & ImGuiMultiSelectFlags_BoxSelect2d)
7494 flags &= ~ImGuiMultiSelectFlags_BoxSelect1d;
7495
7496 // FIXME: BeginFocusScope()
7497 const ImGuiID id = window->IDStack.back();
7498 ms->Clear();
7499 ms->FocusScopeId = id;
7500 ms->Flags = flags;
7501 ms->IsFocused = (ms->FocusScopeId == g.NavFocusScopeId);
7502 ms->BackupCursorMaxPos = window->DC.CursorMaxPos;
7503 ms->ScopeRectMin = window->DC.CursorMaxPos = window->DC.CursorPos;
7504 PushFocusScope(ms->FocusScopeId);
7505 if (flags & ImGuiMultiSelectFlags_ScopeWindow) // Mark parent child window as navigable into, with highlight. Assume user will always submit interactive items.
7506 window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main;
7507
7508 // Use copy of keyboard mods at the time of the request, otherwise we would requires mods to be held for an extra frame.
7509 ms->KeyMods = g.NavJustMovedToId ? (g.NavJustMovedToIsTabbing ? 0 : g.NavJustMovedToKeyMods) : g.IO.KeyMods;
7510 if (flags & ImGuiMultiSelectFlags_NoRangeSelect)
7511 ms->KeyMods &= ~ImGuiMod_Shift;
7512
7513 // Bind storage
7514 ImGuiMultiSelectState* storage = g.MultiSelectStorage.GetOrAddByKey(id);
7515 storage->ID = id;
7516 storage->LastFrameActive = g.FrameCount;
7517 storage->LastSelectionSize = selection_size;
7518 storage->Window = window;
7519 ms->Storage = storage;
7520
7521 // Output to user
7522 ms->IO.Requests.resize(0);
7523 ms->IO.RangeSrcItem = storage->RangeSrcItem;
7524 ms->IO.NavIdItem = storage->NavIdItem;
7525 ms->IO.NavIdSelected = (storage->NavIdSelected == 1) ? true : false;
7526 ms->IO.ItemsCount = items_count;
7527
7528 // Clear when using Navigation to move within the scope
7529 // (we compare FocusScopeId so it possible to use multiple selections inside a same window)
7530 bool request_clear = false;
7531 bool request_select_all = false;
7532 if (g.NavJustMovedToId != 0 && g.NavJustMovedToFocusScopeId == ms->FocusScopeId && g.NavJustMovedToHasSelectionData)
7533 {
7534 if (ms->KeyMods & ImGuiMod_Shift)
7535 ms->IsKeyboardSetRange = true;
7536 if (ms->IsKeyboardSetRange)
7537 IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid); // Not ready -> could clear?
7538 if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0 && (flags & (ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_NoAutoSelect)) == 0)
7539 request_clear = true;
7540 }
7541 else if (g.NavJustMovedFromFocusScopeId == ms->FocusScopeId)
7542 {
7543 // Also clear on leaving scope (may be optional?)
7544 if ((ms->KeyMods & (ImGuiMod_Ctrl | ImGuiMod_Shift)) == 0 && (flags & (ImGuiMultiSelectFlags_NoAutoClear | ImGuiMultiSelectFlags_NoAutoSelect)) == 0)
7545 request_clear = true;
7546 }
7547
7548 // Box-select handling: update active state.
7549 ImGuiBoxSelectState* bs = &g.BoxSelectState;
7550 if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d))
7551 {
7552 ms->BoxSelectId = GetID("##BoxSelect");
7553 if (BeginBoxSelect(CalcScopeRect(ms, window), window, ms->BoxSelectId, flags))
7554 request_clear |= bs->RequestClear;
7555 }
7556
7557 if (ms->IsFocused)
7558 {
7559 // Shortcut: Clear selection (Escape)
7560 // - Only claim shortcut if selection is not empty, allowing further presses on Escape to e.g. leave current child window.
7561 // - Box select also handle Escape and needs to pass an id to bypass ActiveIdUsingAllKeyboardKeys lock.
7562 if (flags & ImGuiMultiSelectFlags_ClearOnEscape)
7563 {
7564 if (selection_size != 0 || bs->IsActive)
7565 if (Shortcut(ImGuiKey_Escape, ImGuiInputFlags_None, bs->IsActive ? bs->ID : 0))
7566 {
7567 request_clear = true;
7568 if (bs->IsActive)
7569 BoxSelectDeactivateDrag(bs);
7570 }
7571 }
7572
7573 // Shortcut: Select all (CTRL+A)
7574 if (!(flags & ImGuiMultiSelectFlags_SingleSelect) && !(flags & ImGuiMultiSelectFlags_NoSelectAll))
7575 if (Shortcut(ImGuiMod_Ctrl | ImGuiKey_A))
7576 request_select_all = true;
7577 }
7578
7579 if (request_clear || request_select_all)
7580 {
7581 MultiSelectAddSetAll(ms, request_select_all);
7582 if (!request_select_all)
7583 storage->LastSelectionSize = 0;
7584 }
7585 ms->LoopRequestSetAll = request_select_all ? 1 : request_clear ? 0 : -1;
7586 ms->LastSubmittedItem = ImGuiSelectionUserData_Invalid;
7587
7588 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection)
7589 DebugLogMultiSelectRequests("BeginMultiSelect", &ms->IO);
7590
7591 return &ms->IO;
7592 }
7593
7594 // Return updated ImGuiMultiSelectIO structure.
7595 // Lifetime: don't hold on ImGuiMultiSelectIO* pointers over multiple frames or past any subsequent call to BeginMultiSelect() or EndMultiSelect().
7596 ImGuiMultiSelectIO* ImGui::EndMultiSelect()
7597 {
7598 ImGuiContext& g = *GImGui;
7599 ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect;
7600 ImGuiMultiSelectState* storage = ms->Storage;
7601 ImGuiWindow* window = g.CurrentWindow;
7602 IM_ASSERT_USER_ERROR(ms->FocusScopeId == g.CurrentFocusScopeId, "EndMultiSelect() FocusScope mismatch!");
7603 IM_ASSERT(g.CurrentMultiSelect != NULL && storage->Window == g.CurrentWindow);
7604 IM_ASSERT(g.MultiSelectTempDataStacked > 0 && &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] == g.CurrentMultiSelect);
7605
7606 ImRect scope_rect = CalcScopeRect(ms, window);
7607 if (ms->IsFocused)
7608 {
7609 // We currently don't allow user code to modify RangeSrcItem by writing to BeginIO's version, but that would be an easy change here.
7610 if (ms->IO.RangeSrcReset || (ms->RangeSrcPassedBy == false && ms->IO.RangeSrcItem != ImGuiSelectionUserData_Invalid)) // Can't read storage->RangeSrcItem here -> we want the state at begining of the scope (see tests for easy failure)
7611 {
7612 IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset RangeSrcItem.\n"); // Will set be to NavId.
7613 storage->RangeSrcItem = ImGuiSelectionUserData_Invalid;
7614 }
7615 if (ms->NavIdPassedBy == false && storage->NavIdItem != ImGuiSelectionUserData_Invalid)
7616 {
7617 IMGUI_DEBUG_LOG_SELECTION("[selection] EndMultiSelect: Reset NavIdItem.\n");
7618 storage->NavIdItem = ImGuiSelectionUserData_Invalid;
7619 storage->NavIdSelected = -1;
7620 }
7621
7622 if ((ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d)) && GetBoxSelectState(ms->BoxSelectId))
7623 EndBoxSelect(scope_rect, ms->Flags);
7624 }
7625
7626 if (ms->IsEndIO == false)
7627 ms->IO.Requests.resize(0);
7628
7629 // Clear selection when clicking void?
7630 // We specifically test for IsMouseDragPastThreshold(0) == false to allow box-selection!
7631 // The InnerRect test is necessary for non-child/decorated windows.
7632 bool scope_hovered = IsWindowHovered() && window->InnerRect.Contains(g.IO.MousePos);
7633 if (scope_hovered && (ms->Flags & ImGuiMultiSelectFlags_ScopeRect))
7634 scope_hovered &= scope_rect.Contains(g.IO.MousePos);
7635 if (scope_hovered && g.HoveredId == 0 && g.ActiveId == 0)
7636 {
7637 if (ms->Flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d))
7638 {
7639 if (!g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && g.IO.MouseClickedCount[0] == 1)
7640 {
7641 BoxSelectPreStartDrag(ms->BoxSelectId, ImGuiSelectionUserData_Invalid);
7642 FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7643 SetHoveredID(ms->BoxSelectId);
7644 if (ms->Flags & ImGuiMultiSelectFlags_ScopeRect)
7645 SetNavID(0, ImGuiNavLayer_Main, ms->FocusScopeId, ImRect(g.IO.MousePos, g.IO.MousePos)); // Automatically switch FocusScope for initial click from void to box-select.
7646 }
7647 }
7648
7649 if (ms->Flags & ImGuiMultiSelectFlags_ClearOnClickVoid)
7650 if (IsMouseReleased(0) && IsMouseDragPastThreshold(0) == false && g.IO.KeyMods == ImGuiMod_None)
7651 MultiSelectAddSetAll(ms, false);
7652 }
7653
7654 // Courtesy nav wrapping helper flag
7655 if (ms->Flags & ImGuiMultiSelectFlags_NavWrapX)
7656 {
7657 IM_ASSERT(ms->Flags & ImGuiMultiSelectFlags_ScopeWindow); // Only supported at window scope
7658 ImGui::NavMoveRequestTryWrapping(ImGui::GetCurrentWindow(), ImGuiNavMoveFlags_WrapX);
7659 }
7660
7661 // Unwind
7662 window->DC.CursorMaxPos = ImMax(ms->BackupCursorMaxPos, window->DC.CursorMaxPos);
7663 PopFocusScope();
7664
7665 if (g.DebugLogFlags & ImGuiDebugLogFlags_EventSelection)
7666 DebugLogMultiSelectRequests("EndMultiSelect", &ms->IO);
7667
7668 ms->FocusScopeId = 0;
7669 ms->Flags = ImGuiMultiSelectFlags_None;
7670 g.CurrentMultiSelect = (--g.MultiSelectTempDataStacked > 0) ? &g.MultiSelectTempData[g.MultiSelectTempDataStacked - 1] : NULL;
7671
7672 return &ms->IO;
7673 }
7674
7675 void ImGui::SetNextItemSelectionUserData(ImGuiSelectionUserData selection_user_data)
7676 {
7677 // Note that flags will be cleared by ItemAdd(), so it's only useful for Navigation code!
7678 // This designed so widgets can also cheaply set this before calling ItemAdd(), so we are not tied to MultiSelect api.
7679 ImGuiContext& g = *GImGui;
7680 g.NextItemData.SelectionUserData = selection_user_data;
7681 g.NextItemData.FocusScopeId = g.CurrentFocusScopeId;
7682
7683 if (ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect)
7684 {
7685 // Auto updating RangeSrcPassedBy for cases were clipper is not used (done before ItemAdd() clipping)
7686 g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData | ImGuiItemFlags_IsMultiSelect;
7687 if (ms->IO.RangeSrcItem == selection_user_data)
7688 ms->RangeSrcPassedBy = true;
7689 }
7690 else
7691 {
7692 g.NextItemData.ItemFlags |= ImGuiItemFlags_HasSelectionUserData;
7693 }
7694 }
7695
7696 // In charge of:
7697 // - Applying SetAll for submitted items.
7698 // - Applying SetRange for submitted items and record end points.
7699 // - Altering button behavior flags to facilitate use with drag and drop.
7700 void ImGui::MultiSelectItemHeader(ImGuiID id, bool* p_selected, ImGuiButtonFlags* p_button_flags)
7701 {
7702 ImGuiContext& g = *GImGui;
7703 ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect;
7704
7705 bool selected = *p_selected;
7706 if (ms->IsFocused)
7707 {
7708 ImGuiMultiSelectState* storage = ms->Storage;
7709 ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData;
7710 IM_ASSERT(g.NextItemData.FocusScopeId == g.CurrentFocusScopeId && "Forgot to call SetNextItemSelectionUserData() prior to item, required in BeginMultiSelect()/EndMultiSelect() scope");
7711
7712 // Apply SetAll (Clear/SelectAll) requests requested by BeginMultiSelect().
7713 // This is only useful if the user hasn't processed them already, and this only works if the user isn't using the clipper.
7714 // If you are using a clipper you need to process the SetAll request after calling BeginMultiSelect()
7715 if (ms->LoopRequestSetAll != -1)
7716 selected = (ms->LoopRequestSetAll == 1);
7717
7718 // When using SHIFT+Nav: because it can incur scrolling we cannot afford a frame of lag with the selection highlight (otherwise scrolling would happen before selection)
7719 // For this to work, we need someone to set 'RangeSrcPassedBy = true' at some point (either clipper either SetNextItemSelectionUserData() function)
7720 if (ms->IsKeyboardSetRange)
7721 {
7722 IM_ASSERT(id != 0 && (ms->KeyMods & ImGuiMod_Shift) != 0);
7723 const bool is_range_dst = (ms->RangeDstPassedBy == false) && g.NavJustMovedToId == id; // Assume that g.NavJustMovedToId is not clipped.
7724 if (is_range_dst)
7725 ms->RangeDstPassedBy = true;
7726 if (is_range_dst && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid) // If we don't have RangeSrc, assign RangeSrc = RangeDst
7727 {
7728 storage->RangeSrcItem = item_data;
7729 storage->RangeSelected = selected ? 1 : 0;
7730 }
7731 const bool is_range_src = storage->RangeSrcItem == item_data;
7732 if (is_range_src || is_range_dst || ms->RangeSrcPassedBy != ms->RangeDstPassedBy)
7733 {
7734 // Apply range-select value to visible items
7735 IM_ASSERT(storage->RangeSrcItem != ImGuiSelectionUserData_Invalid && storage->RangeSelected != -1);
7736 selected = (storage->RangeSelected != 0);
7737 }
7738 else if ((ms->KeyMods & ImGuiMod_Ctrl) == 0 && (ms->Flags & ImGuiMultiSelectFlags_NoAutoClear) == 0)
7739 {
7740 // Clear other items
7741 selected = false;
7742 }
7743 }
7744 *p_selected = selected;
7745 }
7746
7747 // Alter button behavior flags
7748 // To handle drag and drop of multiple items we need to avoid clearing selection on click.
7749 // Enabling this test makes actions using CTRL+SHIFT delay their effect on MouseUp which is annoying, but it allows drag and drop of multiple items.
7750 if (p_button_flags != NULL)
7751 {
7752 ImGuiButtonFlags button_flags = *p_button_flags;
7753 button_flags |= ImGuiButtonFlags_NoHoveredOnFocus;
7754 if ((!selected || (g.ActiveId == id && g.ActiveIdHasBeenPressedBefore)) && !(ms->Flags & ImGuiMultiSelectFlags_SelectOnClickRelease))
7755 button_flags = (button_flags | ImGuiButtonFlags_PressedOnClick) & ~ImGuiButtonFlags_PressedOnClickRelease;
7756 else
7757 button_flags |= ImGuiButtonFlags_PressedOnClickRelease;
7758 *p_button_flags = button_flags;
7759 }
7760 }
7761
7762 // In charge of:
7763 // - Auto-select on navigation.
7764 // - Box-select toggle handling.
7765 // - Right-click handling.
7766 // - Altering selection based on Ctrl/Shift modifiers, both for keyboard and mouse.
7767 // - Record current selection state for RangeSrc
7768 // This is all rather complex, best to run and refer to "widgets_multiselect_xxx" tests in imgui_test_suite.
7769 void ImGui::MultiSelectItemFooter(ImGuiID id, bool* p_selected, bool* p_pressed)
7770 {
7771 ImGuiContext& g = *GImGui;
7772 ImGuiWindow* window = g.CurrentWindow;
7773
7774 bool selected = *p_selected;
7775 bool pressed = *p_pressed;
7776 ImGuiMultiSelectTempData* ms = g.CurrentMultiSelect;
7777 ImGuiMultiSelectState* storage = ms->Storage;
7778 if (pressed)
7779 ms->IsFocused = true;
7780
7781 bool hovered = false;
7782 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect)
7783 hovered = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
7784 if (!ms->IsFocused && !hovered)
7785 return;
7786
7787 ImGuiSelectionUserData item_data = g.NextItemData.SelectionUserData;
7788
7789 ImGuiMultiSelectFlags flags = ms->Flags;
7790 const bool is_singleselect = (flags & ImGuiMultiSelectFlags_SingleSelect) != 0;
7791 bool is_ctrl = (ms->KeyMods & ImGuiMod_Ctrl) != 0;
7792 bool is_shift = (ms->KeyMods & ImGuiMod_Shift) != 0;
7793
7794 bool apply_to_range_src = false;
7795
7796 if (g.NavId == id && storage->RangeSrcItem == ImGuiSelectionUserData_Invalid)
7797 apply_to_range_src = true;
7798 if (ms->IsEndIO == false)
7799 {
7800 ms->IO.Requests.resize(0);
7801 ms->IsEndIO = true;
7802 }
7803
7804 // Auto-select as you navigate a list
7805 if (g.NavJustMovedToId == id)
7806 {
7807 if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
7808 {
7809 if (is_ctrl && is_shift)
7810 pressed = true;
7811 else if (!is_ctrl)
7812 selected = pressed = true;
7813 }
7814 else
7815 {
7816 // With NoAutoSelect, using Shift+keyboard performs a write/copy
7817 if (is_shift)
7818 pressed = true;
7819 else if (!is_ctrl)
7820 apply_to_range_src = true; // Since if (pressed) {} main block is not running we update this
7821 }
7822 }
7823
7824 if (apply_to_range_src)
7825 {
7826 storage->RangeSrcItem = item_data;
7827 storage->RangeSelected = selected; // Will be updated at the end of this function anyway.
7828 }
7829
7830 // Box-select toggle handling
7831 if (ms->BoxSelectId != 0)
7832 if (ImGuiBoxSelectState* bs = GetBoxSelectState(ms->BoxSelectId))
7833 {
7834 const bool rect_overlap_curr = bs->BoxSelectRectCurr.Overlaps(g.LastItemData.Rect);
7835 const bool rect_overlap_prev = bs->BoxSelectRectPrev.Overlaps(g.LastItemData.Rect);
7836 if ((rect_overlap_curr && !rect_overlap_prev && !selected) || (rect_overlap_prev && !rect_overlap_curr))
7837 {
7838 if (storage->LastSelectionSize <= 0 && bs->IsStartedSetNavIdOnce)
7839 {
7840 pressed = true; // First item act as a pressed: code below will emit selection request and set NavId (whatever we emit here will be overridden anyway)
7841 bs->IsStartedSetNavIdOnce = false;
7842 }
7843 else
7844 {
7845 selected = !selected;
7846 MultiSelectAddSetRange(ms, selected, +1, item_data, item_data);
7847 }
7848 storage->LastSelectionSize = ImMax(storage->LastSelectionSize + 1, 1);
7849 }
7850 }
7851
7852 // Right-click handling.
7853 // FIXME-MULTISELECT: Currently filtered out by ImGuiMultiSelectFlags_NoAutoSelect but maybe should be moved to Selectable(). See https://github.com/ocornut/imgui/pull/5816
7854 if (hovered && IsMouseClicked(1) && (flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
7855 {
7856 if (g.ActiveId != 0 && g.ActiveId != id)
7857 ClearActiveID();
7858 SetFocusID(id, window);
7859 if (!pressed && !selected)
7860 {
7861 pressed = true;
7862 is_ctrl = is_shift = false;
7863 }
7864 }
7865
7866 // Unlike Space, Enter doesn't alter selection (but can still return a press) unless current item is not selected.
7867 // The later, "unless current item is not select", may become optional? It seems like a better default if Enter doesn't necessarily open something
7868 // (unlike e.g. Windows explorer). For use case where Enter always open something, we might decide to make this optional?
7869 const bool enter_pressed = pressed && (g.NavActivateId == id) && (g.NavActivateFlags & ImGuiActivateFlags_PreferInput);
7870
7871 // Alter selection
7872 if (pressed && (!enter_pressed || !selected))
7873 {
7874 // Box-select
7875 ImGuiInputSource input_source = (g.NavJustMovedToId == id || g.NavActivateId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
7876 if (flags & (ImGuiMultiSelectFlags_BoxSelect1d | ImGuiMultiSelectFlags_BoxSelect2d))
7877 if (selected == false && !g.BoxSelectState.IsActive && !g.BoxSelectState.IsStarting && input_source == ImGuiInputSource_Mouse && g.IO.MouseClickedCount[0] == 1)
7878 BoxSelectPreStartDrag(ms->BoxSelectId, item_data);
7879
7880 //----------------------------------------------------------------------------------------
7881 // ACTION | Begin | Pressed/Activated | End
7882 //----------------------------------------------------------------------------------------
7883 // Keys Navigated: | Clear | Src=item, Sel=1 SetRange 1
7884 // Keys Navigated: Ctrl | n/a | n/a
7885 // Keys Navigated: Shift | n/a | Dst=item, Sel=1, => Clear + SetRange 1
7886 // Keys Navigated: Ctrl+Shift | n/a | Dst=item, Sel=Src => Clear + SetRange Src-Dst
7887 // Keys Activated: | n/a | Src=item, Sel=1 => Clear + SetRange 1
7888 // Keys Activated: Ctrl | n/a | Src=item, Sel=!Sel => SetSange 1
7889 // Keys Activated: Shift | n/a | Dst=item, Sel=1 => Clear + SetSange 1
7890 //----------------------------------------------------------------------------------------
7891 // Mouse Pressed: | n/a | Src=item, Sel=1, => Clear + SetRange 1
7892 // Mouse Pressed: Ctrl | n/a | Src=item, Sel=!Sel => SetRange 1
7893 // Mouse Pressed: Shift | n/a | Dst=item, Sel=1, => Clear + SetRange 1
7894 // Mouse Pressed: Ctrl+Shift | n/a | Dst=item, Sel=!Sel => SetRange Src-Dst
7895 //----------------------------------------------------------------------------------------
7896
7897 if ((flags & ImGuiMultiSelectFlags_NoAutoClear) == 0)
7898 {
7899 bool request_clear = false;
7900 if (is_singleselect)
7901 request_clear = true;
7902 else if ((input_source == ImGuiInputSource_Mouse || g.NavActivateId == id) && !is_ctrl)
7903 request_clear = (flags & ImGuiMultiSelectFlags_NoAutoClearOnReselect) ? !selected : true;
7904 else if ((input_source == ImGuiInputSource_Keyboard || input_source == ImGuiInputSource_Gamepad) && is_shift && !is_ctrl)
7905 request_clear = true; // With is_shift==false the RequestClear was done in BeginIO, not necessary to do again.
7906 if (request_clear)
7907 MultiSelectAddSetAll(ms, false);
7908 }
7909
7910 int range_direction;
7911 bool range_selected;
7912 if (is_shift && !is_singleselect)
7913 {
7914 //IM_ASSERT(storage->HasRangeSrc && storage->HasRangeValue);
7915 if (storage->RangeSrcItem == ImGuiSelectionUserData_Invalid)
7916 storage->RangeSrcItem = item_data;
7917 if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
7918 {
7919 // Shift+Arrow always select
7920 // Ctrl+Shift+Arrow copy source selection state (already stored by BeginMultiSelect() in storage->RangeSelected)
7921 range_selected = (is_ctrl && storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true;
7922 }
7923 else
7924 {
7925 // Shift+Arrow copy source selection state
7926 // Shift+Click always copy from target selection state
7927 if (ms->IsKeyboardSetRange)
7928 range_selected = (storage->RangeSelected != -1) ? (storage->RangeSelected != 0) : true;
7929 else
7930 range_selected = !selected;
7931 }
7932 range_direction = ms->RangeSrcPassedBy ? +1 : -1;
7933 }
7934 else
7935 {
7936 // Ctrl inverts selection, otherwise always select
7937 if ((flags & ImGuiMultiSelectFlags_NoAutoSelect) == 0)
7938 selected = is_ctrl ? !selected : true;
7939 else
7940 selected = !selected;
7941 storage->RangeSrcItem = item_data;
7942 range_selected = selected;
7943 range_direction = +1;
7944 }
7945 MultiSelectAddSetRange(ms, range_selected, range_direction, storage->RangeSrcItem, item_data);
7946 }
7947
7948 // Update/store the selection state of the Source item (used by CTRL+SHIFT, when Source is unselected we perform a range unselect)
7949 if (storage->RangeSrcItem == item_data)
7950 storage->RangeSelected = selected ? 1 : 0;
7951
7952 // Update/store the selection state of focused item
7953 if (g.NavId == id)
7954 {
7955 storage->NavIdItem = item_data;
7956 storage->NavIdSelected = selected ? 1 : 0;
7957 }
7958 if (storage->NavIdItem == item_data)
7959 ms->NavIdPassedBy = true;
7960 ms->LastSubmittedItem = item_data;
7961
7962 *p_selected = selected;
7963 *p_pressed = pressed;
7964 }
7965
7966 void ImGui::MultiSelectAddSetAll(ImGuiMultiSelectTempData* ms, bool selected)
7967 {
7968 ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetAll, selected, 0, ImGuiSelectionUserData_Invalid, ImGuiSelectionUserData_Invalid };
7969 ms->IO.Requests.resize(0); // Can always clear previous requests
7970 ms->IO.Requests.push_back(req); // Add new request
7971 }
7972
7973 void ImGui::MultiSelectAddSetRange(ImGuiMultiSelectTempData* ms, bool selected, int range_dir, ImGuiSelectionUserData first_item, ImGuiSelectionUserData last_item)
7974 {
7975 // Merge contiguous spans into same request (unless NoRangeSelect is set which guarantees single-item ranges)
7976 if (ms->IO.Requests.Size > 0 && first_item == last_item && (ms->Flags & ImGuiMultiSelectFlags_NoRangeSelect) == 0)
7977 {
7978 ImGuiSelectionRequest* prev = &ms->IO.Requests.Data[ms->IO.Requests.Size - 1];
7979 if (prev->Type == ImGuiSelectionRequestType_SetRange && prev->RangeLastItem == ms->LastSubmittedItem && prev->Selected == selected)
7980 {
7981 prev->RangeLastItem = last_item;
7982 return;
7983 }
7984 }
7985
7986 ImGuiSelectionRequest req = { ImGuiSelectionRequestType_SetRange, selected, (ImS8)range_dir, (range_dir > 0) ? first_item : last_item, (range_dir > 0) ? last_item : first_item };
7987 ms->IO.Requests.push_back(req); // Add new request
7988 }
7989
7990 void ImGui::DebugNodeMultiSelectState(ImGuiMultiSelectState* storage)
7991 {
7992 #ifndef IMGUI_DISABLE_DEBUG_TOOLS
7993 const bool is_active = (storage->LastFrameActive >= GetFrameCount() - 2); // Note that fully clipped early out scrolling tables will appear as inactive here.
7994 if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
7995 bool open = TreeNode((void*)(intptr_t)storage->ID, "MultiSelect 0x%08X in '%s'%s", storage->ID, storage->Window ? storage->Window->Name : "N/A", is_active ? "" : " *Inactive*");
7996 if (!is_active) { PopStyleColor(); }
7997 if (!open)
7998 return;
7999 Text("RangeSrcItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), RangeSelected = %d", storage->RangeSrcItem, storage->RangeSrcItem, storage->RangeSelected);
8000 Text("NavIdItem = %" IM_PRId64 " (0x%" IM_PRIX64 "), NavIdSelected = %d", storage->NavIdItem, storage->NavIdItem, storage->NavIdSelected);
8001 Text("LastSelectionSize = %d", storage->LastSelectionSize); // Provided by user
8002 TreePop();
8003 #else
8004 IM_UNUSED(storage);
8005 #endif
8006 }
8007
8008 //-------------------------------------------------------------------------
8009 // [SECTION] Widgets: Multi-Select helpers
8010 //-------------------------------------------------------------------------
8011 // - ImGuiSelectionBasicStorage
8012 // - ImGuiSelectionExternalStorage
8013 //-------------------------------------------------------------------------
8014
8015 ImGuiSelectionBasicStorage::ImGuiSelectionBasicStorage()
8016 {
8017 Size = 0;
8018 PreserveOrder = false;
8019 UserData = NULL;
8020 AdapterIndexToStorageId = [](ImGuiSelectionBasicStorage*, int idx) { return (ImGuiID)idx; };
8021 _SelectionOrder = 1; // Always >0
8022 }
8023
8024 void ImGuiSelectionBasicStorage::Clear()
8025 {
8026 Size = 0;
8027 _SelectionOrder = 1; // Always >0
8028 _Storage.Data.resize(0);
8029 }
8030
8031 void ImGuiSelectionBasicStorage::Swap(ImGuiSelectionBasicStorage& r)
8032 {
8033 ImSwap(Size, r.Size);
8034 ImSwap(_SelectionOrder, r._SelectionOrder);
8035 _Storage.Data.swap(r._Storage.Data);
8036 }
8037
8038 bool ImGuiSelectionBasicStorage::Contains(ImGuiID id) const
8039 {
8040 return _Storage.GetInt(id, 0) != 0;
8041 }
8042
8043 static int IMGUI_CDECL PairComparerByValueInt(const void* lhs, const void* rhs)
8044 {
8045 int lhs_v = ((const ImGuiStoragePair*)lhs)->val_i;
8046 int rhs_v = ((const ImGuiStoragePair*)rhs)->val_i;
8047 return (lhs_v > rhs_v ? +1 : lhs_v < rhs_v ? -1 : 0);
8048 }
8049
8050 // GetNextSelectedItem() is an abstraction allowing us to change our underlying actual storage system without impacting user.
8051 // (e.g. store unselected vs compact down, compact down on demand, use raw ImVector<ImGuiID> instead of ImGuiStorage...)
8052 bool ImGuiSelectionBasicStorage::GetNextSelectedItem(void** opaque_it, ImGuiID* out_id)
8053 {
8054 ImGuiStoragePair* it = (ImGuiStoragePair*)*opaque_it;
8055 ImGuiStoragePair* it_end = _Storage.Data.Data + _Storage.Data.Size;
8056 if (PreserveOrder && it == NULL && it_end != NULL)
8057 ImQsort(_Storage.Data.Data, (size_t)_Storage.Data.Size, sizeof(ImGuiStoragePair), PairComparerByValueInt); // ~ImGuiStorage::BuildSortByValueInt()
8058 if (it == NULL)
8059 it = _Storage.Data.Data;
8060 IM_ASSERT(it >= _Storage.Data.Data && it <= it_end);
8061 if (it != it_end)
8062 while (it->val_i == 0 && it < it_end)
8063 it++;
8064 const bool has_more = (it != it_end);
8065 *opaque_it = has_more ? (void**)(it + 1) : (void**)(it);
8066 *out_id = has_more ? it->key : 0;
8067 if (PreserveOrder && !has_more)
8068 _Storage.BuildSortByKey();
8069 return has_more;
8070 }
8071
8072 void ImGuiSelectionBasicStorage::SetItemSelected(ImGuiID id, bool selected)
8073 {
8074 int* p_int = _Storage.GetIntRef(id, 0);
8075 if (selected && *p_int == 0) { *p_int = _SelectionOrder++; Size++; }
8076 else if (!selected && *p_int != 0) { *p_int = 0; Size--; }
8077 }
8078
8079 // Optimized for batch edits (with same value of 'selected')
8080 static void ImGuiSelectionBasicStorage_BatchSetItemSelected(ImGuiSelectionBasicStorage* selection, ImGuiID id, bool selected, int size_before_amends, int selection_order)
8081 {
8082 ImGuiStorage* storage = &selection->_Storage;
8083 ImGuiStoragePair* it = ImLowerBound(storage->Data.Data, storage->Data.Data + size_before_amends, id);
8084 const bool is_contained = (it != storage->Data.Data + size_before_amends) && (it->key == id);
8085 if (selected == (is_contained && it->val_i != 0))
8086 return;
8087 if (selected && !is_contained)
8088 storage->Data.push_back(ImGuiStoragePair(id, selection_order)); // Push unsorted at end of vector, will be sorted in SelectionMultiAmendsFinish()
8089 else if (is_contained)
8090 it->val_i = selected ? selection_order : 0; // Modify in-place.
8091 selection->Size += selected ? +1 : -1;
8092 }
8093
8094 static void ImGuiSelectionBasicStorage_BatchFinish(ImGuiSelectionBasicStorage* selection, bool selected, int size_before_amends)
8095 {
8096 ImGuiStorage* storage = &selection->_Storage;
8097 if (selected && selection->Size != size_before_amends)
8098 storage->BuildSortByKey(); // When done selecting: sort everything
8099 }
8100
8101 // Apply requests coming from BeginMultiSelect() and EndMultiSelect().
8102 // - Enable 'Demo->Tools->Debug Log->Selection' to see selection requests as they happen.
8103 // - Honoring SetRange requests requires that you can iterate/interpolate between RangeFirstItem and RangeLastItem.
8104 // - In this demo we often submit indices to SetNextItemSelectionUserData() + store the same indices in persistent selection.
8105 // - Your code may do differently. If you store pointers or objects ID in ImGuiSelectionUserData you may need to perform
8106 // a lookup in order to have some way to iterate/interpolate between two items.
8107 // - A full-featured application is likely to allow search/filtering which is likely to lead to using indices
8108 // and constructing a view index <> object id/ptr data structure anyway.
8109 // WHEN YOUR APPLICATION SETTLES ON A CHOICE, YOU WILL PROBABLY PREFER TO GET RID OF THIS UNNECESSARY 'ImGuiSelectionBasicStorage' INDIRECTION LOGIC.
8110 // Notice that with the simplest adapter (using indices everywhere), all functions return their parameters.
8111 // The most simple implementation (using indices everywhere) would look like:
8112 // for (ImGuiSelectionRequest& req : ms_io->Requests)
8113 // {
8114 // if (req.Type == ImGuiSelectionRequestType_SetAll) { Clear(); if (req.Selected) { for (int n = 0; n < items_count; n++) { SetItemSelected(n, true); } }
8115 // if (req.Type == ImGuiSelectionRequestType_SetRange) { for (int n = (int)ms_io->RangeFirstItem; n <= (int)ms_io->RangeLastItem; n++) { SetItemSelected(n, ms_io->Selected); } }
8116 // }
8117 void ImGuiSelectionBasicStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io)
8118 {
8119 // For convenience we obtain ItemsCount as passed to BeginMultiSelect(), which is optional.
8120 // It makes sense when using ImGuiSelectionBasicStorage to simply pass your items count to BeginMultiSelect().
8121 // Other scheme may handle SetAll differently.
8122 IM_ASSERT(ms_io->ItemsCount != -1 && "Missing value for items_count in BeginMultiSelect() call!");
8123 IM_ASSERT(AdapterIndexToStorageId != NULL);
8124
8125 // This is optimized/specialized to cope with very large selections (e.g. 100k+ items)
8126 // - A simpler version could call SetItemSelected() directly instead of ImGuiSelectionBasicStorage_BatchSetItemSelected() + ImGuiSelectionBasicStorage_BatchFinish().
8127 // - Optimized select can append unsorted, then sort in a second pass. Optimized unselect can clear in-place then compact in a second pass.
8128 // - A more optimal version wouldn't even use ImGuiStorage but directly a ImVector<ImGuiID> to reduce bandwidth, but this is a reasonable trade off to reuse code.
8129 // - There are many ways this could be better optimized. The worse case scenario being: using BoxSelect2d in a grid, box-select scrolling down while wiggling
8130 // left and right: it affects coarse clipping + can emit multiple SetRange with 1 item each.)
8131 // FIXME-OPT: For each block of consecutive SetRange request:
8132 // - add all requests to a sorted list, store ID, selected, offset in ImGuiStorage.
8133 // - rewrite sorted storage a single time.
8134 for (ImGuiSelectionRequest& req : ms_io->Requests)
8135 {
8136 if (req.Type == ImGuiSelectionRequestType_SetAll)
8137 {
8138 Clear();
8139 if (req.Selected)
8140 {
8141 _Storage.Data.reserve(ms_io->ItemsCount);
8142 const int size_before_amends = _Storage.Data.Size;
8143 for (int idx = 0; idx < ms_io->ItemsCount; idx++, _SelectionOrder++)
8144 ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, _SelectionOrder);
8145 ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends);
8146 }
8147 }
8148 else if (req.Type == ImGuiSelectionRequestType_SetRange)
8149 {
8150 const int selection_changes = (int)req.RangeLastItem - (int)req.RangeFirstItem + 1;
8151 //ImGuiContext& g = *GImGui; IMGUI_DEBUG_LOG_SELECTION("Req %d/%d: set %d to %d\n", ms_io->Requests.index_from_ptr(&req), ms_io->Requests.Size, selection_changes, req.Selected);
8152 if (selection_changes == 1 || (selection_changes < Size / 100))
8153 {
8154 // Multiple sorted insertion + copy likely to be faster.
8155 // Technically we could do a single copy with a little more work (sort sequential SetRange requests)
8156 for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++)
8157 SetItemSelected(GetStorageIdFromIndex(idx), req.Selected);
8158 }
8159 else
8160 {
8161 // Append insertion + single sort likely be faster.
8162 // Use req.RangeDirection to set order field so that shift+clicking from 1 to 5 is different than shift+clicking from 5 to 1
8163 const int size_before_amends = _Storage.Data.Size;
8164 int selection_order = _SelectionOrder + ((req.RangeDirection < 0) ? selection_changes - 1 : 0);
8165 for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++, selection_order += req.RangeDirection)
8166 ImGuiSelectionBasicStorage_BatchSetItemSelected(this, GetStorageIdFromIndex(idx), req.Selected, size_before_amends, selection_order);
8167 if (req.Selected)
8168 _SelectionOrder += selection_changes;
8169 ImGuiSelectionBasicStorage_BatchFinish(this, req.Selected, size_before_amends);
8170 }
8171 }
8172 }
8173 }
8174
8175 //-------------------------------------------------------------------------
8176
8177 ImGuiSelectionExternalStorage::ImGuiSelectionExternalStorage()
8178 {
8179 UserData = NULL;
8180 AdapterSetItemSelected = NULL;
8181 }
8182
8183 // Apply requests coming from BeginMultiSelect() and EndMultiSelect().
8184 // We also pull 'ms_io->ItemsCount' as passed for BeginMultiSelect() for consistency with ImGuiSelectionBasicStorage
8185 // This makes no assumption about underlying storage.
8186 void ImGuiSelectionExternalStorage::ApplyRequests(ImGuiMultiSelectIO* ms_io)
8187 {
8188 IM_ASSERT(AdapterSetItemSelected);
8189 for (ImGuiSelectionRequest& req : ms_io->Requests)
8190 {
8191 if (req.Type == ImGuiSelectionRequestType_SetAll)
8192 for (int idx = 0; idx < ms_io->ItemsCount; idx++)
8193 AdapterSetItemSelected(this, idx, req.Selected);
8194 if (req.Type == ImGuiSelectionRequestType_SetRange)
8195 for (int idx = (int)req.RangeFirstItem; idx <= (int)req.RangeLastItem; idx++)
8196 AdapterSetItemSelected(this, idx, req.Selected);
8197 }
8198 }
8199
8200 //-------------------------------------------------------------------------
8201 // [SECTION] Widgets: ListBox
8202 //-------------------------------------------------------------------------
8203 // - BeginListBox()
8204 // - EndListBox()
8205 // - ListBox()
8206 //-------------------------------------------------------------------------
8207
8208 // This is essentially a thin wrapper to using BeginChild/EndChild with the ImGuiChildFlags_FrameStyle flag for stylistic changes + displaying a label.
8209 // This handle some subtleties with capturing info from the label, but for 99% uses it could essentially be rewritten as:
8210 // if (ImGui::BeginChild("...", ImVec2(ImGui::CalcItemWidth(), ImGui::GetTextLineHeight() * 7.5f), ImGuiChildFlags_FrameStyle))
8211 // { .... }
8212 // ImGui::EndChild();
8213 // ImGui::SameLine();
8214 // ImGui::AlignTextToFramePadding();
8215 // ImGui::Text("Label");
8216 // Tip: To have a list filling the entire window width, use size.x = -FLT_MIN and pass an non-visible label e.g. "##empty"
8217 // Tip: If your vertical size is calculated from an item count (e.g. 10 * item_height) consider adding a fractional part to facilitate seeing scrolling boundaries (e.g. 10.25 * item_height).
8218 bool ImGui::BeginListBox(const char* label, const ImVec2& size_arg)
8219 {
8220 ImGuiContext& g = *GImGui;
8221 ImGuiWindow* window = GetCurrentWindow();
8222 if (window->SkipItems)
8223 return false;
8224
8225 const ImGuiStyle& style = g.Style;
8226 const ImGuiID id = GetID(label);
8227 const ImVec2 label_size = CalcTextSize(label, NULL, true);
8228
8229 // Size default to hold ~7.25 items.
8230 // Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
8231 ImVec2 size = ImTrunc(CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.25f + style.FramePadding.y * 2.0f));
8232 ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
8233 ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
8234 ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
8235 g.NextItemData.ClearFlags();
8236
8237 if (!IsRectVisible(bb.Min, bb.Max))
8238 {
8239 ItemSize(bb.GetSize(), style.FramePadding.y);
8240 ItemAdd(bb, 0, &frame_bb);
8241 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
8242 return false;
8243 }
8244
8245 // FIXME-OPT: We could omit the BeginGroup() if label_size.x == 0.0f but would need to omit the EndGroup() as well.
8246 BeginGroup();
8247 if (label_size.x > 0.0f)
8248 {
8249 ImVec2 label_pos = ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y);
8250 RenderText(label_pos, label);
8251 window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, label_pos + label_size);
8252 AlignTextToFramePadding();
8253 }
8254
8255 BeginChild(id, frame_bb.GetSize(), ImGuiChildFlags_FrameStyle);
8256 return true;
8257 }
8258
8259 void ImGui::EndListBox()
8260 {
8261 ImGuiContext& g = *GImGui;
8262 ImGuiWindow* window = g.CurrentWindow;
8263 IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) && "Mismatched BeginListBox/EndListBox calls. Did you test the return value of BeginListBox?");
8264 IM_UNUSED(window);
8265
8266 EndChild();
8267 EndGroup(); // This is only required to be able to do IsItemXXX query on the whole ListBox including label
8268 }
8269
8270 bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
8271 {
8272 const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
8273 return value_changed;
8274 }
8275
8276 // This is merely a helper around BeginListBox(), EndListBox().
8277 // Considering using those directly to submit custom data or store selection differently.
8278 bool ImGui::ListBox(const char* label, int* current_item, const char* (*getter)(void* user_data, int idx), void* user_data, int items_count, int height_in_items)
8279 {
8280 ImGuiContext& g = *GImGui;
8281
8282 // Calculate size from "height_in_items"
8283 if (height_in_items < 0)
8284 height_in_items = ImMin(items_count, 7);
8285 float height_in_items_f = height_in_items + 0.25f;
8286 ImVec2 size(0.0f, ImTrunc(GetTextLineHeightWithSpacing() * height_in_items_f + g.Style.FramePadding.y * 2.0f));
8287
8288 if (!BeginListBox(label, size))
8289 return false;
8290
8291 // Assume all items have even height (= 1 line of text). If you need items of different height,
8292 // you can create a custom version of ListBox() in your code without using the clipper.
8293 bool value_changed = false;
8294 ImGuiListClipper clipper;
8295 clipper.Begin(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to.
8296 clipper.IncludeItemByIndex(*current_item);
8297 while (clipper.Step())
8298 for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
8299 {
8300 const char* item_text = getter(user_data, i);
8301 if (item_text == NULL)
8302 item_text = "*Unknown item*";
8303
8304 PushID(i);
8305 const bool item_selected = (i == *current_item);
8306 if (Selectable(item_text, item_selected))
8307 {
8308 *current_item = i;
8309 value_changed = true;
8310 }
8311 if (item_selected)
8312 SetItemDefaultFocus();
8313 PopID();
8314 }
8315 EndListBox();
8316
8317 if (value_changed)
8318 MarkItemEdited(g.LastItemData.ID);
8319
8320 return value_changed;
8321 }
8322
8323 //-------------------------------------------------------------------------
8324 // [SECTION] Widgets: PlotLines, PlotHistogram
8325 //-------------------------------------------------------------------------
8326 // - PlotEx() [Internal]
8327 // - PlotLines()
8328 // - PlotHistogram()
8329 //-------------------------------------------------------------------------
8330 // Plot/Graph widgets are not very good.
8331 // Consider writing your own, or using a third-party one, see:
8332 // - ImPlot https://github.com/epezent/implot
8333 // - others https://github.com/ocornut/imgui/wiki/Useful-Extensions
8334 //-------------------------------------------------------------------------
8335
8336 int ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, const ImVec2& size_arg)
8337 {
8338 ImGuiContext& g = *GImGui;
8339 ImGuiWindow* window = GetCurrentWindow();
8340 if (window->SkipItems)
8341 return -1;
8342
8343 const ImGuiStyle& style = g.Style;
8344 const ImGuiID id = window->GetID(label);
8345
8346 const ImVec2 label_size = CalcTextSize(label, NULL, true);
8347 const ImVec2 frame_size = CalcItemSize(size_arg, CalcItemWidth(), label_size.y + style.FramePadding.y * 2.0f);
8348
8349 const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
8350 const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
8351 const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0));
8352 ItemSize(total_bb, style.FramePadding.y);
8353 if (!ItemAdd(total_bb, id, &frame_bb, ImGuiItemFlags_NoNav))
8354 return -1;
8355 bool hovered;
8356 ButtonBehavior(frame_bb, id, &hovered, NULL);
8357
8358 // Determine scale from values if not specified
8359 if (scale_min == FLT_MAX || scale_max == FLT_MAX)
8360 {
8361 float v_min = FLT_MAX;
8362 float v_max = -FLT_MAX;
8363 for (int i = 0; i < values_count; i++)
8364 {
8365 const float v = values_getter(data, i);
8366 if (v != v) // Ignore NaN values
8367 continue;
8368 v_min = ImMin(v_min, v);
8369 v_max = ImMax(v_max, v);
8370 }
8371 if (scale_min == FLT_MAX)
8372 scale_min = v_min;
8373 if (scale_max == FLT_MAX)
8374 scale_max = v_max;
8375 }
8376
8377 RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
8378
8379 const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1;
8380 int idx_hovered = -1;
8381 if (values_count >= values_count_min)
8382 {
8383 int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
8384 int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
8385
8386 // Tooltip on hover
8387 if (hovered && inner_bb.Contains(g.IO.MousePos))
8388 {
8389 const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
8390 const int v_idx = (int)(t * item_count);
8391 IM_ASSERT(v_idx >= 0 && v_idx < values_count);
8392
8393 const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
8394 const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
8395 if (plot_type == ImGuiPlotType_Lines)
8396 SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx + 1, v1);
8397 else if (plot_type == ImGuiPlotType_Histogram)
8398 SetTooltip("%d: %8.4g", v_idx, v0);
8399 idx_hovered = v_idx;
8400 }
8401
8402 const float t_step = 1.0f / (float)res_w;
8403 const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min));
8404
8405 float v0 = values_getter(data, (0 + values_offset) % values_count);
8406 float t0 = 0.0f;
8407 ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle
8408 float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (1 + scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
8409
8410 const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
8411 const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
8412
8413 for (int n = 0; n < res_w; n++)
8414 {
8415 const float t1 = t0 + t_step;
8416 const int v1_idx = (int)(t0 * item_count + 0.5f);
8417 IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
8418 const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
8419 const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) );
8420
8421 // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
8422 ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
8423 ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
8424 if (plot_type == ImGuiPlotType_Lines)
8425 {
8426 window->DrawList->AddLine(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base);
8427 }
8428 else if (plot_type == ImGuiPlotType_Histogram)
8429 {
8430 if (pos1.x >= pos0.x + 2.0f)
8431 pos1.x -= 1.0f;
8432 window->DrawList->AddRectFilled(pos0, pos1, idx_hovered == v1_idx ? col_hovered : col_base);
8433 }
8434
8435 t0 = t1;
8436 tp0 = tp1;
8437 }
8438 }
8439
8440 // Text overlay
8441 if (overlay_text)
8442 RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f, 0.0f));
8443
8444 if (label_size.x > 0.0f)
8445 RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
8446
8447 // Return hovered index or -1 if none are hovered.
8448 // This is currently not exposed in the public API because we need a larger redesign of the whole thing, but in the short-term we are making it available in PlotEx().
8449 return idx_hovered;
8450 }
8451
8452 struct ImGuiPlotArrayGetterData
8453 {
8454 const float* Values;
8455 int Stride;
8456
8457 ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
8458 };
8459
8460 static float Plot_ArrayGetter(void* data, int idx)
8461 {
8462 ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
8463 const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
8464 return v;
8465 }
8466
8467 void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
8468 {
8469 ImGuiPlotArrayGetterData data(values, stride);
8470 PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8471 }
8472
8473 void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
8474 {
8475 PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8476 }
8477
8478 void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
8479 {
8480 ImGuiPlotArrayGetterData data(values, stride);
8481 PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8482 }
8483
8484 void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
8485 {
8486 PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
8487 }
8488
8489 //-------------------------------------------------------------------------
8490 // [SECTION] Widgets: Value helpers
8491 // Those is not very useful, legacy API.
8492 //-------------------------------------------------------------------------
8493 // - Value()
8494 //-------------------------------------------------------------------------
8495
8496 void ImGui::Value(const char* prefix, bool b)
8497 {
8498 Text("%s: %s", prefix, (b ? "true" : "false"));
8499 }
8500
8501 void ImGui::Value(const char* prefix, int v)
8502 {
8503 Text("%s: %d", prefix, v);
8504 }
8505
8506 void ImGui::Value(const char* prefix, unsigned int v)
8507 {
8508 Text("%s: %d", prefix, v);
8509 }
8510
8511 void ImGui::Value(const char* prefix, float v, const char* float_format)
8512 {
8513 if (float_format)
8514 {
8515 char fmt[64];
8516 ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
8517 Text(fmt, prefix, v);
8518 }
8519 else
8520 {
8521 Text("%s: %.3f", prefix, v);
8522 }
8523 }
8524
8525 //-------------------------------------------------------------------------
8526 // [SECTION] MenuItem, BeginMenu, EndMenu, etc.
8527 //-------------------------------------------------------------------------
8528 // - ImGuiMenuColumns [Internal]
8529 // - BeginMenuBar()
8530 // - EndMenuBar()
8531 // - BeginMainMenuBar()
8532 // - EndMainMenuBar()
8533 // - BeginMenu()
8534 // - EndMenu()
8535 // - MenuItemEx() [Internal]
8536 // - MenuItem()
8537 //-------------------------------------------------------------------------
8538
8539 // Helpers for internal use
8540 void ImGuiMenuColumns::Update(float spacing, bool window_reappearing)
8541 {
8542 if (window_reappearing)
8543 memset(Widths, 0, sizeof(Widths));
8544 Spacing = (ImU16)spacing;
8545 CalcNextTotalWidth(true);
8546 memset(Widths, 0, sizeof(Widths));
8547 TotalWidth = NextTotalWidth;
8548 NextTotalWidth = 0;
8549 }
8550
8551 void ImGuiMenuColumns::CalcNextTotalWidth(bool update_offsets)
8552 {
8553 ImU16 offset = 0;
8554 bool want_spacing = false;
8555 for (int i = 0; i < IM_ARRAYSIZE(Widths); i++)
8556 {
8557 ImU16 width = Widths[i];
8558 if (want_spacing && width > 0)
8559 offset += Spacing;
8560 want_spacing |= (width > 0);
8561 if (update_offsets)
8562 {
8563 if (i == 1) { OffsetLabel = offset; }
8564 if (i == 2) { OffsetShortcut = offset; }
8565 if (i == 3) { OffsetMark = offset; }
8566 }
8567 offset += width;
8568 }
8569 NextTotalWidth = offset;
8570 }
8571
8572 float ImGuiMenuColumns::DeclColumns(float w_icon, float w_label, float w_shortcut, float w_mark)
8573 {
8574 Widths[0] = ImMax(Widths[0], (ImU16)w_icon);
8575 Widths[1] = ImMax(Widths[1], (ImU16)w_label);
8576 Widths[2] = ImMax(Widths[2], (ImU16)w_shortcut);
8577 Widths[3] = ImMax(Widths[3], (ImU16)w_mark);
8578 CalcNextTotalWidth(false);
8579 return (float)ImMax(TotalWidth, NextTotalWidth);
8580 }
8581
8582 // FIXME: Provided a rectangle perhaps e.g. a BeginMenuBarEx() could be used anywhere..
8583 // Currently the main responsibility of this function being to setup clip-rect + horizontal layout + menu navigation layer.
8584 // Ideally we also want this to be responsible for claiming space out of the main window scrolling rectangle, in which case ImGuiWindowFlags_MenuBar will become unnecessary.
8585 // Then later the same system could be used for multiple menu-bars, scrollbars, side-bars.
8586 bool ImGui::BeginMenuBar()
8587 {
8588 ImGuiWindow* window = GetCurrentWindow();
8589 if (window->SkipItems)
8590 return false;
8591 if (!(window->Flags & ImGuiWindowFlags_MenuBar))
8592 return false;
8593
8594 IM_ASSERT(!window->DC.MenuBarAppending);
8595 BeginGroup(); // Backup position on layer 0 // FIXME: Misleading to use a group for that backup/restore
8596 PushID("##menubar");
8597
8598 // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect.
8599 // We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy.
8600 ImRect bar_rect = window->MenuBarRect();
8601 ImRect clip_rect(IM_ROUND(bar_rect.Min.x + window->WindowBorderSize), IM_ROUND(bar_rect.Min.y + window->WindowBorderSize), IM_ROUND(ImMax(bar_rect.Min.x, bar_rect.Max.x - ImMax(window->WindowRounding, window->WindowBorderSize))), IM_ROUND(bar_rect.Max.y));
8602 clip_rect.ClipWith(window->OuterRectClipped);
8603 PushClipRect(clip_rect.Min, clip_rect.Max, false);
8604
8605 // We overwrite CursorMaxPos because BeginGroup sets it to CursorPos (essentially the .EmitItem hack in EndMenuBar() would need something analogous here, maybe a BeginGroupEx() with flags).
8606 window->DC.CursorPos = window->DC.CursorMaxPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y);
8607 window->DC.LayoutType = ImGuiLayoutType_Horizontal;
8608 window->DC.IsSameLine = false;
8609 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
8610 window->DC.MenuBarAppending = true;
8611 AlignTextToFramePadding();
8612 return true;
8613 }
8614
8615 void ImGui::EndMenuBar()
8616 {
8617 ImGuiWindow* window = GetCurrentWindow();
8618 if (window->SkipItems)
8619 return;
8620 ImGuiContext& g = *GImGui;
8621
8622 // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
8623 if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
8624 {
8625 // Try to find out if the request is for one of our child menu
8626 ImGuiWindow* nav_earliest_child = g.NavWindow;
8627 while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu))
8628 nav_earliest_child = nav_earliest_child->ParentWindow;
8629 if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
8630 {
8631 // To do so we claim focus back, restore NavId and then process the movement request for yet another frame.
8632 // This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth bothering)
8633 const ImGuiNavLayer layer = ImGuiNavLayer_Menu;
8634 IM_ASSERT(window->DC.NavLayersActiveMaskNext & (1 << layer)); // Sanity check (FIXME: Seems unnecessary)
8635 FocusWindow(window);
8636 SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
8637 // FIXME-NAV: How to deal with this when not using g.IO.ConfigNavCursorVisibleAuto?
8638 if (g.NavCursorVisible)
8639 {
8640 g.NavCursorVisible = false; // Hide nav cursor for the current frame so we don't see the intermediary selection. Will be set again
8641 g.NavCursorHideFrames = 2;
8642 }
8643 g.NavHighlightItemUnderNav = g.NavMousePosDirty = true;
8644 NavMoveRequestForward(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags); // Repeat
8645 }
8646 }
8647
8648 IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
8649 IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
8650 IM_ASSERT(window->DC.MenuBarAppending);
8651 PopClipRect();
8652 PopID();
8653 window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->Pos.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos.
8654
8655 // FIXME: Extremely confusing, cleanup by (a) working on WorkRect stack system (b) not using a Group confusingly here.
8656 ImGuiGroupData& group_data = g.GroupStack.back();
8657 group_data.EmitItem = false;
8658 ImVec2 restore_cursor_max_pos = group_data.BackupCursorMaxPos;
8659 window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, window->DC.CursorMaxPos.x - window->Scroll.x); // Convert ideal extents for scrolling layer equivalent.
8660 EndGroup(); // Restore position on layer 0 // FIXME: Misleading to use a group for that backup/restore
8661 window->DC.LayoutType = ImGuiLayoutType_Vertical;
8662 window->DC.IsSameLine = false;
8663 window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
8664 window->DC.MenuBarAppending = false;
8665 window->DC.CursorMaxPos = restore_cursor_max_pos;
8666 }
8667
8668 // Important: calling order matters!
8669 // FIXME: Somehow overlapping with docking tech.
8670 // FIXME: The "rect-cut" aspect of this could be formalized into a lower-level helper (rect-cut: https://halt.software/dead-simple-layouts)
8671 bool ImGui::BeginViewportSideBar(const char* name, ImGuiViewport* viewport_p, ImGuiDir dir, float axis_size, ImGuiWindowFlags window_flags)
8672 {
8673 IM_ASSERT(dir != ImGuiDir_None);
8674
8675 ImGuiWindow* bar_window = FindWindowByName(name);
8676 if (bar_window == NULL || bar_window->BeginCount == 0)
8677 {
8678 // Calculate and set window size/position
8679 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)(viewport_p ? viewport_p : GetMainViewport());
8680 ImRect avail_rect = viewport->GetBuildWorkRect();
8681 ImGuiAxis axis = (dir == ImGuiDir_Up || dir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
8682 ImVec2 pos = avail_rect.Min;
8683 if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
8684 pos[axis] = avail_rect.Max[axis] - axis_size;
8685 ImVec2 size = avail_rect.GetSize();
8686 size[axis] = axis_size;
8687 SetNextWindowPos(pos);
8688 SetNextWindowSize(size);
8689
8690 // Report our size into work area (for next frame) using actual window size
8691 if (dir == ImGuiDir_Up || dir == ImGuiDir_Left)
8692 viewport->BuildWorkInsetMin[axis] += axis_size;
8693 else if (dir == ImGuiDir_Down || dir == ImGuiDir_Right)
8694 viewport->BuildWorkInsetMax[axis] += axis_size;
8695 }
8696
8697 window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
8698 PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
8699 PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0, 0)); // Lift normal size constraint
8700 bool is_open = Begin(name, NULL, window_flags);
8701 PopStyleVar(2);
8702
8703 return is_open;
8704 }
8705
8706 bool ImGui::BeginMainMenuBar()
8707 {
8708 ImGuiContext& g = *GImGui;
8709 ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
8710
8711 // For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set.
8712 // FIXME: This could be generalized as an opt-in way to clamp window->DC.CursorStartPos to avoid SafeArea?
8713 // FIXME: Consider removing support for safe area down the line... it's messy. Nowadays consoles have support for TV calibration in OS settings.
8714 g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f));
8715 ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar;
8716 float height = GetFrameHeight();
8717 bool is_open = BeginViewportSideBar("##MainMenuBar", viewport, ImGuiDir_Up, height, window_flags);
8718 g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f);
8719
8720 if (is_open)
8721 BeginMenuBar();
8722 else
8723 End();
8724 return is_open;
8725 }
8726
8727 void ImGui::EndMainMenuBar()
8728 {
8729 EndMenuBar();
8730
8731 // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
8732 // FIXME: With this strategy we won't be able to restore a NULL focus.
8733 ImGuiContext& g = *GImGui;
8734 if (g.CurrentWindow == g.NavWindow && g.NavLayer == ImGuiNavLayer_Main && !g.NavAnyRequest)
8735 FocusTopMostWindowUnderOne(g.NavWindow, NULL, NULL, ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild);
8736
8737 End();
8738 }
8739
8740 static bool IsRootOfOpenMenuSet()
8741 {
8742 ImGuiContext& g = *GImGui;
8743 ImGuiWindow* window = g.CurrentWindow;
8744 if ((g.OpenPopupStack.Size <= g.BeginPopupStack.Size) || (window->Flags & ImGuiWindowFlags_ChildMenu))
8745 return false;
8746
8747 // Initially we used 'upper_popup->OpenParentId == window->IDStack.back()' to differentiate multiple menu sets from each others
8748 // (e.g. inside menu bar vs loose menu items) based on parent ID.
8749 // This would however prevent the use of e.g. PushID() user code submitting menus.
8750 // Previously this worked between popup and a first child menu because the first child menu always had the _ChildWindow flag,
8751 // making hovering on parent popup possible while first child menu was focused - but this was generally a bug with other side effects.
8752 // Instead we don't treat Popup specifically (in order to consistently support menu features in them), maybe the first child menu of a Popup
8753 // doesn't have the _ChildWindow flag, and we rely on this IsRootOfOpenMenuSet() check to allow hovering between root window/popup and first child menu.
8754 // In the end, lack of ID check made it so we could no longer differentiate between separate menu sets. To compensate for that, we at least check parent window nav layer.
8755 // This fixes the most common case of menu opening on hover when moving between window content and menu bar. Multiple different menu sets in same nav layer would still
8756 // open on hover, but that should be a lesser problem, because if such menus are close in proximity in window content then it won't feel weird and if they are far apart
8757 // it likely won't be a problem anyone runs into.
8758 const ImGuiPopupData* upper_popup = &g.OpenPopupStack[g.BeginPopupStack.Size];
8759 if (window->DC.NavLayerCurrent != upper_popup->ParentNavLayer)
8760 return false;
8761 return upper_popup->Window && (upper_popup->Window->Flags & ImGuiWindowFlags_ChildMenu) && ImGui::IsWindowChildOf(upper_popup->Window, window, true);
8762 }
8763
8764 bool ImGui::BeginMenuEx(const char* label, const char* icon, bool enabled)
8765 {
8766 ImGuiWindow* window = GetCurrentWindow();
8767 if (window->SkipItems)
8768 return false;
8769
8770 ImGuiContext& g = *GImGui;
8771 const ImGuiStyle& style = g.Style;
8772 const ImGuiID id = window->GetID(label);
8773 bool menu_is_open = IsPopupOpen(id, ImGuiPopupFlags_None);
8774
8775 // Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu)
8776 // The first menu in a hierarchy isn't so hovering doesn't get across (otherwise e.g. resizing borders with ImGuiButtonFlags_FlattenChildren would react), but top-most BeginMenu() will bypass that limitation.
8777 ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus;
8778 if (window->Flags & ImGuiWindowFlags_ChildMenu)
8779 window_flags |= ImGuiWindowFlags_ChildWindow;
8780
8781 // If a menu with same the ID was already submitted, we will append to it, matching the behavior of Begin().
8782 // We are relying on a O(N) search - so O(N log N) over the frame - which seems like the most efficient for the expected small amount of BeginMenu() calls per frame.
8783 // If somehow this is ever becoming a problem we can switch to use e.g. ImGuiStorage mapping key to last frame used.
8784 if (g.MenusIdSubmittedThisFrame.contains(id))
8785 {
8786 if (menu_is_open)
8787 menu_is_open = BeginPopupEx(id, window_flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
8788 else
8789 g.NextWindowData.ClearFlags(); // we behave like Begin() and need to consume those values
8790 return menu_is_open;
8791 }
8792
8793 // Tag menu as used. Next time BeginMenu() with same ID is called it will append to existing menu
8794 g.MenusIdSubmittedThisFrame.push_back(id);
8795
8796 ImVec2 label_size = CalcTextSize(label, NULL, true);
8797
8798 // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent without always being a Child window)
8799 // This is only done for items for the menu set and not the full parent window.
8800 const bool menuset_is_open = IsRootOfOpenMenuSet();
8801 if (menuset_is_open)
8802 PushItemFlag(ImGuiItemFlags_NoWindowHoverableCheck, true);
8803
8804 // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu,
8805 // However the final position is going to be different! It is chosen by FindBestWindowPosForPopup().
8806 // e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering.
8807 ImVec2 popup_pos, pos = window->DC.CursorPos;
8808 PushID(label);
8809 if (!enabled)
8810 BeginDisabled();
8811 const ImGuiMenuColumns* offsets = &window->DC.MenuColumns;
8812 bool pressed;
8813
8814 // We use ImGuiSelectableFlags_NoSetKeyOwner to allow down on one menu item, move, up on another.
8815 const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SelectOnClick | ImGuiSelectableFlags_NoAutoClosePopups;
8816 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
8817 {
8818 // Menu inside an horizontal menu bar
8819 // Selectable extend their highlight by half ItemSpacing in each direction.
8820 // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin()
8821 popup_pos = ImVec2(pos.x - 1.0f - IM_TRUNC(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight);
8822 window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f);
8823 PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f);
8824 float w = label_size.x;
8825 ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
8826 pressed = Selectable("", menu_is_open, selectable_flags, ImVec2(w, label_size.y));
8827 LogSetNextTextDecoration("[", "]");
8828 RenderText(text_pos, label);
8829 PopStyleVar();
8830 window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
8831 }
8832 else
8833 {
8834 // Menu inside a regular/vertical menu
8835 // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
8836 // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.
8837 popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
8838 float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f;
8839 float checkmark_w = IM_TRUNC(g.FontSize * 1.20f);
8840 float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, 0.0f, checkmark_w); // Feedback to next frame
8841 float extra_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
8842 ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
8843 pressed = Selectable("", menu_is_open, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y));
8844 LogSetNextTextDecoration("", ">");
8845 RenderText(text_pos, label);
8846 if (icon_w > 0.0f)
8847 RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon);
8848 RenderArrow(window->DrawList, pos + ImVec2(offsets->OffsetMark + extra_w + g.FontSize * 0.30f, 0.0f), GetColorU32(ImGuiCol_Text), ImGuiDir_Right);
8849 }
8850 if (!enabled)
8851 EndDisabled();
8852
8853 const bool hovered = (g.HoveredId == id) && enabled && !g.NavHighlightItemUnderNav;
8854 if (menuset_is_open)
8855 PopItemFlag();
8856
8857 bool want_open = false;
8858 bool want_open_nav_init = false;
8859 bool want_close = false;
8860 if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
8861 {
8862 // Close menu when not hovering it anymore unless we are moving roughly in the direction of the menu
8863 // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
8864 bool moving_toward_child_menu = false;
8865 ImGuiPopupData* child_popup = (g.BeginPopupStack.Size < g.OpenPopupStack.Size) ? &g.OpenPopupStack[g.BeginPopupStack.Size] : NULL; // Popup candidate (testing below)
8866 ImGuiWindow* child_menu_window = (child_popup && child_popup->Window && child_popup->Window->ParentWindow == window) ? child_popup->Window : NULL;
8867 if (g.HoveredWindow == window && child_menu_window != NULL)
8868 {
8869 const float ref_unit = g.FontSize; // FIXME-DPI
8870 const float child_dir = (window->Pos.x < child_menu_window->Pos.x) ? 1.0f : -1.0f;
8871 const ImRect next_window_rect = child_menu_window->Rect();
8872 ImVec2 ta = (g.IO.MousePos - g.IO.MouseDelta);
8873 ImVec2 tb = (child_dir > 0.0f) ? next_window_rect.GetTL() : next_window_rect.GetTR();
8874 ImVec2 tc = (child_dir > 0.0f) ? next_window_rect.GetBL() : next_window_rect.GetBR();
8875 const float pad_farmost_h = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, ref_unit * 0.5f, ref_unit * 2.5f); // Add a bit of extra slack.
8876 ta.x += child_dir * -0.5f;
8877 tb.x += child_dir * ref_unit;
8878 tc.x += child_dir * ref_unit;
8879 tb.y = ta.y + ImMax((tb.y - pad_farmost_h) - ta.y, -ref_unit * 8.0f); // Triangle has maximum height to limit the slope and the bias toward large sub-menus
8880 tc.y = ta.y + ImMin((tc.y + pad_farmost_h) - ta.y, +ref_unit * 8.0f);
8881 moving_toward_child_menu = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
8882 //GetForegroundDrawList()->AddTriangleFilled(ta, tb, tc, moving_toward_child_menu ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); // [DEBUG]
8883 }
8884
8885 // The 'HovereWindow == window' check creates an inconsistency (e.g. moving away from menu slowly tends to hit same window, whereas moving away fast does not)
8886 // But we also need to not close the top-menu menu when moving over void. Perhaps we should extend the triangle check to a larger polygon.
8887 // (Remember to test this on BeginPopup("A")->BeginMenu("B") sequence which behaves slightly differently as B isn't a Child of A and hovering isn't shared.)
8888 if (menu_is_open && !hovered && g.HoveredWindow == window && !moving_toward_child_menu && !g.NavHighlightItemUnderNav && g.ActiveId == 0)
8889 want_close = true;
8890
8891 // Open
8892 // (note: at this point 'hovered' actually includes the NavDisableMouseHover == false test)
8893 if (!menu_is_open && pressed) // Click/activate to open
8894 want_open = true;
8895 else if (!menu_is_open && hovered && !moving_toward_child_menu) // Hover to open
8896 want_open = true;
8897 else if (!menu_is_open && hovered && g.HoveredIdTimer >= 0.30f && g.MouseStationaryTimer >= 0.30f) // Hover to open (timer fallback)
8898 want_open = true;
8899 if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open
8900 {
8901 want_open = want_open_nav_init = true;
8902 NavMoveRequestCancel();
8903 SetNavCursorVisibleAfterMove();
8904 }
8905 }
8906 else
8907 {
8908 // Menu bar
8909 if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it
8910 {
8911 want_close = true;
8912 want_open = menu_is_open = false;
8913 }
8914 else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others
8915 {
8916 want_open = true;
8917 }
8918 else if (g.NavId == id && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open
8919 {
8920 want_open = true;
8921 NavMoveRequestCancel();
8922 }
8923 }
8924
8925 if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }'
8926 want_close = true;
8927 if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None))
8928 ClosePopupToLevel(g.BeginPopupStack.Size, true);
8929
8930 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));
8931 PopID();
8932
8933 if (want_open && !menu_is_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)
8934 {
8935 // Don't reopen/recycle same menu level in the same frame if it is a different menu ID, first close the other menu and yield for a frame.
8936 OpenPopup(label);
8937 }
8938 else if (want_open)
8939 {
8940 menu_is_open = true;
8941 OpenPopup(label, ImGuiPopupFlags_NoReopen);// | (want_open_nav_init ? ImGuiPopupFlags_NoReopenAlwaysNavInit : 0));
8942 }
8943
8944 if (menu_is_open)
8945 {
8946 ImGuiLastItemData last_item_in_parent = g.LastItemData;
8947 SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: misleading: the value will serve as reference for FindBestWindowPosForPopup(), not actual pos.
8948 PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding
8949 menu_is_open = BeginPopupEx(id, window_flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
8950 PopStyleVar();
8951 if (menu_is_open)
8952 {
8953 // Implement what ImGuiPopupFlags_NoReopenAlwaysNavInit would do:
8954 // Perform an init request in the case the popup was already open (via a previous mouse hover)
8955 if (want_open && want_open_nav_init && !g.NavInitRequest)
8956 {
8957 FocusWindow(g.CurrentWindow, ImGuiFocusRequestFlags_UnlessBelowModal);
8958 NavInitWindow(g.CurrentWindow, false);
8959 }
8960
8961 // Restore LastItemData so IsItemXXXX functions can work after BeginMenu()/EndMenu()
8962 // (This fixes using IsItemClicked() and IsItemHovered(), but IsItemHovered() also relies on its support for ImGuiItemFlags_NoWindowHoverableCheck)
8963 g.LastItemData = last_item_in_parent;
8964 if (g.HoveredWindow == window)
8965 g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
8966 }
8967 }
8968 else
8969 {
8970 g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
8971 }
8972
8973 return menu_is_open;
8974 }
8975
8976 bool ImGui::BeginMenu(const char* label, bool enabled)
8977 {
8978 return BeginMenuEx(label, NULL, enabled);
8979 }
8980
8981 void ImGui::EndMenu()
8982 {
8983 // Nav: When a left move request our menu failed, close ourselves.
8984 ImGuiContext& g = *GImGui;
8985 ImGuiWindow* window = g.CurrentWindow;
8986 IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginMenu()/EndMenu() calls
8987 ImGuiWindow* parent_window = window->ParentWindow; // Should always be != NULL is we passed assert.
8988 if (window->BeginCount == window->BeginCountPreviousFrame)
8989 if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet())
8990 if (g.NavWindow && (g.NavWindow->RootWindowForNav == window) && parent_window->DC.LayoutType == ImGuiLayoutType_Vertical)
8991 {
8992 ClosePopupToLevel(g.BeginPopupStack.Size - 1, true);
8993 NavMoveRequestCancel();
8994 }
8995
8996 EndPopup();
8997 }
8998
8999 bool ImGui::MenuItemEx(const char* label, const char* icon, const char* shortcut, bool selected, bool enabled)
9000 {
9001 ImGuiWindow* window = GetCurrentWindow();
9002 if (window->SkipItems)
9003 return false;
9004
9005 ImGuiContext& g = *GImGui;
9006 ImGuiStyle& style = g.Style;
9007 ImVec2 pos = window->DC.CursorPos;
9008 ImVec2 label_size = CalcTextSize(label, NULL, true);
9009
9010 // See BeginMenuEx() for comments about this.
9011 const bool menuset_is_open = IsRootOfOpenMenuSet();
9012 if (menuset_is_open)
9013 PushItemFlag(ImGuiItemFlags_NoWindowHoverableCheck, true);
9014
9015 // We've been using the equivalent of ImGuiSelectableFlags_SetNavIdOnHover on all Selectable() since early Nav system days (commit 43ee5d73),
9016 // but I am unsure whether this should be kept at all. For now moved it to be an opt-in feature used by menus only.
9017 bool pressed;
9018 PushID(label);
9019 if (!enabled)
9020 BeginDisabled();
9021
9022 // We use ImGuiSelectableFlags_NoSetKeyOwner to allow down on one menu item, move, up on another.
9023 const ImGuiSelectableFlags selectable_flags = ImGuiSelectableFlags_SelectOnRelease | ImGuiSelectableFlags_NoSetKeyOwner | ImGuiSelectableFlags_SetNavIdOnHover;
9024 const ImGuiMenuColumns* offsets = &window->DC.MenuColumns;
9025 if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9026 {
9027 // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
9028 // Note that in this situation: we don't render the shortcut, we render a highlight instead of the selected tick mark.
9029 float w = label_size.x;
9030 window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * 0.5f);
9031 ImVec2 text_pos(window->DC.CursorPos.x + offsets->OffsetLabel, window->DC.CursorPos.y + window->DC.CurrLineTextBaseOffset);
9032 PushStyleVarX(ImGuiStyleVar_ItemSpacing, style.ItemSpacing.x * 2.0f);
9033 pressed = Selectable("", selected, selectable_flags, ImVec2(w, 0.0f));
9034 PopStyleVar();
9035 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible)
9036 RenderText(text_pos, label);
9037 window->DC.CursorPos.x += IM_TRUNC(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
9038 }
9039 else
9040 {
9041 // Menu item inside a vertical menu
9042 // (In a typical menu window where all items are BeginMenu() or MenuItem() calls, extra_w will always be 0.0f.
9043 // Only when they are other items sticking out we're going to add spacing, yet only register minimum width into the layout system.
9044 float icon_w = (icon && icon[0]) ? CalcTextSize(icon, NULL).x : 0.0f;
9045 float shortcut_w = (shortcut && shortcut[0]) ? CalcTextSize(shortcut, NULL).x : 0.0f;
9046 float checkmark_w = IM_TRUNC(g.FontSize * 1.20f);
9047 float min_w = window->DC.MenuColumns.DeclColumns(icon_w, label_size.x, shortcut_w, checkmark_w); // Feedback for next frame
9048 float stretch_w = ImMax(0.0f, GetContentRegionAvail().x - min_w);
9049 pressed = Selectable("", false, selectable_flags | ImGuiSelectableFlags_SpanAvailWidth, ImVec2(min_w, label_size.y));
9050 if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible)
9051 {
9052 RenderText(pos + ImVec2(offsets->OffsetLabel, 0.0f), label);
9053 if (icon_w > 0.0f)
9054 RenderText(pos + ImVec2(offsets->OffsetIcon, 0.0f), icon);
9055 if (shortcut_w > 0.0f)
9056 {
9057 PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);
9058 LogSetNextTextDecoration("(", ")");
9059 RenderText(pos + ImVec2(offsets->OffsetShortcut + stretch_w, 0.0f), shortcut, NULL, false);
9060 PopStyleColor();
9061 }
9062 if (selected)
9063 RenderCheckMark(window->DrawList, pos + ImVec2(offsets->OffsetMark + stretch_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(ImGuiCol_Text), g.FontSize * 0.866f);
9064 }
9065 }
9066 IMGUI_TEST_ENGINE_ITEM_INFO(g.LastItemData.ID, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0));
9067 if (!enabled)
9068 EndDisabled();
9069 PopID();
9070 if (menuset_is_open)
9071 PopItemFlag();
9072
9073 return pressed;
9074 }
9075
9076 bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
9077 {
9078 return MenuItemEx(label, NULL, shortcut, selected, enabled);
9079 }
9080
9081 bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
9082 {
9083 if (MenuItemEx(label, NULL, shortcut, p_selected ? *p_selected : false, enabled))
9084 {
9085 if (p_selected)
9086 *p_selected = !*p_selected;
9087 return true;
9088 }
9089 return false;
9090 }
9091
9092 //-------------------------------------------------------------------------
9093 // [SECTION] Widgets: BeginTabBar, EndTabBar, etc.
9094 //-------------------------------------------------------------------------
9095 // - BeginTabBar()
9096 // - BeginTabBarEx() [Internal]
9097 // - EndTabBar()
9098 // - TabBarLayout() [Internal]
9099 // - TabBarCalcTabID() [Internal]
9100 // - TabBarCalcMaxTabWidth() [Internal]
9101 // - TabBarFindTabById() [Internal]
9102 // - TabBarFindTabByOrder() [Internal]
9103 // - TabBarGetCurrentTab() [Internal]
9104 // - TabBarGetTabName() [Internal]
9105 // - TabBarRemoveTab() [Internal]
9106 // - TabBarCloseTab() [Internal]
9107 // - TabBarScrollClamp() [Internal]
9108 // - TabBarScrollToTab() [Internal]
9109 // - TabBarQueueFocus() [Internal]
9110 // - TabBarQueueReorder() [Internal]
9111 // - TabBarProcessReorderFromMousePos() [Internal]
9112 // - TabBarProcessReorder() [Internal]
9113 // - TabBarScrollingButtons() [Internal]
9114 // - TabBarTabListPopupButton() [Internal]
9115 //-------------------------------------------------------------------------
9116
9117 struct ImGuiTabBarSection
9118 {
9119 int TabCount; // Number of tabs in this section.
9120 float Width; // Sum of width of tabs in this section (after shrinking down)
9121 float Spacing; // Horizontal spacing at the end of the section.
9122
9123 ImGuiTabBarSection() { memset(this, 0, sizeof(*this)); }
9124 };
9125
9126 namespace ImGui
9127 {
9128 static void TabBarLayout(ImGuiTabBar* tab_bar);
9129 static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window);
9130 static float TabBarCalcMaxTabWidth();
9131 static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling);
9132 static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections);
9133 static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar);
9134 static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar);
9135 }
9136
9137 ImGuiTabBar::ImGuiTabBar()
9138 {
9139 memset(this, 0, sizeof(*this));
9140 CurrFrameVisible = PrevFrameVisible = -1;
9141 LastTabItemIdx = -1;
9142 }
9143
9144 static inline int TabItemGetSectionIdx(const ImGuiTabItem* tab)
9145 {
9146 return (tab->Flags & ImGuiTabItemFlags_Leading) ? 0 : (tab->Flags & ImGuiTabItemFlags_Trailing) ? 2 : 1;
9147 }
9148
9149 static int IMGUI_CDECL TabItemComparerBySection(const void* lhs, const void* rhs)
9150 {
9151 const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;
9152 const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;
9153 const int a_section = TabItemGetSectionIdx(a);
9154 const int b_section = TabItemGetSectionIdx(b);
9155 if (a_section != b_section)
9156 return a_section - b_section;
9157 return (int)(a->IndexDuringLayout - b->IndexDuringLayout);
9158 }
9159
9160 static int IMGUI_CDECL TabItemComparerByBeginOrder(const void* lhs, const void* rhs)
9161 {
9162 const ImGuiTabItem* a = (const ImGuiTabItem*)lhs;
9163 const ImGuiTabItem* b = (const ImGuiTabItem*)rhs;
9164 return (int)(a->BeginOrder - b->BeginOrder);
9165 }
9166
9167 static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiPtrOrIndex& ref)
9168 {
9169 ImGuiContext& g = *GImGui;
9170 return ref.Ptr ? (ImGuiTabBar*)ref.Ptr : g.TabBars.GetByIndex(ref.Index);
9171 }
9172
9173 static ImGuiPtrOrIndex GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar)
9174 {
9175 ImGuiContext& g = *GImGui;
9176 if (g.TabBars.Contains(tab_bar))
9177 return ImGuiPtrOrIndex(g.TabBars.GetIndex(tab_bar));
9178 return ImGuiPtrOrIndex(tab_bar);
9179 }
9180
9181 bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags)
9182 {
9183 ImGuiContext& g = *GImGui;
9184 ImGuiWindow* window = g.CurrentWindow;
9185 if (window->SkipItems)
9186 return false;
9187
9188 ImGuiID id = window->GetID(str_id);
9189 ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id);
9190 ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->WorkRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2);
9191 tab_bar->ID = id;
9192 tab_bar->SeparatorMinX = tab_bar->BarRect.Min.x - IM_TRUNC(window->WindowPadding.x * 0.5f);
9193 tab_bar->SeparatorMaxX = tab_bar->BarRect.Max.x + IM_TRUNC(window->WindowPadding.x * 0.5f);
9194 //if (g.NavWindow && IsWindowChildOf(g.NavWindow, window, false, false))
9195 flags |= ImGuiTabBarFlags_IsFocused;
9196 return BeginTabBarEx(tab_bar, tab_bar_bb, flags);
9197 }
9198
9199 bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags)
9200 {
9201 ImGuiContext& g = *GImGui;
9202 ImGuiWindow* window = g.CurrentWindow;
9203 if (window->SkipItems)
9204 return false;
9205
9206 IM_ASSERT(tab_bar->ID != 0);
9207 if ((flags & ImGuiTabBarFlags_DockNode) == 0)
9208 PushOverrideID(tab_bar->ID);
9209
9210 // Add to stack
9211 g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar));
9212 g.CurrentTabBar = tab_bar;
9213 tab_bar->Window = window;
9214
9215 // Append with multiple BeginTabBar()/EndTabBar() pairs.
9216 tab_bar->BackupCursorPos = window->DC.CursorPos;
9217 if (tab_bar->CurrFrameVisible == g.FrameCount)
9218 {
9219 window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY);
9220 tab_bar->BeginCount++;
9221 return true;
9222 }
9223
9224 // Ensure correct ordering when toggling ImGuiTabBarFlags_Reorderable flag, or when a new tab was added while being not reorderable
9225 if ((flags & ImGuiTabBarFlags_Reorderable) != (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) || (tab_bar->TabsAddedNew && !(flags & ImGuiTabBarFlags_Reorderable)))
9226 ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByBeginOrder);
9227 tab_bar->TabsAddedNew = false;
9228
9229 // Flags
9230 if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
9231 flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
9232
9233 tab_bar->Flags = flags;
9234 tab_bar->BarRect = tab_bar_bb;
9235 tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab()
9236 tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible;
9237 tab_bar->CurrFrameVisible = g.FrameCount;
9238 tab_bar->PrevTabsContentsHeight = tab_bar->CurrTabsContentsHeight;
9239 tab_bar->CurrTabsContentsHeight = 0.0f;
9240 tab_bar->ItemSpacingY = g.Style.ItemSpacing.y;
9241 tab_bar->FramePadding = g.Style.FramePadding;
9242 tab_bar->TabsActiveCount = 0;
9243 tab_bar->LastTabItemIdx = -1;
9244 tab_bar->BeginCount = 1;
9245
9246 // Set cursor pos in a way which only be used in the off-chance the user erroneously submits item before BeginTabItem(): items will overlap
9247 window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.y + tab_bar->ItemSpacingY);
9248
9249 // Draw separator
9250 // (it would be misleading to draw this in EndTabBar() suggesting that it may be drawn over tabs, as tab bar are appendable)
9251 const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected);
9252 if (g.Style.TabBarBorderSize > 0.0f)
9253 {
9254 const float y = tab_bar->BarRect.Max.y;
9255 window->DrawList->AddRectFilled(ImVec2(tab_bar->SeparatorMinX, y - g.Style.TabBarBorderSize), ImVec2(tab_bar->SeparatorMaxX, y), col);
9256 }
9257 return true;
9258 }
9259
9260 void ImGui::EndTabBar()
9261 {
9262 ImGuiContext& g = *GImGui;
9263 ImGuiWindow* window = g.CurrentWindow;
9264 if (window->SkipItems)
9265 return;
9266
9267 ImGuiTabBar* tab_bar = g.CurrentTabBar;
9268 if (tab_bar == NULL)
9269 {
9270 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Mismatched BeginTabBar()/EndTabBar()!");
9271 return;
9272 }
9273
9274 // Fallback in case no TabItem have been submitted
9275 if (tab_bar->WantLayout)
9276 TabBarLayout(tab_bar);
9277
9278 // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed().
9279 const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
9280 if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing)
9281 {
9282 tab_bar->CurrTabsContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, tab_bar->CurrTabsContentsHeight);
9283 window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->CurrTabsContentsHeight;
9284 }
9285 else
9286 {
9287 window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->PrevTabsContentsHeight;
9288 }
9289 if (tab_bar->BeginCount > 1)
9290 window->DC.CursorPos = tab_bar->BackupCursorPos;
9291
9292 tab_bar->LastTabItemIdx = -1;
9293 if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0)
9294 PopID();
9295
9296 g.CurrentTabBarStack.pop_back();
9297 g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back());
9298 }
9299
9300 // Scrolling happens only in the central section (leading/trailing sections are not scrolling)
9301 static float TabBarCalcScrollableWidth(ImGuiTabBar* tab_bar, ImGuiTabBarSection* sections)
9302 {
9303 return tab_bar->BarRect.GetWidth() - sections[0].Width - sections[2].Width - sections[1].Spacing;
9304 }
9305
9306 // This is called only once a frame before by the first call to ItemTab()
9307 // The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions.
9308 static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar)
9309 {
9310 ImGuiContext& g = *GImGui;
9311 tab_bar->WantLayout = false;
9312
9313 // Garbage collect by compacting list
9314 // Detect if we need to sort out tab list (e.g. in rare case where a tab changed section)
9315 int tab_dst_n = 0;
9316 bool need_sort_by_section = false;
9317 ImGuiTabBarSection sections[3]; // Layout sections: Leading, Central, Trailing
9318 for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++)
9319 {
9320 ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n];
9321 if (tab->LastFrameVisible < tab_bar->PrevFrameVisible || tab->WantClose)
9322 {
9323 // Remove tab
9324 if (tab_bar->VisibleTabId == tab->ID) { tab_bar->VisibleTabId = 0; }
9325 if (tab_bar->SelectedTabId == tab->ID) { tab_bar->SelectedTabId = 0; }
9326 if (tab_bar->NextSelectedTabId == tab->ID) { tab_bar->NextSelectedTabId = 0; }
9327 continue;
9328 }
9329 if (tab_dst_n != tab_src_n)
9330 tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n];
9331
9332 tab = &tab_bar->Tabs[tab_dst_n];
9333 tab->IndexDuringLayout = (ImS16)tab_dst_n;
9334
9335 // We will need sorting if tabs have changed section (e.g. moved from one of Leading/Central/Trailing to another)
9336 int curr_tab_section_n = TabItemGetSectionIdx(tab);
9337 if (tab_dst_n > 0)
9338 {
9339 ImGuiTabItem* prev_tab = &tab_bar->Tabs[tab_dst_n - 1];
9340 int prev_tab_section_n = TabItemGetSectionIdx(prev_tab);
9341 if (curr_tab_section_n == 0 && prev_tab_section_n != 0)
9342 need_sort_by_section = true;
9343 if (prev_tab_section_n == 2 && curr_tab_section_n != 2)
9344 need_sort_by_section = true;
9345 }
9346
9347 sections[curr_tab_section_n].TabCount++;
9348 tab_dst_n++;
9349 }
9350 if (tab_bar->Tabs.Size != tab_dst_n)
9351 tab_bar->Tabs.resize(tab_dst_n);
9352
9353 if (need_sort_by_section)
9354 ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerBySection);
9355
9356 // Calculate spacing between sections
9357 sections[0].Spacing = sections[0].TabCount > 0 && (sections[1].TabCount + sections[2].TabCount) > 0 ? g.Style.ItemInnerSpacing.x : 0.0f;
9358 sections[1].Spacing = sections[1].TabCount > 0 && sections[2].TabCount > 0 ? g.Style.ItemInnerSpacing.x : 0.0f;
9359
9360 // Setup next selected tab
9361 ImGuiID scroll_to_tab_id = 0;
9362 if (tab_bar->NextSelectedTabId)
9363 {
9364 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId;
9365 tab_bar->NextSelectedTabId = 0;
9366 scroll_to_tab_id = tab_bar->SelectedTabId;
9367 }
9368
9369 // Process order change request (we could probably process it when requested but it's just saner to do it in a single spot).
9370 if (tab_bar->ReorderRequestTabId != 0)
9371 {
9372 if (TabBarProcessReorder(tab_bar))
9373 if (tab_bar->ReorderRequestTabId == tab_bar->SelectedTabId)
9374 scroll_to_tab_id = tab_bar->ReorderRequestTabId;
9375 tab_bar->ReorderRequestTabId = 0;
9376 }
9377
9378 // Tab List Popup (will alter tab_bar->BarRect and therefore the available width!)
9379 const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0;
9380 if (tab_list_popup_button)
9381 if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Min.x!
9382 scroll_to_tab_id = tab_bar->SelectedTabId = tab_to_select->ID;
9383
9384 // Leading/Trailing tabs will be shrink only if central one aren't visible anymore, so layout the shrink data as: leading, trailing, central
9385 // (whereas our tabs are stored as: leading, central, trailing)
9386 int shrink_buffer_indexes[3] = { 0, sections[0].TabCount + sections[2].TabCount, sections[0].TabCount };
9387 g.ShrinkWidthBuffer.resize(tab_bar->Tabs.Size);
9388
9389 // Compute ideal tabs widths + store them into shrink buffer
9390 ImGuiTabItem* most_recently_selected_tab = NULL;
9391 int curr_section_n = -1;
9392 bool found_selected_tab_id = false;
9393 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
9394 {
9395 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
9396 IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible);
9397
9398 if ((most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) && !(tab->Flags & ImGuiTabItemFlags_Button))
9399 most_recently_selected_tab = tab;
9400 if (tab->ID == tab_bar->SelectedTabId)
9401 found_selected_tab_id = true;
9402 if (scroll_to_tab_id == 0 && g.NavJustMovedToId == tab->ID)
9403 scroll_to_tab_id = tab->ID;
9404
9405 // Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar.
9406 // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet,
9407 // and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window.
9408 const char* tab_name = TabBarGetTabName(tab_bar, tab);
9409 const bool has_close_button_or_unsaved_marker = (tab->Flags & ImGuiTabItemFlags_NoCloseButton) == 0 || (tab->Flags & ImGuiTabItemFlags_UnsavedDocument);
9410 tab->ContentWidth = (tab->RequestedWidth >= 0.0f) ? tab->RequestedWidth : TabItemCalcSize(tab_name, has_close_button_or_unsaved_marker).x;
9411
9412 int section_n = TabItemGetSectionIdx(tab);
9413 ImGuiTabBarSection* section = &sections[section_n];
9414 section->Width += tab->ContentWidth + (section_n == curr_section_n ? g.Style.ItemInnerSpacing.x : 0.0f);
9415 curr_section_n = section_n;
9416
9417 // Store data so we can build an array sorted by width if we need to shrink tabs down
9418 IM_MSVC_WARNING_SUPPRESS(6385);
9419 ImGuiShrinkWidthItem* shrink_width_item = &g.ShrinkWidthBuffer[shrink_buffer_indexes[section_n]++];
9420 shrink_width_item->Index = tab_n;
9421 shrink_width_item->Width = shrink_width_item->InitialWidth = tab->ContentWidth;
9422 tab->Width = ImMax(tab->ContentWidth, 1.0f);
9423 }
9424
9425 // Compute total ideal width (used for e.g. auto-resizing a window)
9426 tab_bar->WidthAllTabsIdeal = 0.0f;
9427 for (int section_n = 0; section_n < 3; section_n++)
9428 tab_bar->WidthAllTabsIdeal += sections[section_n].Width + sections[section_n].Spacing;
9429
9430 // Horizontal scrolling buttons
9431 // (note that TabBarScrollButtons() will alter BarRect.Max.x)
9432 if ((tab_bar->WidthAllTabsIdeal > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll))
9433 if (ImGuiTabItem* scroll_and_select_tab = TabBarScrollingButtons(tab_bar))
9434 {
9435 scroll_to_tab_id = scroll_and_select_tab->ID;
9436 if ((scroll_and_select_tab->Flags & ImGuiTabItemFlags_Button) == 0)
9437 tab_bar->SelectedTabId = scroll_to_tab_id;
9438 }
9439
9440 // Shrink widths if full tabs don't fit in their allocated space
9441 float section_0_w = sections[0].Width + sections[0].Spacing;
9442 float section_1_w = sections[1].Width + sections[1].Spacing;
9443 float section_2_w = sections[2].Width + sections[2].Spacing;
9444 bool central_section_is_visible = (section_0_w + section_2_w) < tab_bar->BarRect.GetWidth();
9445 float width_excess;
9446 if (central_section_is_visible)
9447 width_excess = ImMax(section_1_w - (tab_bar->BarRect.GetWidth() - section_0_w - section_2_w), 0.0f); // Excess used to shrink central section
9448 else
9449 width_excess = (section_0_w + section_2_w) - tab_bar->BarRect.GetWidth(); // Excess used to shrink leading/trailing section
9450
9451 // With ImGuiTabBarFlags_FittingPolicyScroll policy, we will only shrink leading/trailing if the central section is not visible anymore
9452 if (width_excess >= 1.0f && ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown) || !central_section_is_visible))
9453 {
9454 int shrink_data_count = (central_section_is_visible ? sections[1].TabCount : sections[0].TabCount + sections[2].TabCount);
9455 int shrink_data_offset = (central_section_is_visible ? sections[0].TabCount + sections[2].TabCount : 0);
9456 ShrinkWidths(g.ShrinkWidthBuffer.Data + shrink_data_offset, shrink_data_count, width_excess);
9457
9458 // Apply shrunk values into tabs and sections
9459 for (int tab_n = shrink_data_offset; tab_n < shrink_data_offset + shrink_data_count; tab_n++)
9460 {
9461 ImGuiTabItem* tab = &tab_bar->Tabs[g.ShrinkWidthBuffer[tab_n].Index];
9462 float shrinked_width = IM_TRUNC(g.ShrinkWidthBuffer[tab_n].Width);
9463 if (shrinked_width < 0.0f)
9464 continue;
9465
9466 shrinked_width = ImMax(1.0f, shrinked_width);
9467 int section_n = TabItemGetSectionIdx(tab);
9468 sections[section_n].Width -= (tab->Width - shrinked_width);
9469 tab->Width = shrinked_width;
9470 }
9471 }
9472
9473 // Layout all active tabs
9474 int section_tab_index = 0;
9475 float tab_offset = 0.0f;
9476 tab_bar->WidthAllTabs = 0.0f;
9477 for (int section_n = 0; section_n < 3; section_n++)
9478 {
9479 ImGuiTabBarSection* section = &sections[section_n];
9480 if (section_n == 2)
9481 tab_offset = ImMin(ImMax(0.0f, tab_bar->BarRect.GetWidth() - section->Width), tab_offset);
9482
9483 for (int tab_n = 0; tab_n < section->TabCount; tab_n++)
9484 {
9485 ImGuiTabItem* tab = &tab_bar->Tabs[section_tab_index + tab_n];
9486 tab->Offset = tab_offset;
9487 tab->NameOffset = -1;
9488 tab_offset += tab->Width + (tab_n < section->TabCount - 1 ? g.Style.ItemInnerSpacing.x : 0.0f);
9489 }
9490 tab_bar->WidthAllTabs += ImMax(section->Width + section->Spacing, 0.0f);
9491 tab_offset += section->Spacing;
9492 section_tab_index += section->TabCount;
9493 }
9494
9495 // Clear name buffers
9496 tab_bar->TabsNames.Buf.resize(0);
9497
9498 // If we have lost the selected tab, select the next most recently active one
9499 if (found_selected_tab_id == false)
9500 tab_bar->SelectedTabId = 0;
9501 if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL)
9502 scroll_to_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID;
9503
9504 // Lock in visible tab
9505 tab_bar->VisibleTabId = tab_bar->SelectedTabId;
9506 tab_bar->VisibleTabWasSubmitted = false;
9507
9508 // Apply request requests
9509 if (scroll_to_tab_id != 0)
9510 TabBarScrollToTab(tab_bar, scroll_to_tab_id, sections);
9511 else if ((tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll) && IsMouseHoveringRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, true) && IsWindowContentHoverable(g.CurrentWindow))
9512 {
9513 const float wheel = g.IO.MouseWheelRequestAxisSwap ? g.IO.MouseWheel : g.IO.MouseWheelH;
9514 const ImGuiKey wheel_key = g.IO.MouseWheelRequestAxisSwap ? ImGuiKey_MouseWheelY : ImGuiKey_MouseWheelX;
9515 if (TestKeyOwner(wheel_key, tab_bar->ID) && wheel != 0.0f)
9516 {
9517 const float scroll_step = wheel * TabBarCalcScrollableWidth(tab_bar, sections) / 3.0f;
9518 tab_bar->ScrollingTargetDistToVisibility = 0.0f;
9519 tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget - scroll_step);
9520 }
9521 SetKeyOwner(wheel_key, tab_bar->ID);
9522 }
9523
9524 // Update scrolling
9525 tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim);
9526 tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget);
9527 if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget)
9528 {
9529 // Scrolling speed adjust itself so we can always reach our target in 1/3 seconds.
9530 // Teleport if we are aiming far off the visible line
9531 tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize);
9532 tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f);
9533 const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize);
9534 tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed);
9535 }
9536 else
9537 {
9538 tab_bar->ScrollingSpeed = 0.0f;
9539 }
9540 tab_bar->ScrollingRectMinX = tab_bar->BarRect.Min.x + sections[0].Width + sections[0].Spacing;
9541 tab_bar->ScrollingRectMaxX = tab_bar->BarRect.Max.x - sections[2].Width - sections[1].Spacing;
9542
9543 // Actual layout in host window (we don't do it in BeginTabBar() so as not to waste an extra frame)
9544 ImGuiWindow* window = g.CurrentWindow;
9545 window->DC.CursorPos = tab_bar->BarRect.Min;
9546 ItemSize(ImVec2(tab_bar->WidthAllTabs, tab_bar->BarRect.GetHeight()), tab_bar->FramePadding.y);
9547 window->DC.IdealMaxPos.x = ImMax(window->DC.IdealMaxPos.x, tab_bar->BarRect.Min.x + tab_bar->WidthAllTabsIdeal);
9548 }
9549
9550 // Dockable windows uses Name/ID in the global namespace. Non-dockable items use the ID stack.
9551 static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label, ImGuiWindow* docked_window)
9552 {
9553 IM_ASSERT(docked_window == NULL); // master branch only
9554 IM_UNUSED(docked_window);
9555 if (tab_bar->Flags & ImGuiTabBarFlags_DockNode)
9556 {
9557 ImGuiID id = ImHashStr(label);
9558 KeepAliveID(id);
9559 return id;
9560 }
9561 else
9562 {
9563 ImGuiWindow* window = GImGui->CurrentWindow;
9564 return window->GetID(label);
9565 }
9566 }
9567
9568 static float ImGui::TabBarCalcMaxTabWidth()
9569 {
9570 ImGuiContext& g = *GImGui;
9571 return g.FontSize * 20.0f;
9572 }
9573
9574 ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id)
9575 {
9576 if (tab_id != 0)
9577 for (int n = 0; n < tab_bar->Tabs.Size; n++)
9578 if (tab_bar->Tabs[n].ID == tab_id)
9579 return &tab_bar->Tabs[n];
9580 return NULL;
9581 }
9582
9583 // Order = visible order, not submission order! (which is tab->BeginOrder)
9584 ImGuiTabItem* ImGui::TabBarFindTabByOrder(ImGuiTabBar* tab_bar, int order)
9585 {
9586 if (order < 0 || order >= tab_bar->Tabs.Size)
9587 return NULL;
9588 return &tab_bar->Tabs[order];
9589 }
9590
9591 ImGuiTabItem* ImGui::TabBarGetCurrentTab(ImGuiTabBar* tab_bar)
9592 {
9593 if (tab_bar->LastTabItemIdx < 0 || tab_bar->LastTabItemIdx >= tab_bar->Tabs.Size)
9594 return NULL;
9595 return &tab_bar->Tabs[tab_bar->LastTabItemIdx];
9596 }
9597
9598 const char* ImGui::TabBarGetTabName(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
9599 {
9600 if (tab->NameOffset == -1)
9601 return "N/A";
9602 IM_ASSERT(tab->NameOffset < tab_bar->TabsNames.Buf.Size);
9603 return tab_bar->TabsNames.Buf.Data + tab->NameOffset;
9604 }
9605
9606 // The *TabId fields are already set by the docking system _before_ the actual TabItem was created, so we clear them regardless.
9607 void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id)
9608 {
9609 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))
9610 tab_bar->Tabs.erase(tab);
9611 if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; }
9612 if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; }
9613 if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; }
9614 }
9615
9616 // Called on manual closure attempt
9617 void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
9618 {
9619 if (tab->Flags & ImGuiTabItemFlags_Button)
9620 return; // A button appended with TabItemButton().
9621
9622 if ((tab->Flags & (ImGuiTabItemFlags_UnsavedDocument | ImGuiTabItemFlags_NoAssumedClosure)) == 0)
9623 {
9624 // This will remove a frame of lag for selecting another tab on closure.
9625 // However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure
9626 tab->WantClose = true;
9627 if (tab_bar->VisibleTabId == tab->ID)
9628 {
9629 tab->LastFrameVisible = -1;
9630 tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0;
9631 }
9632 }
9633 else
9634 {
9635 // Actually select before expecting closure attempt (on an UnsavedDocument tab user is expect to e.g. show a popup)
9636 if (tab_bar->VisibleTabId != tab->ID)
9637 TabBarQueueFocus(tab_bar, tab);
9638 }
9639 }
9640
9641 static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling)
9642 {
9643 scrolling = ImMin(scrolling, tab_bar->WidthAllTabs - tab_bar->BarRect.GetWidth());
9644 return ImMax(scrolling, 0.0f);
9645 }
9646
9647 // Note: we may scroll to tab that are not selected! e.g. using keyboard arrow keys
9648 static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiID tab_id, ImGuiTabBarSection* sections)
9649 {
9650 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id);
9651 if (tab == NULL)
9652 return;
9653 if (tab->Flags & ImGuiTabItemFlags_SectionMask_)
9654 return;
9655
9656 ImGuiContext& g = *GImGui;
9657 float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar)
9658 int order = TabBarGetTabOrder(tab_bar, tab);
9659
9660 // Scrolling happens only in the central section (leading/trailing sections are not scrolling)
9661 float scrollable_width = TabBarCalcScrollableWidth(tab_bar, sections);
9662
9663 // We make all tabs positions all relative Sections[0].Width to make code simpler
9664 float tab_x1 = tab->Offset - sections[0].Width + (order > sections[0].TabCount - 1 ? -margin : 0.0f);
9665 float tab_x2 = tab->Offset - sections[0].Width + tab->Width + (order + 1 < tab_bar->Tabs.Size - sections[2].TabCount ? margin : 1.0f);
9666 tab_bar->ScrollingTargetDistToVisibility = 0.0f;
9667 if (tab_bar->ScrollingTarget > tab_x1 || (tab_x2 - tab_x1 >= scrollable_width))
9668 {
9669 // Scroll to the left
9670 tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f);
9671 tab_bar->ScrollingTarget = tab_x1;
9672 }
9673 else if (tab_bar->ScrollingTarget < tab_x2 - scrollable_width)
9674 {
9675 // Scroll to the right
9676 tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - scrollable_width) - tab_bar->ScrollingAnim, 0.0f);
9677 tab_bar->ScrollingTarget = tab_x2 - scrollable_width;
9678 }
9679 }
9680
9681 void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, ImGuiTabItem* tab)
9682 {
9683 tab_bar->NextSelectedTabId = tab->ID;
9684 }
9685
9686 void ImGui::TabBarQueueFocus(ImGuiTabBar* tab_bar, const char* tab_name)
9687 {
9688 IM_ASSERT((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0); // Only supported for manual/explicit tab bars
9689 ImGuiID tab_id = TabBarCalcTabID(tab_bar, tab_name, NULL);
9690 tab_bar->NextSelectedTabId = tab_id;
9691 }
9692
9693 void ImGui::TabBarQueueReorder(ImGuiTabBar* tab_bar, ImGuiTabItem* tab, int offset)
9694 {
9695 IM_ASSERT(offset != 0);
9696 IM_ASSERT(tab_bar->ReorderRequestTabId == 0);
9697 tab_bar->ReorderRequestTabId = tab->ID;
9698 tab_bar->ReorderRequestOffset = (ImS16)offset;
9699 }
9700
9701 void ImGui::TabBarQueueReorderFromMousePos(ImGuiTabBar* tab_bar, ImGuiTabItem* src_tab, ImVec2 mouse_pos)
9702 {
9703 ImGuiContext& g = *GImGui;
9704 IM_ASSERT(tab_bar->ReorderRequestTabId == 0);
9705 if ((tab_bar->Flags & ImGuiTabBarFlags_Reorderable) == 0)
9706 return;
9707
9708 const bool is_central_section = (src_tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0;
9709 const float bar_offset = tab_bar->BarRect.Min.x - (is_central_section ? tab_bar->ScrollingTarget : 0);
9710
9711 // Count number of contiguous tabs we are crossing over
9712 const int dir = (bar_offset + src_tab->Offset) > mouse_pos.x ? -1 : +1;
9713 const int src_idx = tab_bar->Tabs.index_from_ptr(src_tab);
9714 int dst_idx = src_idx;
9715 for (int i = src_idx; i >= 0 && i < tab_bar->Tabs.Size; i += dir)
9716 {
9717 // Reordered tabs must share the same section
9718 const ImGuiTabItem* dst_tab = &tab_bar->Tabs[i];
9719 if (dst_tab->Flags & ImGuiTabItemFlags_NoReorder)
9720 break;
9721 if ((dst_tab->Flags & ImGuiTabItemFlags_SectionMask_) != (src_tab->Flags & ImGuiTabItemFlags_SectionMask_))
9722 break;
9723 dst_idx = i;
9724
9725 // Include spacing after tab, so when mouse cursor is between tabs we would not continue checking further tabs that are not hovered.
9726 const float x1 = bar_offset + dst_tab->Offset - g.Style.ItemInnerSpacing.x;
9727 const float x2 = bar_offset + dst_tab->Offset + dst_tab->Width + g.Style.ItemInnerSpacing.x;
9728 //GetForegroundDrawList()->AddRect(ImVec2(x1, tab_bar->BarRect.Min.y), ImVec2(x2, tab_bar->BarRect.Max.y), IM_COL32(255, 0, 0, 255));
9729 if ((dir < 0 && mouse_pos.x > x1) || (dir > 0 && mouse_pos.x < x2))
9730 break;
9731 }
9732
9733 if (dst_idx != src_idx)
9734 TabBarQueueReorder(tab_bar, src_tab, dst_idx - src_idx);
9735 }
9736
9737 bool ImGui::TabBarProcessReorder(ImGuiTabBar* tab_bar)
9738 {
9739 ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId);
9740 if (tab1 == NULL || (tab1->Flags & ImGuiTabItemFlags_NoReorder))
9741 return false;
9742
9743 //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools
9744 int tab2_order = TabBarGetTabOrder(tab_bar, tab1) + tab_bar->ReorderRequestOffset;
9745 if (tab2_order < 0 || tab2_order >= tab_bar->Tabs.Size)
9746 return false;
9747
9748 // Reordered tabs must share the same section
9749 // (Note: TabBarQueueReorderFromMousePos() also has a similar test but since we allow direct calls to TabBarQueueReorder() we do it here too)
9750 ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order];
9751 if (tab2->Flags & ImGuiTabItemFlags_NoReorder)
9752 return false;
9753 if ((tab1->Flags & ImGuiTabItemFlags_SectionMask_) != (tab2->Flags & ImGuiTabItemFlags_SectionMask_))
9754 return false;
9755
9756 ImGuiTabItem item_tmp = *tab1;
9757 ImGuiTabItem* src_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 + 1 : tab2;
9758 ImGuiTabItem* dst_tab = (tab_bar->ReorderRequestOffset > 0) ? tab1 : tab2 + 1;
9759 const int move_count = (tab_bar->ReorderRequestOffset > 0) ? tab_bar->ReorderRequestOffset : -tab_bar->ReorderRequestOffset;
9760 memmove(dst_tab, src_tab, move_count * sizeof(ImGuiTabItem));
9761 *tab2 = item_tmp;
9762
9763 if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings)
9764 MarkIniSettingsDirty();
9765 return true;
9766 }
9767
9768 static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar)
9769 {
9770 ImGuiContext& g = *GImGui;
9771 ImGuiWindow* window = g.CurrentWindow;
9772
9773 const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f);
9774 const float scrolling_buttons_width = arrow_button_size.x * 2.0f;
9775
9776 const ImVec2 backup_cursor_pos = window->DC.CursorPos;
9777 //window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255));
9778
9779 int select_dir = 0;
9780 ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
9781 arrow_col.w *= 0.5f;
9782
9783 PushStyleColor(ImGuiCol_Text, arrow_col);
9784 PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
9785 PushItemFlag(ImGuiItemFlags_ButtonRepeat, true);
9786 const float backup_repeat_delay = g.IO.KeyRepeatDelay;
9787 const float backup_repeat_rate = g.IO.KeyRepeatRate;
9788 g.IO.KeyRepeatDelay = 0.250f;
9789 g.IO.KeyRepeatRate = 0.200f;
9790 float x = ImMax(tab_bar->BarRect.Min.x, tab_bar->BarRect.Max.x - scrolling_buttons_width);
9791 window->DC.CursorPos = ImVec2(x, tab_bar->BarRect.Min.y);
9792 if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick))
9793 select_dir = -1;
9794 window->DC.CursorPos = ImVec2(x + arrow_button_size.x, tab_bar->BarRect.Min.y);
9795 if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick))
9796 select_dir = +1;
9797 PopItemFlag();
9798 PopStyleColor(2);
9799 g.IO.KeyRepeatRate = backup_repeat_rate;
9800 g.IO.KeyRepeatDelay = backup_repeat_delay;
9801
9802 ImGuiTabItem* tab_to_scroll_to = NULL;
9803 if (select_dir != 0)
9804 if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
9805 {
9806 int selected_order = TabBarGetTabOrder(tab_bar, tab_item);
9807 int target_order = selected_order + select_dir;
9808
9809 // Skip tab item buttons until another tab item is found or end is reached
9810 while (tab_to_scroll_to == NULL)
9811 {
9812 // If we are at the end of the list, still scroll to make our tab visible
9813 tab_to_scroll_to = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order];
9814
9815 // Cross through buttons
9816 // (even if first/last item is a button, return it so we can update the scroll)
9817 if (tab_to_scroll_to->Flags & ImGuiTabItemFlags_Button)
9818 {
9819 target_order += select_dir;
9820 selected_order += select_dir;
9821 tab_to_scroll_to = (target_order < 0 || target_order >= tab_bar->Tabs.Size) ? tab_to_scroll_to : NULL;
9822 }
9823 }
9824 }
9825 window->DC.CursorPos = backup_cursor_pos;
9826 tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f;
9827
9828 return tab_to_scroll_to;
9829 }
9830
9831 static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar)
9832 {
9833 ImGuiContext& g = *GImGui;
9834 ImGuiWindow* window = g.CurrentWindow;
9835
9836 // We use g.Style.FramePadding.y to match the square ArrowButton size
9837 const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y;
9838 const ImVec2 backup_cursor_pos = window->DC.CursorPos;
9839 window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y);
9840 tab_bar->BarRect.Min.x += tab_list_popup_button_width;
9841
9842 ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text];
9843 arrow_col.w *= 0.5f;
9844 PushStyleColor(ImGuiCol_Text, arrow_col);
9845 PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
9846 bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview | ImGuiComboFlags_HeightLargest);
9847 PopStyleColor(2);
9848
9849 ImGuiTabItem* tab_to_select = NULL;
9850 if (open)
9851 {
9852 for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
9853 {
9854 ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
9855 if (tab->Flags & ImGuiTabItemFlags_Button)
9856 continue;
9857
9858 const char* tab_name = TabBarGetTabName(tab_bar, tab);
9859 if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID))
9860 tab_to_select = tab;
9861 }
9862 EndCombo();
9863 }
9864
9865 window->DC.CursorPos = backup_cursor_pos;
9866 return tab_to_select;
9867 }
9868
9869 //-------------------------------------------------------------------------
9870 // [SECTION] Widgets: BeginTabItem, EndTabItem, etc.
9871 //-------------------------------------------------------------------------
9872 // - BeginTabItem()
9873 // - EndTabItem()
9874 // - TabItemButton()
9875 // - TabItemEx() [Internal]
9876 // - SetTabItemClosed()
9877 // - TabItemCalcSize() [Internal]
9878 // - TabItemBackground() [Internal]
9879 // - TabItemLabelAndCloseButton() [Internal]
9880 //-------------------------------------------------------------------------
9881
9882 bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags)
9883 {
9884 ImGuiContext& g = *GImGui;
9885 ImGuiWindow* window = g.CurrentWindow;
9886 if (window->SkipItems)
9887 return false;
9888
9889 ImGuiTabBar* tab_bar = g.CurrentTabBar;
9890 if (tab_bar == NULL)
9891 {
9892 IM_ASSERT_USER_ERROR(tab_bar, "Needs to be called between BeginTabBar() and EndTabBar()!");
9893 return false;
9894 }
9895 IM_ASSERT(!(flags & ImGuiTabItemFlags_Button)); // BeginTabItem() Can't be used with button flags, use TabItemButton() instead!
9896
9897 bool ret = TabItemEx(tab_bar, label, p_open, flags, NULL);
9898 if (ret && !(flags & ImGuiTabItemFlags_NoPushId))
9899 {
9900 ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
9901 PushOverrideID(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label)
9902 }
9903 return ret;
9904 }
9905
9906 void ImGui::EndTabItem()
9907 {
9908 ImGuiContext& g = *GImGui;
9909 ImGuiWindow* window = g.CurrentWindow;
9910 if (window->SkipItems)
9911 return;
9912
9913 ImGuiTabBar* tab_bar = g.CurrentTabBar;
9914 if (tab_bar == NULL)
9915 {
9916 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!");
9917 return;
9918 }
9919 IM_ASSERT(tab_bar->LastTabItemIdx >= 0);
9920 ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx];
9921 if (!(tab->Flags & ImGuiTabItemFlags_NoPushId))
9922 PopID();
9923 }
9924
9925 bool ImGui::TabItemButton(const char* label, ImGuiTabItemFlags flags)
9926 {
9927 ImGuiContext& g = *GImGui;
9928 ImGuiWindow* window = g.CurrentWindow;
9929 if (window->SkipItems)
9930 return false;
9931
9932 ImGuiTabBar* tab_bar = g.CurrentTabBar;
9933 if (tab_bar == NULL)
9934 {
9935 IM_ASSERT_USER_ERROR(tab_bar != NULL, "Needs to be called between BeginTabBar() and EndTabBar()!");
9936 return false;
9937 }
9938 return TabItemEx(tab_bar, label, NULL, flags | ImGuiTabItemFlags_Button | ImGuiTabItemFlags_NoReorder, NULL);
9939 }
9940
9941 bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags, ImGuiWindow* docked_window)
9942 {
9943 // Layout whole tab bar if not already done
9944 ImGuiContext& g = *GImGui;
9945 if (tab_bar->WantLayout)
9946 {
9947 ImGuiNextItemData backup_next_item_data = g.NextItemData;
9948 TabBarLayout(tab_bar);
9949 g.NextItemData = backup_next_item_data;
9950 }
9951 ImGuiWindow* window = g.CurrentWindow;
9952 if (window->SkipItems)
9953 return false;
9954
9955 const ImGuiStyle& style = g.Style;
9956 const ImGuiID id = TabBarCalcTabID(tab_bar, label, docked_window);
9957
9958 // If the user called us with *p_open == false, we early out and don't render.
9959 // We make a call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID.
9960 IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags);
9961 if (p_open && !*p_open)
9962 {
9963 ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav);
9964 return false;
9965 }
9966
9967 IM_ASSERT(!p_open || !(flags & ImGuiTabItemFlags_Button));
9968 IM_ASSERT((flags & (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)) != (ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_Trailing)); // Can't use both Leading and Trailing
9969
9970 // Store into ImGuiTabItemFlags_NoCloseButton, also honor ImGuiTabItemFlags_NoCloseButton passed by user (although not documented)
9971 if (flags & ImGuiTabItemFlags_NoCloseButton)
9972 p_open = NULL;
9973 else if (p_open == NULL)
9974 flags |= ImGuiTabItemFlags_NoCloseButton;
9975
9976 // Acquire tab data
9977 ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, id);
9978 bool tab_is_new = false;
9979 if (tab == NULL)
9980 {
9981 tab_bar->Tabs.push_back(ImGuiTabItem());
9982 tab = &tab_bar->Tabs.back();
9983 tab->ID = id;
9984 tab_bar->TabsAddedNew = tab_is_new = true;
9985 }
9986 tab_bar->LastTabItemIdx = (ImS16)tab_bar->Tabs.index_from_ptr(tab);
9987
9988 // Calculate tab contents size
9989 ImVec2 size = TabItemCalcSize(label, (p_open != NULL) || (flags & ImGuiTabItemFlags_UnsavedDocument));
9990 tab->RequestedWidth = -1.0f;
9991 if (g.NextItemData.HasFlags & ImGuiNextItemDataFlags_HasWidth)
9992 size.x = tab->RequestedWidth = g.NextItemData.Width;
9993 if (tab_is_new)
9994 tab->Width = ImMax(1.0f, size.x);
9995 tab->ContentWidth = size.x;
9996 tab->BeginOrder = tab_bar->TabsActiveCount++;
9997
9998 const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount);
9999 const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0;
10000 const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount);
10001 const bool tab_just_unsaved = (flags & ImGuiTabItemFlags_UnsavedDocument) && !(tab->Flags & ImGuiTabItemFlags_UnsavedDocument);
10002 const bool is_tab_button = (flags & ImGuiTabItemFlags_Button) != 0;
10003 tab->LastFrameVisible = g.FrameCount;
10004 tab->Flags = flags;
10005
10006 // Append name _WITH_ the zero-terminator
10007 if (docked_window != NULL)
10008 {
10009 IM_ASSERT(docked_window == NULL); // master branch only
10010 }
10011 else
10012 {
10013 tab->NameOffset = (ImS32)tab_bar->TabsNames.size();
10014 tab_bar->TabsNames.append(label, label + strlen(label) + 1);
10015 }
10016
10017 // Update selected tab
10018 if (!is_tab_button)
10019 {
10020 if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0)
10021 if (!tab_bar_appearing || tab_bar->SelectedTabId == 0)
10022 TabBarQueueFocus(tab_bar, tab); // New tabs gets activated
10023 if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // _SetSelected can only be passed on explicit tab bar
10024 TabBarQueueFocus(tab_bar, tab);
10025 }
10026
10027 // Lock visibility
10028 // (Note: tab_contents_visible != tab_selected... because CTRL+TAB operations may preview some tabs without selecting them!)
10029 bool tab_contents_visible = (tab_bar->VisibleTabId == id);
10030 if (tab_contents_visible)
10031 tab_bar->VisibleTabWasSubmitted = true;
10032
10033 // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches
10034 if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing)
10035 if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs))
10036 tab_contents_visible = true;
10037
10038 // Note that tab_is_new is not necessarily the same as tab_appearing! When a tab bar stops being submitted
10039 // and then gets submitted again, the tabs will have 'tab_appearing=true' but 'tab_is_new=false'.
10040 if (tab_appearing && (!tab_bar_appearing || tab_is_new))
10041 {
10042 ItemAdd(ImRect(), id, NULL, ImGuiItemFlags_NoNav);
10043 if (is_tab_button)
10044 return false;
10045 return tab_contents_visible;
10046 }
10047
10048 if (tab_bar->SelectedTabId == id)
10049 tab->LastFrameSelected = g.FrameCount;
10050
10051 // Backup current layout position
10052 const ImVec2 backup_main_cursor_pos = window->DC.CursorPos;
10053
10054 // Layout
10055 const bool is_central_section = (tab->Flags & ImGuiTabItemFlags_SectionMask_) == 0;
10056 size.x = tab->Width;
10057 if (is_central_section)
10058 window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(IM_TRUNC(tab->Offset - tab_bar->ScrollingAnim), 0.0f);
10059 else
10060 window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2(tab->Offset, 0.0f);
10061 ImVec2 pos = window->DC.CursorPos;
10062 ImRect bb(pos, pos + size);
10063
10064 // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation)
10065 const bool want_clip_rect = is_central_section && (bb.Min.x < tab_bar->ScrollingRectMinX || bb.Max.x > tab_bar->ScrollingRectMaxX);
10066 if (want_clip_rect)
10067 PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->ScrollingRectMinX), bb.Min.y - 1), ImVec2(tab_bar->ScrollingRectMaxX, bb.Max.y), true);
10068
10069 ImVec2 backup_cursor_max_pos = window->DC.CursorMaxPos;
10070 ItemSize(bb.GetSize(), style.FramePadding.y);
10071 window->DC.CursorMaxPos = backup_cursor_max_pos;
10072
10073 if (!ItemAdd(bb, id))
10074 {
10075 if (want_clip_rect)
10076 PopClipRect();
10077 window->DC.CursorPos = backup_main_cursor_pos;
10078 return tab_contents_visible;
10079 }
10080
10081 // Click to Select a tab
10082 // Allow the close button to overlap
10083 ImGuiButtonFlags button_flags = ((is_tab_button ? ImGuiButtonFlags_PressedOnClickRelease : ImGuiButtonFlags_PressedOnClick) | ImGuiButtonFlags_AllowOverlap);
10084 if (g.DragDropActive)
10085 button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
10086 bool hovered, held;
10087 bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);
10088 if (pressed && !is_tab_button)
10089 TabBarQueueFocus(tab_bar, tab);
10090
10091 // Drag and drop: re-order tabs
10092 if (held && !tab_appearing && IsMouseDragging(0))
10093 {
10094 if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable))
10095 {
10096 // While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x
10097 if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x)
10098 {
10099 TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos);
10100 }
10101 else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x)
10102 {
10103 TabBarQueueReorderFromMousePos(tab_bar, tab, g.IO.MousePos);
10104 }
10105 }
10106 }
10107
10108 #if 0
10109 if (hovered && g.HoveredIdNotActiveTimer > TOOLTIP_DELAY && bb.GetWidth() < tab->ContentWidth)
10110 {
10111 // Enlarge tab display when hovering
10112 bb.Max.x = bb.Min.x + IM_TRUNC(ImLerp(bb.GetWidth(), tab->ContentWidth, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f)));
10113 display_draw_list = GetForegroundDrawList(window);
10114 TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive));
10115 }
10116 #endif
10117
10118 // Render tab shape
10119 ImDrawList* display_draw_list = window->DrawList;
10120 const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabSelected : ImGuiCol_TabDimmedSelected) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabDimmed));
10121 TabItemBackground(display_draw_list, bb, flags, tab_col);
10122 if (tab_contents_visible && (tab_bar->Flags & ImGuiTabBarFlags_DrawSelectedOverline) && style.TabBarOverlineSize > 0.0f)
10123 {
10124 float x_offset = IM_TRUNC(0.4f * style.TabRounding);
10125 if (x_offset < 2.0f * g.CurrentDpiScale)
10126 x_offset = 0.0f;
10127 float y_offset = 1.0f * g.CurrentDpiScale;
10128 display_draw_list->AddLine(bb.GetTL() + ImVec2(x_offset, y_offset), bb.GetTR() + ImVec2(-x_offset, y_offset), GetColorU32(tab_bar_focused ? ImGuiCol_TabSelectedOverline : ImGuiCol_TabDimmedSelectedOverline), style.TabBarOverlineSize);
10129 }
10130 RenderNavCursor(bb, id);
10131
10132 // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget.
10133 const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup);
10134 if (tab_bar->SelectedTabId != tab->ID && hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1)) && !is_tab_button)
10135 TabBarQueueFocus(tab_bar, tab);
10136
10137 if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
10138 flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
10139
10140 // Render tab label, process close button
10141 const ImGuiID close_button_id = p_open ? GetIDWithSeed("#CLOSE", NULL, id) : 0;
10142 bool just_closed;
10143 bool text_clipped;
10144 TabItemLabelAndCloseButton(display_draw_list, bb, tab_just_unsaved ? (flags & ~ImGuiTabItemFlags_UnsavedDocument) : flags, tab_bar->FramePadding, label, id, close_button_id, tab_contents_visible, &just_closed, &text_clipped);
10145 if (just_closed && p_open != NULL)
10146 {
10147 *p_open = false;
10148 TabBarCloseTab(tab_bar, tab);
10149 }
10150
10151 // Restore main window position so user can draw there
10152 if (want_clip_rect)
10153 PopClipRect();
10154 window->DC.CursorPos = backup_main_cursor_pos;
10155
10156 // Tooltip
10157 // (Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer-> seems ok)
10158 // (We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar, which g.HoveredId ignores)
10159 // FIXME: This is a mess.
10160 // FIXME: We may want disabled tab to still display the tooltip?
10161 if (text_clipped && g.HoveredId == id && !held)
10162 if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip) && !(tab->Flags & ImGuiTabItemFlags_NoTooltip))
10163 SetItemTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label);
10164
10165 IM_ASSERT(!is_tab_button || !(tab_bar->SelectedTabId == tab->ID && is_tab_button)); // TabItemButton should not be selected
10166 if (is_tab_button)
10167 return pressed;
10168 return tab_contents_visible;
10169 }
10170
10171 // [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed.
10172 // To use it to need to call the function SetTabItemClosed() between BeginTabBar() and EndTabBar().
10173 // Tabs closed by the close button will automatically be flagged to avoid this issue.
10174 void ImGui::SetTabItemClosed(const char* label)
10175 {
10176 ImGuiContext& g = *GImGui;
10177 bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode);
10178 if (is_within_manual_tab_bar)
10179 {
10180 ImGuiTabBar* tab_bar = g.CurrentTabBar;
10181 ImGuiID tab_id = TabBarCalcTabID(tab_bar, label, NULL);
10182 if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id))
10183 tab->WantClose = true; // Will be processed by next call to TabBarLayout()
10184 }
10185 }
10186
10187 ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button_or_unsaved_marker)
10188 {
10189 ImGuiContext& g = *GImGui;
10190 ImVec2 label_size = CalcTextSize(label, NULL, true);
10191 ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f);
10192 if (has_close_button_or_unsaved_marker)
10193 size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle.
10194 else
10195 size.x += g.Style.FramePadding.x + 1.0f;
10196 return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y);
10197 }
10198
10199 ImVec2 ImGui::TabItemCalcSize(ImGuiWindow*)
10200 {
10201 IM_ASSERT(0); // This function exists to facilitate merge with 'docking' branch.
10202 return ImVec2(0.0f, 0.0f);
10203 }
10204
10205 void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col)
10206 {
10207 // While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it.
10208 ImGuiContext& g = *GImGui;
10209 const float width = bb.GetWidth();
10210 IM_UNUSED(flags);
10211 IM_ASSERT(width > 0.0f);
10212 const float rounding = ImMax(0.0f, ImMin((flags & ImGuiTabItemFlags_Button) ? g.Style.FrameRounding : g.Style.TabRounding, width * 0.5f - 1.0f));
10213 const float y1 = bb.Min.y + 1.0f;
10214 const float y2 = bb.Max.y - g.Style.TabBarBorderSize;
10215 draw_list->PathLineTo(ImVec2(bb.Min.x, y2));
10216 draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9);
10217 draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12);
10218 draw_list->PathLineTo(ImVec2(bb.Max.x, y2));
10219 draw_list->PathFillConvex(col);
10220 if (g.Style.TabBorderSize > 0.0f)
10221 {
10222 draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2));
10223 draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9);
10224 draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12);
10225 draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2));
10226 draw_list->PathStroke(GetColorU32(ImGuiCol_Border), 0, g.Style.TabBorderSize);
10227 }
10228 }
10229
10230 // Render text label (with custom clipping) + Unsaved Document marker + Close Button logic
10231 // We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter.
10232 void ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id, bool is_contents_visible, bool* out_just_closed, bool* out_text_clipped)
10233 {
10234 ImGuiContext& g = *GImGui;
10235 ImVec2 label_size = CalcTextSize(label, NULL, true);
10236
10237 if (out_just_closed)
10238 *out_just_closed = false;
10239 if (out_text_clipped)
10240 *out_text_clipped = false;
10241
10242 if (bb.GetWidth() <= 1.0f)
10243 return;
10244
10245 // In Style V2 we'll have full override of all colors per state (e.g. focused, selected)
10246 // But right now if you want to alter text color of tabs this is what you need to do.
10247 #if 0
10248 const float backup_alpha = g.Style.Alpha;
10249 if (!is_contents_visible)
10250 g.Style.Alpha *= 0.7f;
10251 #endif
10252
10253 // Render text label (with clipping + alpha gradient) + unsaved marker
10254 ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y);
10255 ImRect text_ellipsis_clip_bb = text_pixel_clip_bb;
10256
10257 // Return clipped state ignoring the close button
10258 if (out_text_clipped)
10259 {
10260 *out_text_clipped = (text_ellipsis_clip_bb.Min.x + label_size.x) > text_pixel_clip_bb.Max.x;
10261 //draw_list->AddCircle(text_ellipsis_clip_bb.Min, 3.0f, *out_text_clipped ? IM_COL32(255, 0, 0, 255) : IM_COL32(0, 255, 0, 255));
10262 }
10263
10264 const float button_sz = g.FontSize;
10265 const ImVec2 button_pos(ImMax(bb.Min.x, bb.Max.x - frame_padding.x - button_sz), bb.Min.y + frame_padding.y);
10266
10267 // Close Button & Unsaved Marker
10268 // We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap()
10269 // 'hovered' will be true when hovering the Tab but NOT when hovering the close button
10270 // 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button
10271 // 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false
10272 bool close_button_pressed = false;
10273 bool close_button_visible = false;
10274 if (close_button_id != 0)
10275 if (is_contents_visible || bb.GetWidth() >= ImMax(button_sz, g.Style.TabMinWidthForCloseButton))
10276 if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == tab_id || g.ActiveId == close_button_id)
10277 close_button_visible = true;
10278 bool unsaved_marker_visible = (flags & ImGuiTabItemFlags_UnsavedDocument) != 0 && (button_pos.x + button_sz <= bb.Max.x);
10279
10280 if (close_button_visible)
10281 {
10282 ImGuiLastItemData last_item_backup = g.LastItemData;
10283 if (CloseButton(close_button_id, button_pos))
10284 close_button_pressed = true;
10285 g.LastItemData = last_item_backup;
10286
10287 // Close with middle mouse button
10288 if (!(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2))
10289 close_button_pressed = true;
10290 }
10291 else if (unsaved_marker_visible)
10292 {
10293 const ImRect bullet_bb(button_pos, button_pos + ImVec2(button_sz, button_sz));
10294 RenderBullet(draw_list, bullet_bb.GetCenter(), GetColorU32(ImGuiCol_Text));
10295 }
10296
10297 // This is all rather complicated
10298 // (the main idea is that because the close button only appears on hover, we don't want it to alter the ellipsis position)
10299 // FIXME: if FramePadding is noticeably large, ellipsis_max_x will be wrong here (e.g. #3497), maybe for consistency that parameter of RenderTextEllipsis() shouldn't exist..
10300 float ellipsis_max_x = close_button_visible ? text_pixel_clip_bb.Max.x : bb.Max.x - 1.0f;
10301 if (close_button_visible || unsaved_marker_visible)
10302 {
10303 text_pixel_clip_bb.Max.x -= close_button_visible ? (button_sz) : (button_sz * 0.80f);
10304 text_ellipsis_clip_bb.Max.x -= unsaved_marker_visible ? (button_sz * 0.80f) : 0.0f;
10305 ellipsis_max_x = text_pixel_clip_bb.Max.x;
10306 }
10307 LogSetNextTextDecoration("/", "\\");
10308 RenderTextEllipsis(draw_list, text_ellipsis_clip_bb.Min, text_ellipsis_clip_bb.Max, text_pixel_clip_bb.Max.x, ellipsis_max_x, label, NULL, &label_size);
10309
10310 #if 0
10311 if (!is_contents_visible)
10312 g.Style.Alpha = backup_alpha;
10313 #endif
10314
10315 if (out_just_closed)
10316 *out_just_closed = close_button_pressed;
10317 }
10318
10319
10320 #endif // #ifndef IMGUI_DISABLE